Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 4.0

The Smooks JavaBean Cartridge allows you to create and populate Java objects from your message data (i.e. bind data to). You need to add the milyn-smooks-javabean-1.1.jar to your classpath. If you are using Maven then add the org.milyn:milyn-smooks-javabean:1.1 dependency to the POM.

Note: As you know, Smooks supports a range of source data formats (XML, EDI, CSV, Java etc), but for the purposes of this topic, we will always refer to the message data in terms of an XML format.

In the examples we will be referring a lot to the following XML message data:

No Format
<order>
    <header>
        <date>Wed Nov 15 13:45:28 EST 2006</date>
        <customer number="123123">Joe</customer>
    </header>
    <order-items>
        <order-item>
            <product>111</product>
            <quantity>2</quantity>
            <price>8.90</price>
        </order-item>
        <order-item>
            <product>222</product>
            <quantity>7</quantity>
            <price>5.20</price>
        </order-item>
    </order-items>
</order>

In some examples we will use different XML message data. Where this happens, the data is explicitly defined there then.

The JavaBean Cartridge is used via the http://www.milyn.org/xsd/smooks/javabean-1.1.xsd configuration namespace. Install the schema in your IDE and avail of autocompletion.

An example configuration:

No Format
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" 
                      xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd">

    <jb:bindings beanId="order" class="example.model.Order" createOnElement="$document" />

</smooks-resource-list>

This configuration simply creates an instance of the example.model.Order class and binds it into the bean context under the beanId "order". The instance is created at the very start of the message on the $document element (i.e. the start of the root <order> element).

Info
titlecreateOnElement

The createOnElement attribute controls when the bean instance is created. Population of the bean properties is controlled through the binding configurations (child elements of the <jb:bindings> element).

The namespace of the createOnElement can be specified via the createOnElementNS attribute.

The bean context (also known as "bean map") is a very important part of the JavaBean Cartridge. One bean context is created per execution context (i.e. per Smooks.filter operation). Every bean, created by the cartridge, is put into this context under its beanId. If you want the contents of the bean context to be returned at the end of the Smooks.filter process, supply a org.milyn.delivery.java.JavaResult object in the call to Smooks.filter method. The following example illustrates this principal:

No Format
//Get the data to filter
StreamSource source = new StreamSource(getClass().getResourceAsStream("data.xml"));

//Create a Smooks instance (cachable)
Smooks smooks = new Smooks("smooks-config.xml");

//Create the JavaResult, which will contain the filter result after filtering
JavaResult result = new JavaResult();

//Filter the data from the source, putting the result into the JavaResult
smooks.filter(source, result);

//Getting the Order bean which was created by the JavaBean cartridge
Order order = (Order)result.getBean("order")

If you need to access the bean context beans at runtime (e.g. from a customer Visitor implementation), you do so via the BeanRepository class.

The Javabean cartridge has the following conditions for javabeans:

  1. A public no-argument constructor
  2. Public property setter methods. The don't need to follow any specific name formats, but it would be better if they do follow the standard property setter method names.
  3. Setting javabean properties directly is not supported.

Data binding

The configuration shown above simply created the example.model.Order bean instance and bound it into the bean context. This section will describe how to bind data into that bean instance.

The Javabean Cartridge provides support for 3 types of data bindings, which are added as child elements of the <jb:bindings> element:

<jb:value>

Value binding, via the <jb:value> binding configuration. This is used to bind data values from the Source message event stream into the target bean.

<jb:wiring>

Wiring binding, via the <jb:wiring> binding configuration. This is used to "wire" another bean instance from the bean context into a bean property on the target bean. This is the configuration that allows you to construct an object graph (Vs just a loose bag of Java object instances).

<jb:expression>

Expression based binding, via the <jb:expression> configuration. As it's name suggests, this configuration is used to bind in a value calculated from an expression, a simple example being the binding of an order item total value into an OrderItem bean based on the result of an expression that calculates the value from the items price and quantity (e.g. "price * quantity").

Taking the Order XML message (previous section), lets see what the full XML to Java binding configuration might be. We've seen the order XML (above). Now lets look at the Java Objects that we want to populate from that XML message (getters and setters not shown):

No Format
public class Order {
    private Header header;
    private List<OrderItem> orderItems;
}

public class Header {
    private Date date;
    private Long customerNumber;
    private String customerName;
    private double total;
}

public class OrderItem {
    private long productId;
    private Integer quantity;
    private double price;
}

The Smooks config required to bind the data from the order XML and into this object model is as follows:

No Format
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd">

(1)   <jb:bindings beanId="order" class="com.acme.Order" createOnElement="order">
(1.a)     <jb:wiring property="header" beanIdRef="header" />
(1.b)     <jb:wiring property="orderItems" beanIdRef="orderItems" />
      </jb:bindings>

(2)   <jb:bindings beanId="header" class="com.acme.Header" createOnElement="order">
(2.a)     <jb:value property="date" decoder="Date" data="header/date">
              <jb:decodeParam name="format">EEE MMM dd HH:mm:ss z yyyy</jb:decodeParam>
          </jb:value>
(2.b)     <jb:value property="customerNumber" decoder="Long" data="header/customer/@number" />
(2.c)     <jb:value property="customerName" data="header/customer" />
(2.d)     <jb:expression property="total" execOnElement="order-item" >
              header.total + (orderItem.price * orderItem.quantity);
          </jb:expression>
      </jb:bindings>

(3)   <jb:bindings beanId="orderItems" class="java.util.ArrayList" createOnElement="order">
(3.a)     <jb:wiring beanIdRef="orderItem" />
      </jb:bindings>

(4)   <jb:bindings beanId="orderItem" class="com.acme.OrderItem" createOnElement="order-item">
(4.a)     <jb:value property="productId" decoder="Long" data="order-item/product" />
(4.b)     <jb:value property="quantity" decoder="Integer" data="order-item/quantity" />
(4.c)     <jb:value property="price" decoder="Double" data="order-item/price" />
      </jb:bindings>

</smooks-resource-list>

(1)

Configuration (1) defines the creation rules for the com.acme.Order bean instance (top level bean). We create this bean instance at the very start of the message i.e. on the <order> element (createOnElement="order"). In fact, we create the each of the beans instances ((1), (2), (3) - all accepts the (4)) at the very start of the message (on the <order> element). We do this because there will only ever be a single instance of these beans in the populated model. Configurations (1.a) and (1.b) define the wiring configuration for wiring the Header and List<OrderItem> bean instances ((2) and (3)) into the Order bean instance (see the beanIdRef attribute values and how the reference the beanId values defined on (2) and (3)). The property attributes on (1.a) and (1.b) define the Order bean properties on which the wirings are to be made.

(2)

Configuration (2) creates the com.acme.Header bean instance. Configuration (2.a) defines a value binding onto the Header.date property. Note that the data attribute defines where the binding value is selected from the source message; in this case it is coming from the header/date element. Also note how it defines a decodeParam sub-element. This configures the Date Decoder (decoder="Date").

Configuration (2.b) defines a value binding configuration onto Header.customerNumber property. What should be noted here is how to configure the data attribute to select a binding value from an element attribute on the source message.

Configuration (2.b) defines an expression binding where the order total is calculated and set on the Header.total property. The execOnElement attribute tells Smooks that this expression needs to be evaluated (and bound/rebound) on the <order-item> element. So, if there are multiple <order-item> elements in the source message, this expression will be executed for each <order-item> and the new total value rebound into the Header.total property. Note how the expression adds the current orderItem total to the current order total (header.total).

(3)

Configuration (3) creates the List<OrderItem> bean instance for holding the OrderItem instances. Configuration (3.a) wires in the orderItem bean ((4)) instances into the list. Note how this wiring does not define a property attribute. This is because it wires into a Collection (same applies if wiring into an array).

(4)

Configuration (4) creates the OrderItem bean instances. Note how the createOnElement is set to the <order-item> element. This is because we want a new instance of this bean to be created for every <order-item> element (and wired into the List<OrderItem> (3.a)). If the createOnElement attribute for this configuration was not set to the <order-item> element (e.g. if it was set to one of the <order>, <header> or <order-items> elements), then only a single OrderItem bean instance would be created and the binding configurations ((4.a) etc) would overwrite the bean instance property bindings for every <order-item> element in the source message i.e. you would be left with a List<OrderItem> with just a single OrderItem instance containing the <order-item> data from the last <order-item> encountered in the source message.

Info
titleBinding Tips
  • <jb:bindings createOnElement>
    1. Set to the root element (or "$document"): For bean instances where only a single instance will exist in the model.
    2. Set to the recurring element: For Collection bean instances. If you don't specify the correct element in this case, you could loose data.
  • <jb:value decoder>
    1. Some of decoders require configuration. See the full list of DataDecoder available out of the box.
  • <jb:wiring property>
    1. Not required when binding into Collections.
  • <jb:expression execOnElement>
    1. Explicitly tells Smooks when the expression is to be evaluated and the result bound. If not defined, the expression is executed based on the value of the parent <jb:bindings createOnElement>.
  • Collections
    1. Just define the <jb:bindings class> to be the required Collection type and wire in the Collection entries.
    2. For arrays, just postfix the <jb:bindings class> attribute value with square barkets e.g. class="com.acme.OrderItem[]".

Extended Lifecycle Bindings

Binding Key Value Pairs into Maps

If the <jb:value property> attribute of a binding is not defined (or is empty), then the name of the selected node will be used as the map entry key (where the beanClass is a Map).

There is one other way to define the map key. The value of the <jb:value property> attribute can start with the @ character. The rest of the value then defines the attribute name of the selected node, from which the map key is selected. The following example demonstrates this:

No Format
<root>
   <property name="key1">value1</property>
   <property name="key2">value2</property>
   <property name="key3">value3</property>
</root>

An the config:

No Format
<jb:bindings beanId="keyValuePairs" class="java.util.HashMap" createOnElement="root">
    <jb:value property="@name" data="root/property" />
</jb:bindings>

This would create a HashMap with three entries with the keys set [key1, key2, key3].

Off course the @ character notation doesn't work for bean wiring. The cartridge will simply use the value of the property attribute, including the @ character, as the map entry key.

Virtual Object Models (Maps & Lists)

It is possible to create a complete object model without writing your own Bean classes. This virtual model is created using only maps and lists . This is very convenient if you use the javabean cartridge between two processing steps. For example from xml -> java -> edi.

The following example demonstrates the principle:

No Format
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd">

    <jb:bindings beanId="order" class="java.util.HashMap" createOnElement="order">
        <jb:wiring property="header" beanIdRef="header" />
        <jb:wiring property="orderItems" beanIdRef="orderItems" />
    </jb:bindings>

    <jb:bindings beanId="header" class="java.util.HashMap" createOnElement="order">
        <jb:value property="date" decoder="Date" data="header/date">
            <jb:decodeParam name="format">EEE MMM dd HH:mm:ss z yyyy</jb:decodeParam>
        </jb:value>
        <jb:value property="customerNumber" decoder="Long" data="header/customer/@number" />
        <jb:value property="customerName" data="header/customer" />
        <jb:expression property="total" execOnElement="order-item" >
              header.total + (orderItem.price * orderItem.quantity);
        </jb:expression>
    </jb:bindings>

    <jb:bindings beanId="orderItems" class="java.util.ArrayList" createOnElement="order">
        <jb:wiring beanIdRef="orderItem" />
    </jb:bindings>

    <jb:bindings beanId="orderItem" class="java.util.HashMap" createOnElement="order-item">
         <jb:value property="productId" decoder="Long" data="order-item/product" />
         <jb:value property="quantity" decoder="Integer" data="order-item/quantity" />
         <jb:value property="price" decoder="Double" data="order-item/price" />
    </jb:bindings>

</smooks-resource-list>

Take a look at the milyn/smooks-examples/xml-to-java-virtual for another example.

Merging Multiple Data Entities Into a Single Binding

This can be achieved using Expression Based Bindings (<jb:expression>).

Generating the Smooks Binding Configuration

The Javabean Cartridge contains the org.milyn.javabean.gen.ConfigGenerator utility class that can be used to generate a binding configuration template. This template can then be used as the basis for defining a binding.

From the commandline:

No Format
$JAVA_HOME/bin/java -classpath <classpath> org.milyn.javabean.gen.ConfigGenerator -c <rootBeanClass> -o <outputFilePath> [-p <propertiesFilePath>]
  • The "-c" commandline arg specifies the root class of the model whose binding config is to be generated.
  • The "-o" commandline arg specifies the path and filename for the generated config output.
  • The "-p" commandline arg specifies the path and filename optional binding configuration file that specifies aditional binding parameters.


The optional "-p" properties file parameter allows specification of additional config parameters:

  • packages.included: Semi-colon seperated list of packages scoping classes to be included in the binding generation.
  • packages.excluded: Semi-colon seperated list of packages scoping classes to be excluded in the binding generation.


After running this utility against the target class, you typically need to perform the following follow-up tasks in order to make the binding configuration work for your Source data model.

  1. For each <jb:bindings> element, set the createOnElement attribute to the event element that should be used to create the bean instance.
  2. Update the <jb:value data> attributes to select the event element/attribute supplying the binding data for that bean property.
  3. Check the <jb:value decoder> attributes. Not all will be set, depending on the actual property type. These must be configured by hand e.g. you may need to configure <jb:decodeParam> sub-elements for the decoder on some of the bindings. E.g. for a date field.
  4. Double-check the binding config elements (<jb:value> and <jb:wiring>), making sure all Java properties have been covered in the generated configuration.


Determining the selector values can sometimes be difficult, especially for non XML Sources (Java etc). The Html Reporting tool can be a great help here because it helps you visualise the input message model (against which the selectors will be applied) as seen by Smooks. So, first off, generate a report using your Source data, but with an empty transformation configuration. In the report, you can see the model against which you need to add your configurations. Add the configurations one at a time, rerunning the report to check they are being applied.

The following is an example of a generated configuration. Note the "$TODO$" tokens.

No Format
<?xml version="1.0"?>
<smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd" xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd">

    <jb:bindings beanId="order" class="org.milyn.javabean.Order" createOnElement="$TODO$">
        <jb:wiring property="header" beanIdRef="header" />
        <jb:wiring property="orderItems" beanIdRef="orderItems" />
        <jb:wiring property="orderItemsArray" beanIdRef="orderItemsArray" />
    </jb:bindings>

    <jb:bindings beanId="header" class="org.milyn.javabean.Header" createOnElement="$TODO$">
        <jb:value property="date" decoder="$TODO$" data="$TODO$" />
        <jb:value property="customerNumber" decoder="Long" data="$TODO$" />
        <jb:value property="customerName" decoder="String" data="$TODO$" />
        <jb:value property="privatePerson" decoder="Boolean" data="$TODO$" />
        <jb:wiring property="order" beanIdRef="order" />
    </jb:bindings>

    <jb:bindings beanId="orderItems" class="java.util.ArrayList" createOnElement="$TODO$">
        <jb:wiring beanIdRef="orderItems_entry" />
    </jb:bindings>

    <jb:bindings beanId="orderItems_entry" class="org.milyn.javabean.OrderItem" createOnElement="$TODO$">
        <jb:value property="productId" decoder="Long" data="$TODO$" />
        <jb:value property="quantity" decoder="Integer" data="$TODO$" />
        <jb:value property="price" decoder="Double" data="$TODO$" />
        <jb:wiring property="order" beanIdRef="order" />
    </jb:bindings>

    <jb:bindings beanId="orderItemsArray" class="org.milyn.javabean.OrderItem[]" createOnElement="$TODO$">
        <jb:wiring beanIdRef="orderItemsArray_entry" />
    </jb:bindings>

    <jb:bindings beanId="orderItemsArray_entry" class="org.milyn.javabean.OrderItem" createOnElement="$TODO$">
        <jb:value property="productId" decoder="Long" data="$TODO$" />
        <jb:value property="quantity" decoder="Integer" data="$TODO$" />
        <jb:value property="price" decoder="Double" data="$TODO$" />
        <jb:wiring property="order" beanIdRef="order" />
    </jb:bindings>

</smooks-resource-list>