LibraryToggle FramesPrintFeedback

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

[Tip]Upgrading from Jetty 6 to 7

You can read more about upgrading Jetty here

[Important]Stream

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 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.

Name Default Value Description
sessionSupport false Specifies whether to enable the session manager on the server side of Jetty.
httpClient.XXX null Fuse Mediation Router 1.6.0/2.0: Configuration of Jetty's HttpClient. For example, setting httpClient.idleTimeout=30000 sets the idle timeout to 30 seconds.
httpBindingRef null Fuse Mediation Router 1.6.0/2.0: Reference to an org.apache.camel.component.http.HttpBinding in the Registry. HttpBinding can be used to customize how a response should be written.
jettyHttpBindingRef null Camel 2.6.0: Reference to an org.apache.camel.component.jetty.JettyHttpBinding in the Registry. JettyHttpBinding can be used to customize how a response should be written.
matchOnUriPrefix false Fuse Mediation Router 2.0: Whether or not the CamelServlet should try to find a target consumer by matching the URI prefix if no exact match is found.
handlers null Fuse Mediation Router 1.6.1/2.0: 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 Camel 2.2: If this option is false Jetty servlet will disable the HTTP streaming and set the content-length header on the response
enableJmx false Camel 2.3: If this option is true, Jetty JMX support will be enabled for this endpoint.
disableStreamCache false Camel 2.3: 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.
bridgeEndpoint false

Camel 2.1: 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 throwExcpetionOnFailure to be false to let the HttpProducer send all the fault response back. Camel 2.3: If the option is true, HttpProducer and CamelServlet will skip the gzip processing if the content-encoding is "gzip".

enableMultipartFilter true Canel 2.5: 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 Camel 2.6: Allows using a custom multipart filter. Note: setting multipartFilterRef forces the value of enableMultipartFilter to true.
continuationTimeout null Camel 2.6: Allows to set a timeout in millis when using 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 Jetty with the Asynchronous Routing Engine.
useContinuation true Camel 2.6: Whether or not to use Jetty continuations for the Jetty Server.

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. |

Fuse Mediation Router uses the same message headers as the HTTP component. From Camel 2.2, it also uses (Exchange.HTTP_CHUNKED,CamelHttpChunked) header to turn on or turn off the chuched encoding on the camel-jetty consumer.

Fuse Mediation Router 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. This feature was introduced in Fuse Mediation Router 1.5.

From Camel 1.6.3 and Camel 2.2.0, you can get the request.parameter from the message header not only from Get Method, but also other HTTP method.

The JettyHttpComponent provides the following options:

Name Default Value Description
enableJmx false Camel 2.3: If this option is true, Jetty JMX support will be enabled for this endpoint.
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 Camel 2.5Consumer only: To set a value for minimum number of threads in server thread pool.
maxThreads null Camel 2.5Consumer only: To set a value for maximum number of threads in server thread pool.
threadPool null Camel 2.5Consumer only: To use a custom thread pool for the server.
sslSocketConnectors null Camel 2.3Consumer only: A map which contains per port number specific SSL connectors. See section SSL support for more details.
socketConnectors null Camel 2.5Consumer 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.
sslSocketConnectorProperties null Camel 2.5Consumer only. A map which contains general SSL connector properties. See section SSL support for more details.
socketConnectorProperties null Camel 2.5Consumer 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 Producer only: To use a custom HttpClient with the jetty producer.
httpClientMinThreads null Producer only: To set a value for minimum number of threads in HttpClient thread pool.
httpClientMaxThreads null Producer only: To set a value for maximum number of threads in HttpClient thread pool.
httpClientThreadPool null Producer only: To use a custom thread pool for the client.

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

from("jetty:http://localhost:9080/myapp/myservice").process(new MyBookService());
[Note]Usage of localhost

When you specify localhost in a URL, Fuse Mediation Router 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 Camel in Action</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.

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 = ((HttpExchange)exchange).getRequest().getSession();
    ...
}

Jetty provides SSL support out of the box. To enable Jetty to run in SSL mode, 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:

until Camel 2.2

from Camel 2.3 onwards

For details of how to configure SSL on a Jetty endpoint, read the following documentation at the Jetty Site:

http://docs.codehaus.org/display/JETTY/How+to+configure+SSL

Some SSL properties aren't exposed directly by Camel, however Camel does expose the underlying SslSocketConnector, which will allow you to set properties like needClientAuth for mutual authentication requiring a client certificate or wantClientAuth for mutual authentication where a client doesn't need a certificate but can have one. There's a slight difference between Camel 1.6.x and 2.x:

Camel 1.x

  <bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
    <property name="sslSocketConnector">
      <bean class="org.mortbay.jetty.security.SslSocketConnector">
        <property name="password" value="..." />
        <property name="keyPassword" value="..." />
        <property name="keystore" value="..." />
        <property name="wantClientAuth" value="..." />
        <property name="truststore" value="..." />
      </bean>
    </property>
  </bean>

Until Camel 2.2

  <bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
     <property name="sslSocketConnectors">
        <map>
           <entry key="8043">
             <bean class="org.mortbay.jetty.security.SslSocketConnector">
               <property name="password" value="..." />
               <property name="keyPassword" value="..." />
               <property name="keystore" value="..." />
               <property name="needClientAuth" value="..." />
               <property name="truststore" value="..." />
             </bean>
          </entry>
       </map>
    </property>
  </bean>

Camel 2.3 to 2.4

<bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
    <property name="sslSocketConnectors">
        <map>
            <entry key="8043">
                <bean class="org.eclipse.jetty.server.ssl.SslSocketConnector">
                    <property name="password"value="..."/>
                    <property name="keyPassword"value="..."/>
                    <property name="keystore"value="..."/>
                    <property name="needClientAuth"value="..."/>
                    <property name="truststore"value="..."/>
                </bean>
            </entry>
        </map>
    </property>
</bean>

From Camel 2.5 we switch to use SslSelectChannelConnector

<bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
    <property name="sslSocketConnectors">
        <map>
            <entry key="8043">
                <bean class="org.eclipse.jetty.server.ssl.SslSelectChannelConnector">
                    <property name="password"value="..."/>
                    <property name="keyPassword"value="..."/>
                    <property name="keystore"value="..."/>
                    <property name="needClientAuth"value="..."/>
                    <property name="truststore"value="..."/>
                </bean>
            </entry>
        </map>
    </property>
</bean>

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

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

        <-- Jetty Security handling -->
	<bean id="userRealm" class="org.mortbay.jetty.plus.jaas.JAASUserRealm">
		<property name="name" value="tracker-users" />
		<property name="loginModuleName" value="ldaploginmodule" />
	</bean>

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

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

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

And from Camel 2.3 onwards you can configure a list of Jetty handlers as follows:

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

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

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

You can then define the endpoint as:

from("jetty:http://0.0.0.0:9080/myservice?handlers=securityHandler")

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

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

from("jetty://http://localhost:8234/myserver")
    // use onException to catch all exceptions and return a custom reply message
    .onException(Exception.class)
        .handled(true)
        // create a custom failure response
        .transform(constant("Dude something went wrong"))
        // we must remember to set error code 500 as handled(true)
        // otherwise would let Camel thing its a OK response (200)
        .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
    .end()
    // now just force an exception immediately
    .throwException(new IllegalArgumentException("I cannot do this"));

From Camel 2.3.0, 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.

See also:

Comments powered by Disqus