= Jetty Component
:doctitle: Jetty
:shortname: jetty
:artifactid: camel-jetty
:description: Expose HTTP endpoints using Jetty 9.
:since: 1.2
:supportlevel: Stable
:component-header: Only consumer is supported
//Manually maintained attributes
:camel-spring-boot-name: jetty

*Since Camel {since}*

*{component-header}*

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

*Stream*

The `assert` call appears in this example, because the code is part of
an unit test.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
(e.g.: doing multicasting, or redelivery error handling), you should use
Stream caching or convert the message body to
a `String` which is safe to be re-read multiple times.

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

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

== URI format

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

// component-configure options: START

// component-configure options: END

// component options: START
include::partial$component-configure-options.adoc[]
include::partial$component-endpoint-options.adoc[]
// component options: END

// endpoint options: START

// endpoint options: END


== Message Headers

Camel uses the same message headers as the xref:http-component.adoc[HTTP]
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 method.

// component headers: START
include::partial$component-endpoint-headers.adoc[]
// component headers: END

== Usage

The Jetty component supports consumer endpoints.

== Consumer Example

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

*Usage of localhost*

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

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

To listen across an entire URI prefix, see
xref:manual:faq:how-do-i-let-jetty-match-wildcards.adoc[How do I let Jetty match wildcards].

If you actually want to expose routes by HTTP and already have a
Servlet, you should instead refer to the
xref:servlet-component.adoc[Servlet Transport].

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.

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

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
xref:languages:simple-language.adoc[Simple] (such as xref:languages:ognl-language.adoc[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:

[source,xml]
----
<route>
    <from uri="jetty:http://0.0.0.0/myapp/myservice/?sessionSupport=true"/>
    <process ref="myCode"/>
</route>
----

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

[source,xml]
----
<bean id="myCode" class="com.mycompany.MyCodeProcessor"/>
----

Where the processor implementation can access the `HttpSession` as
follows:

[source,java]
----
public void process(Exchange exchange) throws Exception {
    HttpSession session = exchange.getIn(HttpMessage.class).getRequest().getSession();
    ...
}
----

== SSL Support (HTTPS)

[[Jetty-UsingtheJSSEConfigurationUtility]]
Using the JSSE Configuration Utility

The Jetty component supports SSL/TLS configuration
through the xref:manual::camel-configuration-utilities.adoc[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.

[[Jetty-Programmaticconfigurationofthecomponent]]
Programmatic configuration of the component

[source,java]
----
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);
----

[[Jetty-SpringDSLbasedconfigurationofendpoint]]
Spring DSL based configuration of endpoint

[source,xml]
----
  <camel:sslContextParameters
      id="sslContextParameters">
    <camel:keyManagers
        keyPassword="keyPassword">
      <camel:keyStore
          resource="/users/home/server/keystore.jks"
          password="keystorePassword"/>
    </camel:keyManagers>
  </camel:sslContextParameters>

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

----
[[HTTP-Blueprintbasedconfigurationofendpoint]]
Blueprint based configuration of endpoint

Global configuration of sslContextParameters in a dedicated Blueprint XML file

[source,xml]
----
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd">

  <sslContextParameters id="sslContextParameters" xmlns="http://camel.apache.org/schema/blueprint">
    <keyManagers keyPassword="keyPassword">
      <keyStore resource="etc/keystore.p12" password="keystorePassword"/>
      </keyManagers>
  </sslContextParameters>

  <service ref="sslContextParameters" auto-export="all-classes"/>
</blueprint>
----

Use of the global configuration in other Blueprint XML files with route definitions

[source,xml]
----
...
<reference id="sslContextParameters" interface="org.apache.camel.support.jsse.SSLContextParameters" ext:proxy-method="classes" />

  <camelContext xmlns="http://camel.apache.org/schema/blueprint">
    <route>
     <from uri="jetty:https://0.0.0.0/path?sslContextParameters=#sslContextParameters"/>
...
----

[[Jetty-ConfiguringJettyDirectly]]
Configuring Jetty Directly

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:

[source,xml]
----
<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
following documentation at the Jetty Site:
http://docs.codehaus.org/display/JETTY/How+to+configure+SSL[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.

[source,xml]
----
<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.

=== 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 explicit configured as above with
the port number as entry).

[source,xml]
----
<bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
    <property name="sslSocketConnectorProperties">
        <map>
            <entry key="password" value="..."/>
            <entry key="keyPassword" value="..."/>
            <entry key="keystore" value="..."/>
            <entry key="needClientAuth" value="..."/>
            <entry key="truststore" value="..."/>
        </map>
    </property>
</bean>
----

=== How to obtain reference to the X509Certificate

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

[source,java]
----
HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);
X509Certificate cert = (X509Certificate) req.getAttribute("javax.servlet.request.X509Certificate")
----

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

[source,xml]
----
<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>
----

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

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

Jetty has a forwarded property which takes the value from
X-Forwarded-For and places it in the HttpServletRequest remoteAddr
property.  This property is not available directly through the endpoint
configuration but it can be easily added using the socketConnectors
property:

[source,xml]
----
<bean id="jetty" class="org.apache.camel.component.jetty.JettyHttpComponent">
    <property name="socketConnectors">
        <map>
            <entry key="8080">
                <bean class="org.eclipse.jetty.server.nio.SelectChannelConnector">
                    <property name="forwarded" value="true"/>
                </bean>
            </entry>
        </map>
    </property>
</bean>
----

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

== Default behavior for returning HTTP status codes

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

If the exchange was processed successfully, the 200 HTTP status code is
returned. +
 If the exchange failed with an exception, the 500 HTTP status code is
returned, 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.

== Customizing HttpBinding

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

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

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

[source,xml]
----
<bean id="mybinding" class="com.mycompany.MyHttpBinding"/>
----

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

[source,xml]
----
<route>
  <from uri="jetty:http://0.0.0.0:8080/myapp/myservice?httpBindingRef=mybinding"/>
  <to uri="bean:doSomething"/>
</route>
----

== Jetty handlers and security configuration

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

[source,xml]
----
<bean id="userRealm" class="org.mortbay.jetty.plus.jaas.JAASUserRealm">
    <property name="name" value="tracker-users"/>
    <property name="loginModuleName" value="ldaploginmodule"/>
</bean>

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

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

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

You can configure a list of Jetty handlers as follows:

[source,xml]
----
<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:

[source,java]
----
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.

Blueprint based definition of basic authentication (based on Jetty 9):

[source,xml]
----
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
  xmlns:ext="http://aries.apache.org/blueprint/xmlns/blueprint-ext/v1.0.0">

  <bean id="constraint" class="org.eclipse.jetty.util.security.Constraint">
    <property name="name" value="BASIC"/>
    <property name="authenticate" value="true"/>
      <property name="roles">
        <list>
          <value>rolename1</value>
        </list>
      </property>
  </bean>

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

  <bean id="securityHandler" class="org.eclipse.jetty.security.ConstraintSecurityHandler">
    <property name="loginService">
      <bean class="org.eclipse.jetty.security.HashLoginService">
        <property name="config" value="/opt/apache-karaf/etc/roles.properties"/>
        <property name="hotReload" value="true"/>
      </bean>
    </property>
    <property name="authenticator">
      <bean class="org.eclipse.jetty.security.authentication.BasicAuthenticator"/>
    </property>
    <property name="constraintMappings">
      <list>
        <ref component-id="constraintMapping"/>
      </list>
    </property>
  </bean>
  
  <camelContext xmlns="http://camel.apache.org/schema/blueprint">

    <route>
      <from uri="jetty:http://0.0.0.0/path?handlers=securityHandler"/>
...
----

The roles.properties files contains

----
username1=password1,rolename1
username2=password2,rolename1
----

This file is located in the etc folder and will be reloaded when changed. The endpoint

----
http://0.0.0.0/path
----

is now secured with basic authentication, only username1 with password1 and username2 with password2 are able to access the endpoint.

== How to return a custom HTTP 500 reply message

You may want to return a custom reply message when something goes wrong,
instead of the default reply message Camel xref:jetty-component.adoc[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:

== Multi-part Form support

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

== Jetty JMX support

The camel-jetty component supports the enabling of Jetty's JMX
capabilities at the component and endpoint level with the endpoint
configuration taking priority. Note that JMX must be enabled within the
Camel context 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".

[source,xml]
----
<from uri="jetty:https://0.0.0.0/myapp/myservice1/?enableJmx=true"/>
----

[source,xml]
----
<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.


include::spring-boot:partial$starter.adoc[]
