Questo contenuto non è disponibile nella lingua selezionata.

Chapter 282. Restlet Component


Available as of Camel version 2.0

The Restlet component provides Restlet based endpoints for consuming and producing RESTful resources.

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

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

Additionally, you will need to add a dependency on the restlet maven repository in your pom.xml file:

<repository>
   <id>maven-restlet</id>
   <name>Public online Restlet repository</name>
   <url>https://maven.restlet.com</url>
</repository>

282.1. URI format

restlet:restletUrl[?options]

Format of restletUrl:

protocol://hostname[:port][/resourcePattern]

Restlet promotes decoupling of protocol and application concerns. The reference implementation of Restlet Engine supports a number of protocols. However, we have tested the HTTP protocol only. The default port is port 80. We do not automatically switch default port based on the protocol yet.

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

INFO: It seems Restlet is case sensitive in understanding headers. For example to use content-type, use Content-Type, and for location use Location and so on.

Warning

We have received a report about drop in performance in camel-restlet in Camel 2.14.0 and 2.14.1. We have reported this to the Restlet team in issue 996. To remedy the issue then from Camel 2.14.2 onwards you can set synchronous=true as option on the endpoint uris, Or set it on the RestletComponent as a global option so all endpoints inherit this option.

282.2. Options

The Restlet component supports 23 options, which are listed below.

NameDescriptionDefaultType

controllerDaemon (consumer)

Indicates if the controller thread should be a daemon (not blocking JVM exit).

 

Boolean

controllerSleepTimeMs (consumer)

Time for the controller thread to sleep between each control.

 

Integer

headerFilterStrategy (filter)

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message.

 

HeaderFilterStrategy

inboundBufferSize (consumer)

The size of the buffer when reading messages.

 

Integer

maxConnectionsPerHost (common)

Maximum number of concurrent connections per host (IP address).

 

Integer

maxThreads (consumer)

Maximum threads that will service requests.

 

Integer

lowThreads (consumer)

Number of worker threads determining when the connector is considered overloaded.

 

Integer

maxTotalConnections (common)

Maximum number of concurrent connections in total.

 

Integer

minThreads (consumer)

Minimum threads waiting to service requests.

 

Integer

outboundBufferSize (consumer)

The size of the buffer when writing messages.

 

Integer

persistingConnections (consumer)

Indicates if connections should be kept alive after a call.

 

Boolean

pipeliningConnections (consumer)

Indicates if pipelining connections are supported.

 

Boolean

threadMaxIdleTimeMs (consumer)

Time for an idle thread to wait for an operation before being collected.

 

Integer

useForwardedForHeader (consumer)

Lookup the X-Forwarded-For header supported by popular proxies and caches and uses it to populate the Request.getClientAddresses() method result. This information is only safe for intermediary components within your local network. Other addresses could easily be changed by setting a fake header and should not be trusted for serious security checks.

 

Boolean

reuseAddress (consumer)

Enable/disable the SO_REUSEADDR socket option. See java.io.ServerSocket#reuseAddress property for additional details.

 

Boolean

maxQueued (consumer)

Maximum number of calls that can be queued if there aren’t any worker thread available to service them. If the value is '0', then no queue is used and calls are rejected if no worker thread is immediately available. If the value is '-1', then an unbounded queue is used and calls are never rejected.

 

Integer

disableStreamCache (consumer)

Determines whether or not the raw input stream from Restlet 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 Restlet input stream to support reading it multiple times to ensure 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. DefaultRestletBinding 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.

false

boolean

port (consumer)

To configure the port number for the restlet consumer routes. This allows to configure this once to reuse the same port for these consumers.

 

int

synchronous (producer)

Whether to use synchronous Restlet Client for the producer. Setting this option to true can yield faster performance as it seems the Restlet synchronous Client works better.

 

Boolean

enabledConverters (advanced)

A list of converters to enable as full class name or simple class name. All the converters automatically registered are enabled if empty or null

 

List

useGlobalSslContext Parameters (security)

Enable usage of global SSL context parameters.

false

boolean

sslContextParameters (security)

To configure security using SSLContextParameters

 

SSLContextParameters

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 Restlet endpoint is configured using URI syntax:

restlet:protocol:host:port/uriPattern

with the following path and query parameters:

282.2.1. Path Parameters (4 parameters):

NameDescriptionDefaultType

protocol

Required The protocol to use which is http or https

 

String

host

Required The hostname of the restlet service

 

String

port

Required The port number of the restlet service

80

int

uriPattern

The resource pattern such as /customer/id

 

String

282.2.2. Query Parameters (18 parameters):

NameDescriptionDefaultType

restletMethod (common)

On a producer endpoint, specifies the request method to use. On a consumer endpoint, specifies that the endpoint consumes only restletMethod requests.

GET

Method

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

restletMethods (consumer)

Specify one or more methods separated by commas (e.g. restletMethods=post,put) to be serviced by a restlet consumer endpoint. If both restletMethod and restletMethods options are specified, the restletMethod setting is ignored. The possible methods are: ALL,CONNECT,DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT,TRACE

 

String

disableStreamCache (consumer)

Determines whether or not the raw input stream from Restlet 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 Restlet input stream to support reading it multiple times to ensure 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. DefaultRestletBinding 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.

false

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

restletUriPatterns (consumer)

Deprecated Specify one ore more URI templates to be serviced by a restlet consumer endpoint, using the # notation to reference a List in the Camel Registry. If a URI pattern has been defined in the endpoint URI, both the URI pattern defined in the endpoint and the restletUriPatterns option will be honored.

 

List

connectTimeout (producer)

The Client will give up connection if the connection is timeout, 0 for unlimited wait.

30000

int

cookieHandler (producer)

Configure a cookie handler to maintain a HTTP session

 

CookieHandler

socketTimeout (producer)

The Client socket receive timeout, 0 for unlimited wait.

30000

int

throwExceptionOnFailure (producer)

Whether to throw exception on a producer failure. If this option is false then the http status code is set as a message header which can be checked if it has an error value.

true

boolean

autoCloseStream (producer)

Whether to auto close the stream representation as response from calling a REST service using the restlet producer. If the response is streaming and the option streamRepresentation is enabled then you may want to auto close the InputStream from the streaming response to ensure the input stream is closed when the Camel Exchange is done being routed. However if you need to read the stream outside a Camel route, you may need to not auto close the stream.

false

boolean

streamRepresentation (producer)

Whether to support stream representation as response from calling a REST service using the restlet producer. If the response is streaming then this option can be enabled to use an java.io.InputStream as the message body on the Camel Message body. If using this option you may want to enable the autoCloseStream option as well to ensure the input stream is closed when the Camel Exchange is done being routed. However if you need to read the stream outside a Camel route, you may need to not auto close the stream.

false

boolean

headerFilterStrategy (advanced)

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

 

HeaderFilterStrategy

restletBinding (advanced)

To use a custom RestletBinding to bind between Restlet and Camel message.

 

RestletBinding

synchronous (advanced)

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

false

boolean

restletRealm (security)

To configure the security realms of restlet as a map.

 

Map

sslContextParameters (security)

To configure security using SSLContextParameters.

 

SSLContextParameters

282.3. Spring Boot Auto-Configuration

The component supports 24 options, which are listed below.

NameDescriptionDefaultType

camel.component.restlet.controller-daemon

Indicates if the controller thread should be a daemon (not blocking JVM exit).

 

Boolean

camel.component.restlet.controller-sleep-time-ms

Time for the controller thread to sleep between each control.

 

Integer

camel.component.restlet.disable-stream-cache

Determines whether or not the raw input stream from Restlet 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 Restlet input stream to support reading it multiple times to ensure 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. DefaultRestletBinding 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.

false

Boolean

camel.component.restlet.enabled

Enable restlet component

true

Boolean

camel.component.restlet.enabled-converters

A list of converters to enable as full class name or simple class name. All the converters automatically registered are enabled if empty or null

 

List

camel.component.restlet.header-filter-strategy

To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. The option is a org.apache.camel.spi.HeaderFilterStrategy type.

 

String

camel.component.restlet.inbound-buffer-size

The size of the buffer when reading messages.

 

Integer

camel.component.restlet.low-threads

Number of worker threads determining when the connector is considered overloaded.

 

Integer

camel.component.restlet.max-connections-per-host

Maximum number of concurrent connections per host (IP address).

 

Integer

camel.component.restlet.max-queued

Maximum number of calls that can be queued if there aren’t any worker thread available to service them. If the value is '0', then no queue is used and calls are rejected if no worker thread is immediately available. If the value is '-1', then an unbounded queue is used and calls are never rejected.

 

Integer

camel.component.restlet.max-threads

Maximum threads that will service requests.

 

Integer

camel.component.restlet.max-total-connections

Maximum number of concurrent connections in total.

 

Integer

camel.component.restlet.min-threads

Minimum threads waiting to service requests.

 

Integer

camel.component.restlet.outbound-buffer-size

The size of the buffer when writing messages.

 

Integer

camel.component.restlet.persisting-connections

Indicates if connections should be kept alive after a call.

 

Boolean

camel.component.restlet.pipelining-connections

Indicates if pipelining connections are supported.

 

Boolean

camel.component.restlet.port

To configure the port number for the restlet consumer routes. This allows to configure this once to reuse the same port for these consumers.

 

Integer

camel.component.restlet.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.restlet.reuse-address

Enable/disable the SO_REUSEADDR socket option. See java.io.ServerSocket#reuseAddress property for additional details.

 

Boolean

camel.component.restlet.ssl-context-parameters

To configure security using SSLContextParameters. The option is a org.apache.camel.util.jsse.SSLContextParameters type.

 

String

camel.component.restlet.synchronous

Whether to use synchronous Restlet Client for the producer. Setting this option to true can yield faster performance as it seems the Restlet synchronous Client works better.

 

Boolean

camel.component.restlet.thread-max-idle-time-ms

Time for an idle thread to wait for an operation before being collected.

 

Integer

camel.component.restlet.use-forwarded-for-header

Lookup the X-Forwarded-For header supported by popular proxies and caches and uses it to populate the Request.getClientAddresses() method result. This information is only safe for intermediary components within your local network. Other addresses could easily be changed by setting a fake header and should not be trusted for serious security checks.

 

Boolean

camel.component.restlet.use-global-ssl-context-parameters

Enable usage of global SSL context parameters.

false

Boolean

282.4. Message Headers

NameTypeDescription

Content-Type

String

Specifies the content type, which can be set on the OUT message by the application/processor. The value is the content-type of the response message. If this header is not set, the content type is based on the object type of the OUT message body. In Camel 2.3 onward, if the Content-Type header is specified in the Camel IN message, the value of the header determine the content type for the Restlet request message. Otherwise, it is defaulted to "application/x-www-form-urlencoded'. Prior to release 2.3, it is not possible to change the request content type default.

CamelAcceptContentType

String

Since Camel 2.9.3, 2.10.0: The HTTP Accept request header.

CamelHttpMethod

String

The HTTP request method. This is set in the IN message header.

CamelHttpQuery

String

The query string of the request URI. It is set on the IN message by DefaultRestletBinding when the restlet component receives a request.

CamelHttpResponseCode

String or Integer

The response code can be set on the OUT message by the application/processor. The value is the response code of the response message. If this header is not set, the response code is set by the restlet runtime engine.

CamelHttpUri

String

The HTTP request URI. This is set in the IN message header.

CamelRestletLogin

String

Login name for basic authentication. It is set on the IN message by the application and gets filtered before the restlet request header by Camel.

CamelRestletPassword

String

Password name for basic authentication. It is set on the IN message by the application and gets filtered before the restlet request header by Camel.

CamelRestletRequest

Request

Camel 2.8: The org.restlet.Request object which holds all request details.

CamelRestletResponse

Response

Camel 2.8: The org.restlet.Response object. You can use this to create responses using the API from Restlet. See examples below.

org.restlet.*

 

Attributes of a Restlet message that get propagated to Camel IN headers.

cache-control

String or List<CacheDirective>

Camel 2.11: User can set the cache-control with the String value or the List of CacheDirective of Restlet from the camel message header.

282.5. Message Body

Camel will store the restlet response from the external server on the OUT body. All headers from the IN message will be copied to the OUT message, so that headers are preserved during routing.

282.6. Samples

282.6.1. Restlet Endpoint with Authentication

The following route starts a restlet consumer endpoint that listens for POST requests on http://localhost:8080. The processor creates a response that echoes the request body and the value of the id header.

The restletRealm setting in the URI query is used to look up a Realm Map in the registry. If this option is specified, the restlet consumer uses the information to authenticate user logins. Only authenticated requests can access the resources. In this sample, we create a Spring application context that serves as a registry. The bean ID of the Realm Map should match the restletRealmRef.

The following sample starts a direct endpoint that sends requests to the server on http://localhost:8080 (that is, our restlet consumer endpoint).

That is all we need. We are ready to send a request and try out the restlet component:

The sample client sends a request to the direct:start-auth endpoint with the following headers:

  • CamelRestletLogin (used internally by Camel)
  • CamelRestletPassword (used internally by Camel)
  • id (application header)
Note

org.apache.camel.restlet.auth.login and org.apache.camel.restlet.auth.password will not be propagated as Restlet header.

The sample client gets a response like the following:

received [<order foo='1'/>] as an order id = 89531

282.6.2. Single restlet endpoint to service multiple methods and URI templates (deprecated)

This functionality is deprecated so do NOT use!

It is possible to create a single route to service multiple HTTP methods using the restletMethods option. This snippet also shows how to retrieve the request method from the header:

In addition to servicing multiple methods, the next snippet shows how to create an endpoint that supports multiple URI templates using the restletUriPatterns option. The request URI is available in the header of the IN message as well. If a URI pattern has been defined in the endpoint URI (which is not the case in this sample), both the URI pattern defined in the endpoint and the restletUriPatterns option will be honored.

The restletUriPatterns=#uriTemplates option references the List<String> bean defined in the Spring XML configuration.

<util:list id="uriTemplates">
    <value>/users/{username}</value>
    <value>/atom/collection/{id}/component/{cid}</value>
</util:list>

282.6.3. Using Restlet API to populate response

Available as of Camel 2.8

You may want to use the org.restlet.Response API to populate the response. This gives you full access to the Restlet API and fine grained control of the response. See the route snippet below where we generate the response from an inlined Camel Processor:

Generating response using Restlet Response API

282.6.4. Configuring max threads on component

To configure the max threads options you must do this on the component, such as:

<bean id="restlet" class="org.apache.camel.component.restlet.RestletComponent">
  <property name="maxThreads" value="100"/>
</bean>

282.6.5. Using the Restlet servlet within a webapp

Available as of Camel 2.8
There are three possible ways to configure a Restlet application within a servlet container and using the subclassed SpringServerServlet enables configuration within Camel by injecting the Restlet Component.

Use of the Restlet servlet within a servlet container enables routes to be configured with relative paths in URIs (removing the restrictions of hard-coded absolute URIs) and for the hosting servlet container to handle incoming requests (rather than have to spawn a separate server process on a new port).

Prerequisites

  • You need to add a dependency on the Spring extension to the restlet in your Maven pom.xml file:

    <dependency>
      <groupId>org.restlet.jee</groupId>
      <artifactId>org.restlet.ext.spring</artifactId>
      <version>${restlet-version}</version>
    </dependency>

Procedure

  1. To configure the Restlet application, add the following to your camel-context.xml;

    <camelContext>
      <route id="RS_RestletDemo">
        <from uri="restlet:/demo/{id}" />
        <transform>
          <simple>Request type : ${header.CamelHttpMethod} and ID : ${header.id}</simple>
        </transform>
      </route>
    </camelContext>
    
    <bean id="RestletComponent" class="org.restlet.Component" />
    
    <bean id="RestletComponentService" class="org.apache.camel.component.restlet.RestletComponent">
      <constructor-arg index="0">
        <ref bean="RestletComponent" />
      </constructor-arg>
    </bean>
  2. Add the following to your web.xml;

    <!-- Restlet Servlet -->
    <servlet>
      <servlet-name>RestletServlet</servlet-name>
      <servlet-class>org.restlet.ext.spring.SpringServerServlet</servlet-class>
      <init-param>
        <param-name>org.restlet.component</param-name>
        <param-value>RestletComponent</param-value>
      </init-param>
    </servlet>
    
    <servlet-mapping>
      <servlet-name>RestletServlet</servlet-name>
      <url-pattern>/rs/*</url-pattern>
    </servlet-mapping>

Result

You can access the deployed route at http://localhost:8080/mywebapp/rs/demo/1234 where localhost:8080 is the server and port of your servlet container and mywebapp is the name of your deployed webapp.

Your browser will show the following content:

"Request type : GET and ID : 1234"
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.