Search code examples
javaapache-camelosgicamel-cxf

Camel DefaultMessage cannot be created without CamelContext in version 2.23.0


My actual code (Camel 2.10.x) create a new Camel Message to wrap some data (http query) like this:

Message message = new DefaultMessage();
message.setHeader(HEADER_QUERY, query);
message.setHeader(HEADER_BRAND, brand);
message.setHeader(HEADER_LIST_ID, listId);

And while I am migrating my platform, the version of Camel we use is: 2.23.0 and we can see now the empty constructor is deprecated. When executing the code, we have the same issue as mentioned in this post from the official Camel forum.

The good way seems to create the Message by using the Constructor with the CamelContext in parameter like this:

Message message = new DefaultMessage(camelContext);
message.setHeader(HEADER_QUERY, query);
message.setHeader(HEADER_BRAND, brand);
message.setHeader(HEADER_LIST_ID, listId);

I am in an OSGI context but the code is in a Bean where I have not the Exchange nor the original Message available. I am just wondering how can I provide the CamelContext to the Message constructor or if there is another way to create DefaultMessage without the CamelContext.

Note that I am not in a Camel Route, the Bean is called from a REST interface (I suspect there are some refactoring to clean this up, but we plan to decommission this soon). I am looking for a quick win solution.


Solution

  • Unfortunately the solution with Main.getInstance().getOrCreateCamelContext() seems not working in my context (OSGI): the Main.getInstance() always returns null.

    But I finally found another way to make it work:

    First Step

    Inject the bundleContext into my Bean:

    <bean id="myCustomMessageFactory" class="org.mycompany.module.factory.CustomMessageFactory">
        <property name="bundleContext" ref="blueprintBundleContext" />
    </bean>
    

    The blueprintBundleContext is automatically set and does not need to be declared.

    Second step

    from the Bean (Java code):

    ServiceReference sr = bundleContext.getServiceReference(CamelContext.class);
    CamelContext camelContext = (CamelContext) bundleContext.getService(sr);
    // and then I can inject the camelContext into the message constructor
    Message message = new DefaultMessage(camelContext);
    

    It works perfectly in the OSGI landscape.