Camel Component: Jetty - 6.3

Talend ESB Mediation Developer Guide

EnrichVersion
6.3
EnrichProdName
Talend Data Fabric
Talend Data Services Platform
Talend ESB
Talend MDM Platform
Talend Open Studio for ESB
Talend Real-Time Big Data Platform
task
Design and Development
EnrichPlatform
Talend ESB

The jetty component provides HTTP-based endpoints for consuming HTTP requests. That is, the Jetty component behaves as a simple Web server. Jetty can also be used as a http client which mean you can also use it with Camel as a Producer.

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>
   <!-- use the same version as your Camel core version -->
   <version>x.x.x</version>
</dependency>

Note Jetty 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 Exchange.HTTP_RESPONSE_CODE data multiple times (for example, 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.

URI format

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

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

Options

Name

Default Value

Description

sessionSupport

false

Specifies whether to enable the session manager on the server side of Jetty.

httpClient.XXX

null

Configuration of Jetty's HttpClient . For example, setting httpClient.idleTimeout=30000 sets the idle timeout to 30 seconds.

httpClient

null

To use a shared HttpClient for all producers created by this endpoint. This option should only be used in special circumstances.

httpClientMinThreads

null

Starting with Camel 2.11: (Producer only): To set a value for minimum number of threads in the HttpClient thread pool. This setting overrides any setting configured at the component level. Notice that both a min and max size must be configured.

httpClientMaxThreads

null

Starting with Camel 2.11: (Producer only): To set a value for maximum number of threads in HttpClient thread pool. This setting overrides any setting configured at the component level. Notice that both a min and max size must be configured.

httpBindingRef

null

Reference to an Camel HttpBinding object in the Registry . HttpBinding can be used to customize how a response should be written for the consumer.

jettyHttpBindingRef

null

Reference to a Camel JettyHttpBinding object in the Registry . JettyHttpBinding can be used to customize how a response should be written for the producer.

matchOnUriPrefix

false

Whether or not the CamelServlet should try to find a target consumer by matching the URI prefix if no exact match is found. See here How do I let Jetty match wildcards.

handlers

null

Specifies a comma-delimited set of org.mortbay.jetty.Handler instances in your Registry (such as your Spring ApplicationContext). These handlers are added to the Jetty servlet context (for example, to add security).

chunked

true

If this option is false Jetty servlet will disable the HTTP streaming and set the content-length header on the response

enableJmx

false

If this option is true, Jetty JMX support will be enabled for this endpoint. See Jetty JMX support for more details.

disableStreamCache

false

Determines whether or not the raw input stream from Jetty is cached or not (Camel will read the stream into a in memory/overflow to file, Stream Caching ) cache. By default Camel will cache the Jetty 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. DefaultHttpBinding will copy the request input stream into a stream cache and put it into message body if this option is false to support reading the stream multiple times. If you use [Jetty] to bridge/proxy an endpoint then consider enabling this option to improve performance, in case you do not need to read the message payload multiple times.

throwExceptionOnFailure

true

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

transferException

false

Camel 2.6: 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.

bridgeEndpoint

false

If the option is true, HttpProducer 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 HttpProducer send all the fault response back. If the option is true, HttpProducer and CamelServlet will skip the gzip processing if the content-encoding is "gzip". Also consider setting *disableStreamCache* to true to optimize when bridging.

enableMultipartFilter

true

Whether Jetty org.eclipse. jetty.servlets. MultiPartFilter is enabled or not. You should set this value to false when bridging endpoints, to ensure multipart requests is proxied/bridged as well.

multipartFilterRef

null

Allows using a custom multipart filter. Note: setting multipartFilterRef forces the value of enableMultipartFilter to true .

filtersRef

null

Allows using a custom filter which is put into a list and can be found in the Registry

continuationTimeout

null

Allows to set a timeout in milliseconds when using Camel Component: Jetty as consumer (server). By default Jetty uses 30000. You can use a value of <= 0 to never expire. If a timeout occurs then the request will be expired and Jetty will return back a http error 503 to the client. This option is only in use when using Camel Component: Jetty with the Asynchronous Routing Engine .

useContinuation

true

Whether or not to use Jetty continuations for the Jetty Server.

sslContextParametersRef

null

Reference to an org.apache.camel.util.jsse. SSLContextParameters object in the Camel Registry. This reference overrides any configured SSLContextParameters at the component level.

traceEnabled

false

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

headerFilterStrategy

null

Starting with Camel 2.11: Reference to a instance of HeaderFilterStrategy in the Registry. It will be used to apply the custom headerFilterStrategy on the new create HttpJettyEndpoint.

urlRewrite

null

*Camel 2.11:* *Producer only* Refers to a custom UrlRewrite which allows you to rewrite urls when you bridge/proxy endpoints.

responseBufferSize

null

Camel 2.12: To use a custom buffer size on the javax.servlet.ServletResponse.

proxyHost

null

Camel 2.11:Producer only The http proxy Host url which will be used by Jetty client.

proxyPort

null

Camel 2.11:Producer only The http proxy port which will be used by Jetty client.

sendServerVersion

true

Camel 2.13: if the option is true, jetty will send the server header with the jetty version information to the client which sends the request. NOTE please make sure there is no any other camel-jetty endpoint is share the same port, otherwise this option may not work as expected.

SendDateHeader

false

Camel 2.14: if the option is true, jetty server will send the date header to the client which sends the request. NOTE please make sure there is no any other camel-jetty endpoint is share the same port, otherwise this option may not work as expected.

Message Headers

Camel uses the same message headers as the Camel Component: HTTP4 component. It also uses (Exchange.HTTP_CHUNKED,CamelHttpChunked) header 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 only supports consumer endpoints. Therefore a Jetty endpoint URI should be used only as the input for a Camel route (in a from() DSL call). To issue HTTP requests against other HTTP endpoints, use the HTTP4 Component

Component Options

The JettyHttpComponent provides the following options:

Name

Default Value

Description

enableJmx

false

If this option is true, Jetty JMX support will be enabled for this endpoint. See Jetty JMX support for more details.

sslKeyPassword

null

Consumer only : The password for the keystore when using SSL.

sslPassword

null

Consumer only : The password when using SSL.

sslKeystore

null

Consumer only : The path to the keystore.

minThreads

null

Consumer only : To set a value for minimum number of threads in server thread pool. Note that both a min and max size must be configured.

maxThreads

null

Consumer only : To set a value for maximum number of threads in server thread pool. Note that both a min and max size must be configured.

threadPool

null

Consumer only : To use a custom thread pool for the server. This option is only needed in special circumstances.

sslSocketConnectors

null

Consumer only: A map which contains per port number specific SSL connectors. See section SSL support for more details.

socketConnectors

null

Consumer only: A map which contains per port number specific HTTP connectors. Uses the same principle as sslSocketConnectors and therefore see section SSL support for more details.

sslSocketConnector-Properties

null

Consumer only. A map which contains general SSL connector properties. See section SSL support for more details.

socketConnector-Properties

null

Consumer only. A map which contains general HTTP connector properties. Uses the same principle as sslSocketConnectorProperties and therefore see section SSL support for more details.

httpClient

null

(Deprecated) Producer only : To use a custom HttpClient with the jetty producer. This option is removed from Camel 2.11 onwards, instead you can set the option on the endpoint instead.

httpClientMinThreads

null

Producer only : To set a value for minimum number of threads in HttpClient thread pool. Note that both a min and max size must be configured.

httpClientMaxThreads

null

Producer only : To set a value for maximum number of threads in HttpClient thread pool. Note that both a min and max size must be configured.

httpClientThreadPool

null

(Deprecated) Producer only : To use a custom thread pool for the client. This option will be removed starting with Camel 2.11.

sslContextParameters

null

To configure a custom SSL/TLS configuration options at the component level.

requestBufferSize

null

Camel 2.11.2: Allows to configure a custom value of the request buffer size on the Jetty connectors.

requestHeaderSize

null

Camel 2.11.2: Allows to configure a custom value of the request header size on the Jetty connectors.

responseBufferSize

null

Camel 2.11.2: Allows to configure a custom value of the response buffer size on the Jetty connectors.

responseHeaderSize

null

Camel 2.11.2: Allows to configure a custom value of the response header size on the Jetty connectors.

proxyHost

null

Camel 2.12.2/2.11.3 To use a http proxy.

proxyPort

null

Camel 2.12.2/2.11.3: To use a http proxy.

Sample

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

from("jetty:http://localhost:{{port}}/myapp/myservice").process(
   new MyBookService());

Note

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.

Our business logic is implemented in the MyBookService class, which accesses the HTTP request contents and then returns a response. Note: The assert call appears in this example, because the code is part of an unit test.

public class MyBookService implements Processor {
   public void process(Exchange exchange) throws Exception {
      // just get the body as a string
      String body = exchange.getIn().getBody(String.class);
      // we have access to the HttpServletRequest here and we
      // can grab it if we need it
      HttpServletRequest req = 
         exchange.getIn().getBody(HttpServletRequest.class);
      assertNotNull(req);

      // for unit testing
      assertEquals("bookid=123", body);

      // send a html response
      exchange.getOut().setBody(
         "<html><body>Book 123 is Factory Patterns</body></html>");
   }
}

The following sample shows a content-based route that routes all requests containing the URI parameter, one, to the endpoint, mock:one, and all others to mock:other.

from("jetty:" + serverUri)
   .choice()
   .when().simple("in.header.one").to("mock:one")
   .otherwise()
   .to("mock:other");

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 (such as EL or OGNL) 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:

<route>
   <from uri="jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true"/>
   <processRef ref="myCode"/>
<route>

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

<bean id="myCode"class="com.mycompany.MyCodeProcessor"/>

where the processor implementation can access the HttpSession as follows:

public void process(Exchange exchange) throws Exception {
    HttpSession session = exchange.getIn(HttpMessage.class).getRequest()
        .getSession(); 
    ...
}

SSL Support (HTTPS)

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:

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

...
<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/?sslContextParametersRef=... \
   sslContextParameters"/>
...

You can also configure Jetty for SSL directly. In this case, simply format the URI with the https:// prefix---for example:

<from uri="jetty:https://0.0.0.0/myapp/myservice/"/>

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

  • org.eclipse.jetty.ssl.keystore specifies 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 Jetty documentation here.

The value you use as keys in the above map is the port you configure Jetty to listen on.

Configuring general SSL properties

Instead of a per port number specific SSL socket connector (as shown above) you can now configure general properties which applies for all SSL socket connectors (which is not explicitly configured as above with the port number as entry).

<bean id="jetty" 
   class="org.apache.camel.component.jetty.JettyHttpComponent">
   <property name="sslSocketConnectorProperties">
      <map>
         <entry name="password"value="..."/>
         <entry name="keyPassword"value="..."/>
         <entry name="keystore"value="..."/>
         <entry name="needClientAuth"value="..."/>
         <entry name="truststore"value="..."/>
      </map>
   </property>
</bean>

Configuring general HTTP properties

Instead of a per port number specific HTTP socket connector (as shown above) you can now configure general properties which applies for all HTTP socket connectors (which is not explicit configured as above with the port number as entry).

<bean id="jetty" 
   class="org.apache.camel.component.jetty.JettyHttpComponent">
   <property name="socketConnectorProperties">
      <map>
         <entry key="acceptors" value="4"/>
         <entry key="maxIdleTime" value="300000"/>
      </map>
   </property>
</bean>

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, and the stacktrace is returned in the body. 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.

Jetty JMX support

Camel-jetty 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 in order 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".

<from uri="jetty:https://0.0.0.0/myapp/myservice1/?enableJmx=true"/>
<from uri="jetty:https://0.0.0.0/myapp/myservice2/?enableJmx=false"/>

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 in order to avoid name collisions when registering Jetty MBeans.