Modified: websites/production/camel/content/type-converter.html
==============================================================================
--- websites/production/camel/content/type-converter.html (original)
+++ websites/production/camel/content/type-converter.html Fri Aug 25 14:20:21
2017
@@ -36,17 +36,6 @@
<![endif]-->
- <link href='//camel.apache.org/styles/highlighter/styles/shCoreCamel.css'
rel='stylesheet' type='text/css' />
- <link href='//camel.apache.org/styles/highlighter/styles/shThemeCamel.css'
rel='stylesheet' type='text/css' />
- <script src='//camel.apache.org/styles/highlighter/scripts/shCore.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushJava.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushXml.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushPlain.js'
type='text/javascript'></script>
-
- <script type="text/javascript">
- SyntaxHighlighter.defaults['toolbar'] = false;
- SyntaxHighlighter.all();
- </script>
<title>
Apache Camel: Type Converter
@@ -86,66 +75,29 @@
<tbody>
<tr>
<td valign="top" width="100%">
-<div class="wiki-content maincontent"><h2
id="TypeConverter-TypeConverter">Type Converter</h2><p>Its very common when
routing messages from one endpoint to another to need to convert the body
payloads from one type to another such as to convert to and from the following
common types</p><ul><li>File</li><li>String</li><li>byte[] and
ByteBuffer</li><li>InputStream and OutputStream</li><li>Reader and
Writer</li><li>Document and Source</li><li>...</li></ul><p>The <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Message.html">Message
interface</a> defines a helper method to allow conversions to be done via the
<a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Message.html#getBody(java.lang.Class)">getBody(Class)</a>
method.</p><p>So in an endpoint you can convert a body to another type
via</p><div class="code panel pdl" style="border-width: 1px;"><div c
lass="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[Message message = exchange.getIn();
+<div class="wiki-content maincontent"><h2
id="TypeConverter-TypeConverter">Type Converter</h2><p>Its very common when
routing messages from one endpoint to another to need to convert the body
payloads from one type to another such as to convert to and from the following
common types</p><ul><li>File</li><li>String</li><li>byte[] and
ByteBuffer</li><li>InputStream and OutputStream</li><li>Reader and
Writer</li><li>Document and Source</li><li>...</li></ul><p>The <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Message.html">Message
interface</a> defines a helper method to allow conversions to be done via the
<a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Message.html#getBody(java.lang.Class)">getBody(Class)</a>
method.</p><p>So in an endpoint you can convert a body to another type
via</p><plain-text-body>Message message = exchange.getIn();
Document document = message.getBody(Document.class);
-]]></script>
-</div></div><h3 id="TypeConverter-HowTypeConversionworks">How Type Conversion
works</h3><p>The type conversion strategy is defined by the <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/TypeConverter.html">TypeConverter</a>
interface that can be customized on a <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html">CamelContext</a>.</p><p>The
default implementation, <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/DefaultTypeConverter.html">DefaultTypeConverter</a>,
uses pluggable strategies to load type converters via <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/TypeConverterLoader.html">TypeConverterLoader</a>.
The default strategy, <a shape="rect" class="externa
l-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>,
uses a discovery mechanism to find converters.</p><p><strong>New in Camel
1.5</strong></p><p>The default implementation, <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/DefaultTypeConverter.html">DefaultTypeConverter</a>,
now throws a <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/NoTypeConversionAvailableException.html">NoTypeConversionAvailableException</a>
if a suitable conversion cannot be found (CAMEL-84). The semantical ambiguity
of <code>null</code> (both valid result and indication of no conversion found)
is now resolved, but this may impact existing code in that it should now catch
the exception instead of checking for <code>null</code>.</p><h3 id="T
ypeConverter-TypeConverterRegistry">TypeConverterRegistry</h3><p><strong>New
in Camel 2.0</strong></p><p>Exposed the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/spi/TypeConverterRegistry.html">TypeConverterRegistry</a>
from <a shape="rect" href="camelcontext.html">CamelContext</a> so end users
more easily will be able to add type converters at runtime. This is also usable
in situations where the default discovering of type converters fails on
platforms with classloading issues.</p><p>To access the registry, you get it
from the CamelContext</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ CamelContext context = ...
+</plain-text-body><h3 id="TypeConverter-HowTypeConversionworks">How Type
Conversion works</h3><p>The type conversion strategy is defined by the <a
shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/TypeConverter.html">TypeConverter</a>
interface that can be customized on a <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/CamelContext.html">CamelContext</a>.</p><p>The
default implementation, <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/DefaultTypeConverter.html">DefaultTypeConverter</a>,
uses pluggable strategies to load type converters via <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/TypeConverterLoader.html">TypeConverterLoader</a>.
The default strategy, <a shape="rect" class="e
xternal-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>,
uses a discovery mechanism to find converters.</p><p><strong>New in Camel
1.5</strong></p><p>The default implementation, <a shape="rect"
class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/DefaultTypeConverter.html">DefaultTypeConverter</a>,
now throws a <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/NoTypeConversionAvailableException.html">NoTypeConversionAvailableException</a>
if a suitable conversion cannot be found (CAMEL-84). The semantical ambiguity
of <code>null</code> (both valid result and indication of no conversion found)
is now resolved, but this may impact existing code in that it should now catch
the exception instead of checking for <code>null</code>.</p><h3
id="TypeConverter-TypeConverterRegistry">TypeConverterRegistry</h3><p><strong>New
in Camel 2.0</strong></p><p>Exposed the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/spi/TypeConverterRegistry.html">TypeConverterRegistry</a>
from <a shape="rect" href="camelcontext.html">CamelContext</a> so end users
more easily will be able to add type converters at runtime. This is also usable
in situations where the default discovering of type converters fails on
platforms with classloading issues.</p><p>To access the registry, you get it
from the CamelContext</p><parameter
ac:name="">java</parameter><plain-text-body> CamelContext context = ...
context.getTypeConverterRegistry()
-]]></script>
-</div></div><h4
id="TypeConverter-TypeConverterRegistryutilizationstatistics">TypeConverterRegistry
utilization statistics</h4><p>Camel can gather utilization statistics of the
runtime usage of type converters. These stats are available in JMX, and as well
as from the <code>getStatistics()</code> method from
<code>TypeConverterRegistry</code>.</p><p>From <strong>Camel
2.11.0/2.10.5</strong> onwards these statistics are turned off by default as
there is some performance overhead under very high concurrent load. To enable
the statistics in Java, do the following:</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ CamelContext context = ...
+</plain-text-body><h4
id="TypeConverter-TypeConverterRegistryutilizationstatistics">TypeConverterRegistry
utilization statistics</h4><p>Camel can gather utilization statistics of the
runtime usage of type converters. These stats are available in JMX, and as well
as from the <code>getStatistics()</code> method from
<code>TypeConverterRegistry</code>.</p><p>From <strong>Camel
2.11.0/2.10.5</strong> onwards these statistics are turned off by default as
there is some performance overhead under very high concurrent load. To enable
the statistics in Java, do the following:</p><plain-text-body> CamelContext
context = ...
context.setTypeConverterStatisticsEnabled(true);
-]]></script>
-</div></div><p>Or in the XML DSL with:</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[<camelContext
xmlns="http://camel.apache.org/schema/spring"
typeConverterStatisticsEnabled="true">
+</plain-text-body><p>Or in the XML DSL with:</p><parameter
ac:name="">xml</parameter><plain-text-body><camelContext
xmlns="http://camel.apache.org/schema/spring"
typeConverterStatisticsEnabled="true">
...
</camelContext>
-]]></script>
-</div></div><h4 id="TypeConverter-Addtypeconverteratruntime">Add type
converter at runtime</h4><p>The following sample demonstrates how to add a type
converter at runtime:</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// add our own type converter manually that converts from String -> MyOrder
using MyOrderTypeConverter
-context.getTypeConverterRegistry().addTypeConverter(MyOrder.class,
String.class, new MyOrderTypeConverter());
-]]></script>
-</div></div>And our type converter is implemented as:<div class="code panel
pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-private static class MyOrderTypeConverter extends TypeConverterSupport {
-
- @SuppressWarnings("unchecked")
- public <T> T convertTo(Class<T> type, Exchange exchange,
Object value) {
- // converter from value to the MyOrder bean
- MyOrder order = new MyOrder();
- order.setId(Integer.parseInt(value.toString()));
- return (T) order;
- }
-}
-]]></script>
-</div></div>And then we can convert from String to MyOrder as we are used to
with the type converter:<div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-MyOrder order = context.getTypeConverter().convertTo(MyOrder.class,
"123");
-]]></script>
-</div></div><h3 id="TypeConverter-Addtypeconverterclassesatruntime">Add type
converter classes at runtime</h3><p><strong>Available as of Camel
2.16</strong></p><p>From Camel 2.16 onwards you type converter classes can
implement <code>org.apache.camel.TypeConverters</code> which is an marker
interface. Then for each type converter you want use
the <code>@Converter</code> annotation.</p><div class="code panel
pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[private class MyOrderTypeConverters
implements TypeConverters {
-Â
+</plain-text-body><h4 id="TypeConverter-Addtypeconverteratruntime">Add type
converter at runtime</h4><p>The following sample demonstrates how to add a type
converter at
runtime:<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/TypeConverterRegistryTest.java}</plain-text-body>And
our type converter is implemented
as:<plain-text-body>{snippet:id=e2|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/TypeConverterRegistryTest.java}</plain-text-body>And
then we can convert from String to MyOrder as we are used to with the type
converter:<plain-text-body>{snippet:id=e3|lang=java|url=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/TypeConverterRegistryTest.java}</plain-text-body></p><h3
id="TypeConverter-Addtypeconverterclassesatruntime">Add type converter classes
at runtime</h3><p><strong>Available as of Camel 2.16</strong></p><p>From Camel
2.16 onwards you type converter classes can implement <co
de>org.apache.camel.TypeConverters</code> which is an marker interface. Then
for each type converter you want use
the <code>@Converter</code> annotation.</p><plain-text-body>private
class MyOrderTypeConverters implements TypeConverters {
+ 
@Converter
public MyOrder toMyOrder(String orderId) {
MyOrder order = new MyOrder();
order.setId(Integer.parseInt(orderId));
return order;
}
-}]]></script>
-</div></div><p> </p><p>Then you can add these converters to the registry
using</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[MyOrderTypeConverters myClass = ...
-context.getTypeConverterRegistry().addTypeConverters(myClass);]]></script>
-</div></div><p>If you are using Spring or Blueprint, then you can just declare
a <bean> then CamelContext will automatic discover and add the
converters.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[<bean id="myOrderTypeConverters"
class="..."/>
-Â
+}</plain-text-body><p> </p><p>Then you can add these converters to the
registry using</p><plain-text-body>MyOrderTypeConverters myClass = ...
+context.getTypeConverterRegistry().addTypeConverters(myClass);</plain-text-body><p>If
you are using Spring or Blueprint, then you can just declare a <bean>
then CamelContext will automatic discover and add the
converters.</p><plain-text-body><bean id="myOrderTypeConverters"
class="..."/>
+ 
<camelContext ...>
...
-</camelContext>]]></script>
-</div></div><p>You can declare multiple <bean>s if you have more
classes.</p><p>Using this technique do not require to scan the classpath and
using the file
<code>META-INF/services/org/apache/camel/TypeConverter</code> as discussed
in the <em>Discovering Type Converters</em> section. However the latter is
highly recommended when developing Camel components or data formats as then the
type converters is automatic included out of the box. The functionality from
this section requires the end users to explicit add the converters to their
Camel applications.</p><h3
id="TypeConverter-DiscoveringTypeConverters">Discovering Type
Converters</h3><p>The <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>
will search the classpath for a file called
<em>META-INF/services/org/apache/camel/TypeConverter</em>. The contents are
expecte
d to be comma separated package names. These packages are then recursively
searched for any objects with the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Converter">@Converter</a>
annotation. Then any method marked with @Converter is assumed to be a
conversion method; where the parameter is the from value and the return is the
to value.</p><p>e.g. the following shows how to register a converter from File
-> InputStream</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[@Converter
+</camelContext></plain-text-body><p>You can declare multiple
<bean>s if you have more classes.</p><p>Using this technique do not
require to scan the classpath and using the file
<code>META-INF/services/org/apache/camel/TypeConverter</code> as discussed
in the <em>Discovering Type Converters</em> section. However the latter is
highly recommended when developing Camel components or data formats as then the
type converters is automatic included out of the box. The functionality from
this section requires the end users to explicit add the converters to their
Camel applications.</p><h3
id="TypeConverter-DiscoveringTypeConverters">Discovering Type
Converters</h3><p>The <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>
will search the classpath for a file called
<em>META-INF/services/org/apache/camel/TypeConverter</em
>. The contents are expected to be comma separated package names. These
>packages are then recursively searched for any objects with the <a
>shape="rect" class="external-link"
>href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/Converter">@Converter</a>
> annotation. Then any method marked with @Converter is assumed to be a
>conversion method; where the parameter is the from value and the return is
>the to value.</p><p>e.g. the following shows how to register a converter from
>File -> InputStream</p><plain-text-body>@Converter
public class IOConverter {
@Converter
@@ -153,9 +105,7 @@ public class IOConverter {
return new BufferedInputStream(new FileInputStream(file));
}
}
-]]></script>
-</div></div><p>Static methods are invoked; non-static methods require an
instance of the converter object to be created (which is then cached). If a
converter requires configuration you can plug in an Injector interface to the
DefaultTypeConverter which can construct and inject converter objects via
Spring or Guice.</p><p>We have most of the common converters for common Java
types in the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/converter/package-summary.html">org.apache.camel.converter</a>
package and its children.</p><h4
id="TypeConverter-Returningnullvalues">Returning null values</h4><p>By default
when using a method in a POJO annotation with @Converter returning null is not
a valid response. If null is returned, then Camel will regard that type
converter as a <em>miss</em>, and prevent from using it in the future. If null
should be allowed as a valid response, then from <strong>Camel
2.11.2/2.12</strong>
onwards you can specify this in the annotation as shown:</p><div class="code
panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ @Converter(allowNull = true)
+</plain-text-body><p>Static methods are invoked; non-static methods require an
instance of the converter object to be created (which is then cached). If a
converter requires configuration you can plug in an Injector interface to the
DefaultTypeConverter which can construct and inject converter objects via
Spring or Guice.</p><p>We have most of the common converters for common Java
types in the <a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/converter/package-summary.html">org.apache.camel.converter</a>
package and its children.</p><h4
id="TypeConverter-Returningnullvalues">Returning null values</h4><p>By default
when using a method in a POJO annotation with @Converter returning null is not
a valid response. If null is returned, then Camel will regard that type
converter as a <em>miss</em>, and prevent from using it in the future. If null
should be allowed as a valid response, then from <strong>Camel 2.11.2/2.12</s
trong> onwards you can specify this in the annotation as
shown:</p><plain-text-body> @Converter(allowNull = true)
public static InputStream toInputStream(File file) throws IOException {
if (file.exist()) {
return new BufferedInputStream(new FileInputStream(file));
@@ -163,17 +113,11 @@ public class IOConverter {
return null;
}
}
-]]></script>
-</div></div><h3
id="TypeConverter-DiscoveringFallbackTypeConverters">Discovering Fallback Type
Converters</h3><p><strong>Available in Camel 2.0</strong><br clear="none"> The
<a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>
has been enhanced to also look for methods defined with a @FallbackConverter
annotation, and register it as a fallback type converter.</p><p>Fallback type
converters are used as a last resort for converting a given value to another
type. Its used when the regular type converters give up.<br clear="none"> The
fallback converters is also meant for a broader scope, so its method signature
is a bit different:</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ @FallbackConverter
+</plain-text-body><h3
id="TypeConverter-DiscoveringFallbackTypeConverters">Discovering Fallback Type
Converters</h3><p><strong>Available in Camel 2.0</strong><br clear="none"> The
<a shape="rect" class="external-link"
href="http://camel.apache.org/maven/current/camel-core/apidocs/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.html">AnnotationTypeConverterLoader</a>
has been enhanced to also look for methods defined with a @FallbackConverter
annotation, and register it as a fallback type converter.</p><p>Fallback type
converters are used as a last resort for converting a given value to another
type. Its used when the regular type converters give up.<br clear="none"> The
fallback converters is also meant for a broader scope, so its method signature
is a bit different:</p><plain-text-body> @FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange
exchange, Object value, TypeConverterRegistry registry)
-]]></script>
-</div></div><p>Or you can use the non generic signature.</p><div class="code
panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ @FallbackConverter
+</plain-text-body><p>Or you can use the non generic
signature.</p><plain-text-body> @FallbackConverter
public static Object convertTo(Class type, Exchange exchange, Object
value, TypeConverterRegistry registry)
-]]></script>
-</div></div><p>And the method name can be anything (<code>convertTo</code> is
not required as a name), so it can be named <code>convertMySpecialTypes</code>
if you like.<br clear="none"> The <code>Exchange</code> parameter is optional,
just as its with the regular <code>@Converter</code> methods.</p><p>The purpose
with this broad scope method signature is allowing you to control if you can
convert the given type or not. The <code>type</code> parameter holds the type
we want the <code>value</code> converted to. Its used internally in Camel for
wrapper objects so we can delegate the type convertions to the body that is
wrapped.</p><p>For instance in the method below we will handle all type
conversions that is based on the wrapper class <code>GenericFile</code> and we
let Camel do the type conversions on its body instead.</p><div class="code
panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ @FallbackConverter
+</plain-text-body><p>And the method name can be anything
(<code>convertTo</code> is not required as a name), so it can be named
<code>convertMySpecialTypes</code> if you like.<br clear="none"> The
<code>Exchange</code> parameter is optional, just as its with the regular
<code>@Converter</code> methods.</p><p>The purpose with this broad scope method
signature is allowing you to control if you can convert the given type or not.
The <code>type</code> parameter holds the type we want the <code>value</code>
converted to. Its used internally in Camel for wrapper objects so we can
delegate the type convertions to the body that is wrapped.</p><p>For instance
in the method below we will handle all type conversions that is based on the
wrapper class <code>GenericFile</code> and we let Camel do the type conversions
on its body instead.</p><plain-text-body> @FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange
exchange, Object value, TypeConverterRegistry registry) {
// use a fallback type converter so we can convert the embedded body
if the value is GenericFile
if (GenericFile.class.isAssignableFrom(value.getClass())) {
@@ -188,18 +132,12 @@ public class IOConverter {
return null;
}
-]]></script>
-</div></div><h3 id="TypeConverter-WritingyourownTypeConverters">Writing your
own Type Converters</h3><p> </p><div class="confluence-information-macro
confluence-information-macro-information"><p class="title">Use FQN</p><span
class="aui-icon aui-icon-small aui-iconfont-info
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>In Camel 2.8 the TypeConverter
file now supports specifying the FQN class name. This is recommended to be
used. See below for more details. Using FQN must be used. The older way with
just package name is deprecated and should not be used, and it may also not
work in some application servers due to classpath scanning
issues.</p></div></div><p> </p><p>You are welcome to write your own
converters. Remember to use the @Converter annotations on the classes and
methods you wish to use. Then add the packages to a file called
<em>META-INF/services/org/apache/camel/TypeConverter</em> in your jar. Remember
to make sure tha
t :-</p><ul><li>static methods are encouraged to reduce caching, but instance
methods are fine, particularly if you want to allow optional dependency
injection to customize the converter</li><li>converter methods should be thread
safe and reentrant</li></ul><h4
id="TypeConverter-ExamplesofTypeConverterfile">Examples of TypeConverter
file</h4><p>The file in the JAR:
<code>META-INF/services/org/apache/camel/TypeConverter</code> contains the
following line(s)</p><div class="code panel pdl" style="border-width:
1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[com.foo
+</plain-text-body><h3 id="TypeConverter-WritingyourownTypeConverters">Writing
your own Type Converters</h3><p> </p><parameter ac:name="title">Use
FQN</parameter><rich-text-body><p>In Camel 2.8 the TypeConverter file now
supports specifying the FQN class name. This is recommended to be used. See
below for more details. Using FQN must be used. The older way with just package
name is deprecated and should not be used, and it may also not work in some
application servers due to classpath scanning
issues.</p></rich-text-body><p> </p><p>You are welcome to write your own
converters. Remember to use the @Converter annotations on the classes and
methods you wish to use. Then add the packages to a file called
<em>META-INF/services/org/apache/camel/TypeConverter</em> in your jar. Remember
to make sure that :-</p><ul><li>static methods are encouraged to reduce
caching, but instance methods are fine, particularly if you want to allow
optional dependency injection to customize the conve
rter</li><li>converter methods should be thread safe and
reentrant</li></ul><h4 id="TypeConverter-ExamplesofTypeConverterfile">Examples
of TypeConverter file</h4><p>The file in the JAR:
<code>META-INF/services/org/apache/camel/TypeConverter</code> contains the
following line(s)</p><plain-text-body>com.foo
com.bar
-]]></script>
-</div></div><p>Each line in the file is a package name. This tells Camel to go
scan those packages for any classes that has been annotated with the
@Converter.</p><h3
id="TypeConverter-ImprovedTypeConverterbyusingFQNclassnames">Improved
TypeConverter by using FQN class names</h3><p><strong>Available as of Camel
2.8</strong><br clear="none"> In Camel 2.8 we improved the type converter
loader to support specifying the FQN class name of the converter classes. This
has the advantage of avoiding having to scan packages for @Converter classes.
Instead it loads the @Converter class directly. This is a
<strong>highly</strong> recommend approach to use going forward.</p><h4
id="TypeConverter-ExamplesofTypeConverterfile.1">Examples of TypeConverter
file</h4><p>The file in the JAR:
<code>META-INF/services/org/apache/camel/TypeConverter</code> contains the
following line(s) for FQN class names</p><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[com.foo.MyConverter
+</plain-text-body><p>Each line in the file is a package name. This tells Camel
to go scan those packages for any classes that has been annotated with the
@Converter.</p><h3
id="TypeConverter-ImprovedTypeConverterbyusingFQNclassnames">Improved
TypeConverter by using FQN class names</h3><p><strong>Available as of Camel
2.8</strong><br clear="none"> In Camel 2.8 we improved the type converter
loader to support specifying the FQN class name of the converter classes. This
has the advantage of avoiding having to scan packages for @Converter classes.
Instead it loads the @Converter class directly. This is a
<strong>highly</strong> recommend approach to use going forward.</p><h4
id="TypeConverter-ExamplesofTypeConverterfile.1">Examples of TypeConverter
file</h4><p>The file in the JAR:
<code>META-INF/services/org/apache/camel/TypeConverter</code> contains the
following line(s) for FQN class names</p><plain-text-body>com.foo.MyConverter
com.bar.MyOtherConverter
com.bar.YetOtherConverter
-]]></script>
-</div></div><p>As you can see each line in the file now contains a FQN class
name. This is the recommended approach.</p><h3
id="TypeConverter-Encodingsupportforbyte[]andStringConversion">Encoding support
for byte[] and String Conversion</h3><p><strong>Available in Camel
1.5</strong></p><p>Since Java provides converting the byte[] to String and
String to byte[] with the <a shape="rect" class="external-link"
href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html"
rel="nofollow">charset name</a> parameter. You can define the charset name by
setting the exchange property name <code>Exchange.CHARSET_NAME</code> with the
charset name, such as <code>"UTF-8"</code> or <code>"iso-8859-1"</code>.</p><h3
id="TypeConverter-Exchangeparameter">Exchange
parameter</h3><p><strong>Available in Camel 1.5</strong></p><p>The type
converter accepts the <code>Exchange</code> as an optional 2nd parameter. This
is usable if the type converter for instance needs information from the curr
ent exchange. For instance combined with the encoding support its possible for
type converters to convert with the configured encoding. An example from
camel-core for the <code>byte[] -> String</code> converter:</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[ @Converter
+</plain-text-body><p>As you can see each line in the file now contains a FQN
class name. This is the recommended approach.</p><h3
id="TypeConverter-Encodingsupportforbyte[]andStringConversion">Encoding support
for byte[] and String Conversion</h3><p><strong>Available in Camel
1.5</strong></p><p>Since Java provides converting the byte[] to String and
String to byte[] with the <a shape="rect" class="external-link"
href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html"
rel="nofollow">charset name</a> parameter. You can define the charset name by
setting the exchange property name <code>Exchange.CHARSET_NAME</code> with the
charset name, such as <code>"UTF-8"</code> or <code>"iso-8859-1"</code>.</p><h3
id="TypeConverter-Exchangeparameter">Exchange
parameter</h3><p><strong>Available in Camel 1.5</strong></p><p>The type
converter accepts the <code>Exchange</code> as an optional 2nd parameter. This
is usable if the type converter for instance needs information from th
e current exchange. For instance combined with the encoding support its
possible for type converters to convert with the configured encoding. An
example from camel-core for the <code>byte[] -> String</code>
converter:</p><plain-text-body> @Converter
public static String toString(byte[] data, Exchange exchange) {
if (exchange != null) {
String charsetName = exchange.getProperty(Exchange.CHARSET_NAME,
String.class);
@@ -207,14 +145,13 @@ com.bar.YetOtherConverter
try {
return new String(data, charsetName);
} catch (UnsupportedEncodingException e) {
- LOG.warn("Can't convert the byte to String with
the charset " + charsetName, e);
+ LOG.warn("Can't convert the byte to String with the
charset " + charsetName, e);
}
}
}
return new String(data);
}
-]]></script>
-</div></div></div>
+</plain-text-body></div>
</td>
<td valign="top">
<div class="navigation">
Modified: websites/production/camel/content/websocket.html
==============================================================================
--- websites/production/camel/content/websocket.html (original)
+++ websites/production/camel/content/websocket.html Fri Aug 25 14:20:21 2017
@@ -36,17 +36,6 @@
<![endif]-->
- <link href='//camel.apache.org/styles/highlighter/styles/shCoreCamel.css'
rel='stylesheet' type='text/css' />
- <link href='//camel.apache.org/styles/highlighter/styles/shThemeCamel.css'
rel='stylesheet' type='text/css' />
- <script src='//camel.apache.org/styles/highlighter/scripts/shCore.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushJava.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushXml.js'
type='text/javascript'></script>
- <script src='//camel.apache.org/styles/highlighter/scripts/shBrushPlain.js'
type='text/javascript'></script>
-
- <script type="text/javascript">
- SyntaxHighlighter.defaults['toolbar'] = false;
- SyntaxHighlighter.all();
- </script>
<title>
Apache Camel: Websocket
@@ -86,33 +75,17 @@
<tbody>
<tr>
<td valign="top" width="100%">
-<div class="wiki-content maincontent"><h2
id="Websocket-WebsocketComponent">Websocket Component</h2><p><strong>Available
as of Camel 2.10</strong></p><p>The <strong>websocket</strong> component
provides websocket <a shape="rect" href="endpoint.html">endpoints</a> for
communicating with clients using websocket. The component uses Eclipse Jetty
Server which implements the <a shape="rect" class="external-link"
href="http://tools.ietf.org/html/rfc6455" rel="nofollow">IETF</a> specification
(drafts and RFC 6455). It supports the protocols ws:// and wss://. To use
wss:// protocol, the SSLContextParameters must be defined.</p><div
class="confluence-information-macro
confluence-information-macro-information"><p class="title">Version currently
supported</p><span class="aui-icon aui-icon-small aui-iconfont-info
confluence-information-macro-icon"></span><div
class="confluence-information-macro-body"><p>As Camel 2.10 uses Jetty
7.5.4.v20111024, only the D00 to <a shape="rect" class="external-li
nk" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-13"
rel="nofollow">D13</a> IETF implementations are available.<br clear="none">
Camel 2.11 uses Jetty 7.6.7.</p></div></div><h3 id="Websocket-URIformat">URI
format</h3><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[websocket://hostname[:port][/resourceUri][?options]
-]]></script>
-</div></div><p>You can append query options to the URI in the following
format, <code>?option=value&option=value&...</code></p><h3
id="Websocket-ComponentOptions">Component Options</h3><p>The
<code>WebsocketComponent</code> can be configured prior to use, to setup host,
to act as a websocket server.</p><div class="table-wrap"><table
class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1"
class="confluenceTh"><p>Option</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>host</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>0.0.0.0</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>The hostname.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>port</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>9292</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>The p
ort number.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>staticResources</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>Path for static resources such as index.html files etc.
If this option has been configured, then a server is started on the given
hostname and port, to service the static resources, eg such as an index.html
file. If this option has not been configured, then no server is
started.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>sslContextParameters</p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>Reference to a
<code>org.apache.camel.util.jsse.SSLContextParameters</code> in the <a
shape="rect" class="external-link"
href="http://camel.apache.org/registry.html">Registry</a>. This reference
overrides any configured SSLContextParameters at the component level.&
#160; See <a shape="rect" href="camel-configuration-utilities.html">Using the
JSSE Configuration Utility</a>.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>enableJmx</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>false</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p>If this option is true, Jetty JMX support
will be enabled for this endpoint. See <a shape="rect"
href="#Websocket-JettyJMXsupport">Jetty JMX support</a> for more
details.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>sslKeyPassword</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>: The
password for the keystore when using SSL.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>sslPassword</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code><
/p></td><td colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer
only</strong>: The password when using SSL.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>sslKeystore</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>:
The path to the keystore.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>minThreads</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>1</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>: To set a
value for minimum number of threads in server thread pool. <strong>From Camel
2.18</strong>: MinThreads/MaxThreads or threadPool fields are required due to
switch to Jetty 9</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>maxThreads</code></p></td><td colspan="1"
rowspan="1" class="conflue
nceTd"><p><code>1 + noCores * 2<br clear="none"></code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>:
To set a value for maximum number of threads in server thread pool.
<strong>From Camel 2.18</strong>: MinThreads/MaxThreads or threadPool fields
are required due to switch to Jetty 9</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>threadPool</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>:
To use a custom thread pool for the server. <strong>From Camel 2.18</strong>:
MinThreads/MaxThreads or threadPool fields are required due to switch to Jetty
9</p></td></tr></tbody></table></div><h3
id="Websocket-EndpointOptions">Endpoint Options</h3><p>The
<code>WebsocketEndpoint</code> can be configured prior to use</p><div
class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1"
rowspan="1" class="confluenceTh"><p>Option</p></th><th colspan="1"
rowspan="1" class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>sslContextParametersRef</p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Deprecated and will be removed in
Camel 3.0:</strong> Reference to a
<code>org.apache.camel.util.jsse.SSLContextParameters</code> in the <a
shape="rect" class="external-link"
href="http://camel.apache.org/registry.html">Registry</a>.  This reference
overrides any configured SSLContextParameters at the component level. See <a
shape="rect" href="camel-configuration-utilities.html">Using the JSSE
Configuration Utility</a>. Use the <code>sslContextParameters</code> option
instead</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>sslContextParameters</p></td><
td colspan="1" rowspan="1" class="confluenceTd"><p> </p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Camel 2.11.1:</strong>
Reference to a <code>org.apache.camel.util.jsse.SSLContextParameters</code> in
the <a shape="rect" class="external-link"
href="http://camel.apache.org/registry.html">Registry</a>. This reference
overrides any configured SSLContextParameters at the component level.  See
<a shape="rect" href="camel-configuration-utilities.html">Using the JSSE
Configuration Utility</a>.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>sendToAll</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Producer only:</strong> To send to all
websocket subscribers. Can be used to configure on endpoint level, instead of
having to use the <code>WebsocketConstants.SEND_TO_ALL</code> header on the
message.</p></td></tr><tr><td colspan="1" rowspan="1" c
lass="confluenceTd"><p>staticResources</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>The root directory for the web resources or classpath.
Use the protocol file: or classpath: depending if you want that the component
loads the resource from file system or classpath.</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p> bufferSize</p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Camel 2.12.3:</strong>
set the buffer size of the websocketServlet, which is also the max frame byte
size (default 8192)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxIdleTime</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> set the time in ms that
the websoc
ket created by the websocketServlet may be idle before closing. (default is
300000)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxTextMessageSize</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used to set the
size in characters that the websocket created by the websocketServlet may be
accept before closing.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxBinaryMessageSize</p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used
to set the size in bytes that the websocket created by the websocketServlet may
be accept before closing. (Default is -1 - or unlimited)</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p>minVersion</p></td><td
colspan="1" rowspan="1" class="co
nfluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used to set the
minimum protocol version accepted for the websocketServlet. (Default 13 - the
RFC6455 version)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd">sendTimeout</td><td colspan="1" rowspan="1"
class="confluenceTd">30000</td><td colspan="1" rowspan="1"
class="confluenceTd"><strong>Camel 2.18:</strong> Timeout in millis when
sending to a websocket channel. The default timeout is 30000 (30
seconds).</td></tr></tbody></table></div><p> </p><h3
id="Websocket-MessageHeaders">Message Headers</h3><p>The websocket component
uses 2 headers to indicate to either send messages back to a single/current
client, or to all clients.</p><div class="table-wrap"><table
class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1"
class="confluenceTh"><p>Key</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr>
<tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>WebsocketConstants.SEND_TO_ALL</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>Sends the message to all
clients which are currently connected. You can use the <code>sendToAll</code>
option on the endpoint instead of using this header.</p></td></tr><tr><td
colspan="1" rowspan="1"
class="confluenceTd"><p><code>WebsocketConstants.CONNECTION_KEY</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p>Sends the message to the
client with the given connection key.</p></td></tr></tbody></table></div><h3
id="Websocket-Usage">Usage</h3><p>In this example we let Camel exposes a
websocket server which clients can communicate with. The websocket server uses
the default host and port, which would be <code>0.0.0.0:9292</code>.<br
clear="none"> The example will send back an echo of the input. To send back a
message, we need to send the transformed message to the same endpoint
<code>"websocket://echo"</code>
. This is needed<br clear="none"> because by default the messaging is
InOnly.</p><div class="code panel pdl" style="border-width: 1px;"><div
class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[
-// expose a echo websocket client, that sends back an echo
-from("websocket://echo")
- .log(">>> Message received from WebSocket Client :
${body}")
- .transform().simple("${body}${body}")
- // send back to the client, by sending the message to the same endpoint
- // this is needed as by default messages is InOnly
- // and we will by default send back to the current client using the
provided connection key
- .to("websocket://echo");
-]]></script>
-</div></div>This example is part of an unit test, which you can find <a
shape="rect" class="external-link"
href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketRouteExampleTest.java">here</a>.
As a client we use the <a shape="rect" href="ahc.html">AHC</a> library which
offers support for web socket as well.<p>Here is another example where webapp
resources location have been defined to allow the Jetty Application Server to
not only register the WebSocket servlet but also to expose web resources for
the browser. Resources should be defined under the webapp directory.</p><div
class="code panel pdl" style="border-width: 1px;"><div class="codeContent
panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[from("activemq:topic:newsTopic")
- .routeId("fromJMStoWebSocket")
-
.to("websocket://localhost:8443/newsTopic?sendToAll=true&staticResources=classpath:webapp");
-]]></script>
-</div></div><h3 id="Websocket-SettingupSSLforWebSocketComponent">Setting up
SSL for WebSocket Component</h3><h4
id="Websocket-UsingtheJSSEConfigurationUtility">Using the JSSE Configuration
Utility</h4><p>As of Camel 2.10, the WebSocket component supports SSL/TLS
configuration through the <a shape="rect"
href="camel-configuration-utilities.html">Camel JSSE Configuration
Utility</a>.  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 Cometd component.</p><h5
id="Websocket-Programmaticconfigurationofthecomponent">Programmatic
configuration of the component</h5><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[KeyStoreParameters ksp = new
KeyStoreParameters();
-ksp.setResource("/users/home/server/keystore.jks");
-ksp.setPassword("keystorePassword");
+<div class="wiki-content maincontent"><h2
id="Websocket-WebsocketComponent">Websocket Component</h2><p><strong>Available
as of Camel 2.10</strong></p><p>The <strong>websocket</strong> component
provides websocket <a shape="rect" href="endpoint.html">endpoints</a> for
communicating with clients using websocket. The component uses Eclipse Jetty
Server which implements the <a shape="rect" class="external-link"
href="http://tools.ietf.org/html/rfc6455" rel="nofollow">IETF</a> specification
(drafts and RFC 6455). It supports the protocols ws:// and wss://. To use
wss:// protocol, the SSLContextParameters must be defined.</p><parameter
ac:name="title">Version currently supported</parameter><rich-text-body><p>As
Camel 2.10 uses Jetty 7.5.4.v20111024, only the D00 to <a shape="rect"
class="external-link"
href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-13"
rel="nofollow">D13</a> IETF implementations are available.<br clear="none">
Camel 2.11 uses Jetty 7.6.7.</p></rich-
text-body><h3 id="Websocket-URIformat">URI
format</h3><plain-text-body>websocket://hostname[:port][/resourceUri][?options]
+</plain-text-body><p>You can append query options to the URI in the following
format, <code>?option=value&option=value&...</code></p><h3
id="Websocket-ComponentOptions">Component Options</h3><p>The
<code>WebsocketComponent</code> can be configured prior to use, to setup host,
to act as a websocket server.</p><div class="table-wrap"><table
class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1"
class="confluenceTh"><p>Option</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>host</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>0.0.0.0</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>The hostname.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>port</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p>9292</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p
>The port number.</p></td></tr><tr><td colspan="1" rowspan="1"
>class="confluenceTd"><p>staticResources</p></td><td colspan="1" rowspan="1"
>class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
>class="confluenceTd"><p>Path for static resources such as index.html files
>etc. If this option has been configured, then a server is started on the
>given hostname and port, to service the static resources, eg such as an
>index.html file. If this option has not been configured, then no server is
>started.</p></td></tr><tr><td colspan="1" rowspan="1"
>class="confluenceTd"><p>sslContextParameters</p></td><td colspan="1"
>rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1"
>rowspan="1" class="confluenceTd"><p>Reference to a
><code>org.apache.camel.util.jsse.SSLContextParameters</code> in the <a
>shape="rect" class="external-link"
>href="http://camel.apache.org/registry.html">Registry</a>. This reference
>overrides any configured SSLContextParameters at the component l
evel.  See <a shape="rect"
href="camel-configuration-utilities.html">Using the JSSE Configuration
Utility</a>.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>enableJmx</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>false</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p>If this option is true, Jetty JMX support
will be enabled for this endpoint. See <a shape="rect"
href="#Websocket-JettyJMXsupport">Jetty JMX support</a> for more
details.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>sslKeyPassword</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>: The
password for the keystore when using SSL.</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>sslPassword</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</
code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Consumer only</strong>: The password when using
SSL.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>sslKeystore</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>: The path to
the keystore.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>minThreads</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>1</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>: To set a
value for minimum number of threads in server thread pool. <strong>From Camel
2.18</strong>: MinThreads/MaxThreads or threadPool fields are required due to
switch to Jetty 9</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>maxThreads</code></p></td><td colspan="1"
rowspan="1" class="c
onfluenceTd"><p><code>1 + noCores * 2<br clear="none"></code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>:
To set a value for maximum number of threads in server thread pool.
<strong>From Camel 2.18</strong>: MinThreads/MaxThreads or threadPool fields
are required due to switch to Jetty 9</p></td></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>threadPool</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Consumer only</strong>:
To use a custom thread pool for the server. <strong>From Camel 2.18</strong>:
MinThreads/MaxThreads or threadPool fields are required due to switch to Jetty
9</p></td></tr></tbody></table></div><h3
id="Websocket-EndpointOptions">Endpoint Options</h3><p>The
<code>WebsocketEndpoint</code> can be configured prior to use</p><div
class="table-wrap"><table class="confluenceTable"><tbody><tr><th colsp
an="1" rowspan="1" class="confluenceTh"><p>Option</p></th><th colspan="1"
rowspan="1" class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th></tr><tr><td colspan="1"
rowspan="1" class="confluenceTd"><p>sslContextParametersRef</p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p> </p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Deprecated and will be removed in
Camel 3.0:</strong> Reference to a
<code>org.apache.camel.util.jsse.SSLContextParameters</code> in the <a
shape="rect" class="external-link"
href="http://camel.apache.org/registry.html">Registry</a>.  This reference
overrides any configured SSLContextParameters at the component level. See <a
shape="rect" href="camel-configuration-utilities.html">Using the JSSE
Configuration Utility</a>. Use the <code>sslContextParameters</code> option
instead</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>sslContextParameters</p>
</td><td colspan="1" rowspan="1" class="confluenceTd"><p> </p></td><td
colspan="1" rowspan="1" class="confluenceTd"><p><strong>Camel 2.11.1:</strong>
Reference to a <code>org.apache.camel.util.jsse.SSLContextParameters</code> in
the <a shape="rect" class="external-link"
href="http://camel.apache.org/registry.html">Registry</a>. This reference
overrides any configured SSLContextParameters at the component level.  See
<a shape="rect" href="camel-configuration-utilities.html">Using the JSSE
Configuration Utility</a>.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>sendToAll</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Producer only:</strong> To send to all
websocket subscribers. Can be used to configure on endpoint level, instead of
having to use the <code>WebsocketConstants.SEND_TO_ALL</code> header on the
message.</p></td></tr><tr><td colspan="1" rowspan
="1" class="confluenceTd"><p>staticResources</p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p>The root directory for the web resources or
classpath. Use the protocol file: or classpath: depending if you want that the
component loads the resource from file system or
classpath.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p> bufferSize</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> set the buffer size of
the websocketServlet, which is also the max frame byte size (default
8192)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxIdleTime</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> set the time in ms that
the
websocket created by the websocketServlet may be idle before closing. (default
is 300000)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxTextMessageSize</p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used to set the
size in characters that the websocket created by the websocketServlet may be
accept before closing.</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd"><p>maxBinaryMessageSize</p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><code>null</code></p></td><td colspan="1"
rowspan="1" class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used
to set the size in bytes that the websocket created by the websocketServlet may
be accept before closing. (Default is -1 - or unlimited)</p></td></tr><tr><td
colspan="1" rowspan="1" class="confluenceTd"><p>minVersion</p></td><td
colspan="1" rowspan="1" cla
ss="confluenceTd"><p><code>null</code></p></td><td colspan="1" rowspan="1"
class="confluenceTd"><p><strong>Camel 2.12.3:</strong> can be used to set the
minimum protocol version accepted for the websocketServlet. (Default 13 - the
RFC6455 version)</p></td></tr><tr><td colspan="1" rowspan="1"
class="confluenceTd">sendTimeout</td><td colspan="1" rowspan="1"
class="confluenceTd">30000</td><td colspan="1" rowspan="1"
class="confluenceTd"><strong>Camel 2.18:</strong> Timeout in millis when
sending to a websocket channel. The default timeout is 30000 (30
seconds).</td></tr></tbody></table></div><p> </p><h3
id="Websocket-MessageHeaders">Message Headers</h3><p>The websocket component
uses 2 headers to indicate to either send messages back to a single/current
client, or to all clients.</p><div class="table-wrap"><table
class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1"
class="confluenceTh"><p>Key</p></th><th colspan="1" rowspan="1"
class="confluenceTh"><p>Description</p></th
></tr><tr><td colspan="1" rowspan="1"
>class="confluenceTd"><p><code>WebsocketConstants.SEND_TO_ALL</code></p></td><td
> colspan="1" rowspan="1" class="confluenceTd"><p>Sends the message to all
>clients which are currently connected. You can use the <code>sendToAll</code>
>option on the endpoint instead of using this header.</p></td></tr><tr><td
>colspan="1" rowspan="1"
>class="confluenceTd"><p><code>WebsocketConstants.CONNECTION_KEY</code></p></td><td
> colspan="1" rowspan="1" class="confluenceTd"><p>Sends the message to the
>client with the given connection key.</p></td></tr></tbody></table></div><h3
>id="Websocket-Usage">Usage</h3><p>In this example we let Camel exposes a
>websocket server which clients can communicate with. The websocket server
>uses the default host and port, which would be <code>0.0.0.0:9292</code>.<br
>clear="none"> The example will send back an echo of the input. To send back a
>message, we need to send the transformed message to the same endpoint
><code>"websocket://echo"<
/code>. This is needed<br clear="none"> because by default the messaging is
InOnly.<plain-text-body>{snippet:id=e1|lang=java|url=camel/trunk/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketRouteExampleTest.java}</plain-text-body>This
example is part of an unit test, which you can find <a shape="rect"
class="external-link"
href="https://svn.apache.org/repos/asf/camel/trunk/components/camel-websocket/src/test/java/org/apache/camel/component/websocket/WebsocketRouteExampleTest.java">here</a>.
As a client we use the <a shape="rect" href="ahc.html">AHC</a> library which
offers support for web socket as well.</p><p>Here is another example where
webapp resources location have been defined to allow the Jetty Application
Server to not only register the WebSocket servlet but also to expose web
resources for the browser. Resources should be defined under the webapp
directory.</p><parameter
ac:name="">java</parameter><plain-text-body>from("activemq:topic:n
ewsTopic")
+ .routeId("fromJMStoWebSocket")
+
.to("websocket://localhost:8443/newsTopic?sendToAll=true&staticResources=classpath:webapp");
+</plain-text-body><h3 id="Websocket-SettingupSSLforWebSocketComponent">Setting
up SSL for WebSocket Component</h3><h4
id="Websocket-UsingtheJSSEConfigurationUtility">Using the JSSE Configuration
Utility</h4><p>As of Camel 2.10, the WebSocket component supports SSL/TLS
configuration through the <a shape="rect"
href="camel-configuration-utilities.html">Camel JSSE Configuration
Utility</a>.  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 Cometd component.</p><h5
id="Websocket-Programmaticconfigurationofthecomponent">Programmatic
configuration of the component</h5><plain-text-body>KeyStoreParameters ksp =
new KeyStoreParameters();
+ksp.setResource("/users/home/server/keystore.jks");
+ksp.setPassword("keystorePassword");
KeyManagersParameters kmp = new KeyManagersParameters();
kmp.setKeyStore(ksp);
-kmp.setKeyPassword("keyPassword");
+kmp.setKeyPassword("keyPassword");
TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);
@@ -121,46 +94,40 @@ SSLContextParameters scp = new SSLContex
scp.setKeyManagers(kmp);
scp.setTrustManagers(tmp);
-CometdComponent commetdComponent =
getContext().getComponent("cometds", CometdComponent.class);
+CometdComponent commetdComponent = getContext().getComponent("cometds",
CometdComponent.class);
commetdComponent.setSslContextParameters(scp);
-]]></script>
-</div></div><h5 id="Websocket-SpringDSLbasedconfigurationofendpoint">Spring
DSL based configuration of endpoint</h5><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: xml; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[...
+</plain-text-body><h5
id="Websocket-SpringDSLbasedconfigurationofendpoint">Spring DSL based
configuration of endpoint</h5><parameter
ac:name="">xml</parameter><plain-text-body>...
<camel:sslContextParameters
- id="sslContextParameters">
+ id="sslContextParameters">
<camel:keyManagers
- keyPassword="keyPassword">
+ keyPassword="keyPassword">
<camel:keyStore
- resource="/users/home/server/keystore.jks"
- password="keystorePassword"/>
+ resource="/users/home/server/keystore.jks"
+ password="keystorePassword"/>
</camel:keyManagers>
<camel:trustManagers>
<camel:keyStore
- resource="/users/home/server/keystore.jks"
- password="keystorePassword"/>
+ resource="/users/home/server/keystore.jks"
+ password="keystorePassword"/>
</camel:trustManagers>
</camel:sslContextParameters>...
...
- <to
uri="websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters"/>...
-]]></script>
-</div></div><h5 id="Websocket-JavaDSLbasedconfigurationofendpoint">Java DSL
based configuration of endpoint</h5><div class="code panel pdl"
style="border-width: 1px;"><div class="codeContent panelContent pdl">
-<script class="brush: java; gutter: false; theme: Default"
type="syntaxhighlighter"><![CDATA[...
+ <to
uri="websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters"/>...
+</plain-text-body><h5 id="Websocket-JavaDSLbasedconfigurationofendpoint">Java
DSL based configuration of endpoint</h5><parameter
ac:name="">java</parameter><plain-text-body>...
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
public void configure() {
- String uri =
"websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters";
+ String uri =
"websocket://127.0.0.1:8443/test?sslContextParameters=#sslContextParameters";
from(uri)
- .log(">>> Message received from WebSocket
Client : ${body}")
- .to("mock:client")
+ .log(">>> Message received from WebSocket Client
: ${body}")
+ .to("mock:client")
.loop(10)
- .setBody().constant(">> Welcome on
board!")
+ .setBody().constant(">> Welcome on board!")
.to(uri);
...
-]]></script>
-</div></div><p></p><h3 id="Websocket-SeeAlso">See Also</h3>
-<ul><li><a shape="rect" href="configuring-camel.html">Configuring
Camel</a></li><li><a shape="rect"
href="component.html">Component</a></li><li><a shape="rect"
href="endpoint.html">Endpoint</a></li><li><a shape="rect"
href="getting-started.html">Getting Started</a></li></ul><ul
class="alternate"><li><a shape="rect" href="ahc.html">AHC</a></li><li><a
shape="rect" href="jetty.html">Jetty</a></li><li><a shape="rect"
href="twitter-websocket-example.html">Twitter Websocket Example</a>
demonstrates how to poll a constant feed of twitter searches and publish
results in real time using web socket to a web page.</li></ul></div>
+</plain-text-body><p><parameter ac:name=""><a shape="rect"
href="endpoint-see-also.html">Endpoint See Also</a></parameter></p><ul
class="alternate"><li><a shape="rect" href="ahc.html">AHC</a></li><li><a
shape="rect" href="jetty.html">Jetty</a></li><li><a shape="rect"
href="twitter-websocket-example.html">Twitter Websocket Example</a>
demonstrates how to poll a constant feed of twitter searches and publish
results in real time using web socket to a web page.</li></ul></div>
</td>
<td valign="top">
<div class="navigation">