<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
>

<channel>
	<title>Smooks Data Integration &#187; Java Binding</title>
	<atom:link href="http://blog.smooks.org/category/java-binding/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smooks.org</link>
	<description>The official blog</description>
	<lastBuildDate>Mon, 28 Jun 2010 13:10:25 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<!-- podcast_generator="Blubrry PowerPress/1.0.7" mode="simple" entry="normal" -->
	<itunes:summary>The official blog</itunes:summary>
	<itunes:author>Smooks Data Integration</itunes:author>
	<itunes:explicit>no</itunes:explicit>
	<itunes:image href="http://blog.smooks.org/wp-content/plugins/powerpress/itunes_default.jpg" />
	<itunes:owner>
		<itunes:name>Smooks Data Integration</itunes:name>
		<itunes:email>tom.fennelly@gmail.com</itunes:email>
	</itunes:owner>
	<managingEditor>tom.fennelly@gmail.com (Smooks Data Integration)</managingEditor>
	<itunes:subtitle>The official blog</itunes:subtitle>
	<image>
		<title>Smooks Data Integration &#187; Java Binding</title>
		<url>http://blog.smooks.org/wp-content/plugins/powerpress/rss_default.jpg</url>
		<link>http://blog.smooks.org/category/java-binding/</link>
	</image>
		<item>
		<title>Introduction: Using a factory to instantiate beans with the javabean cartridge</title>
		<link>http://blog.smooks.org/2009/10/12/introduction-using-a-factory-to-instantiate-beans-with-the-javabean-cartridge/</link>
		<comments>http://blog.smooks.org/2009/10/12/introduction-using-a-factory-to-instantiate-beans-with-the-javabean-cartridge/#comments</comments>
		<pubDate>Mon, 12 Oct 2009 08:01:59 +0000</pubDate>
		<dc:creator>Maurice</dc:creator>
				<category><![CDATA[Java Binding]]></category>
		<category><![CDATA[Smooks]]></category>
		<category><![CDATA[Technical Info & Concepts]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=354</guid>
		<description><![CDATA[<p>I would like to introduce the new factory feature in the Javabean cartridge of the up coming Smooks 1.3 release. This new features makes it possible to use a static factory method or a factory object to instantiate objects with the Javabean cartridge.</p>
<p><span id="more-354"></span></p>
<p>Before this new feature you could only instantiate new beans by providing the class name of the bean and the bean would then be created using it&#8217;s public parameterless constructor. So it was mandatory to have a parameterless constructor on the Javabean. Here is an example:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.ArrayList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>But now it is possible to use a factory to instantiate the bean. So you don&#8217;t need a public parameterless constructur anymore. You even don&#8217;t have to define the actual class name any more. Any of the interfaces that the class implements suffices. However only the methods of that interface are available for binding then. Here is an example where we instantiate an ArrayList object using a static factory method:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.List&quot;
   factory=&quot;some.package.ListFactory#newList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>With the factory attribute you set the factory definition. The class attributes defines that a List object is returned. What kind of List object (ArrayList, LinkedList) is up to the ListFactory to decide. Here is another example:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.List&quot;
   factory=&quot;some.package.ListFactory#getInstance.newList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>Here we define that an instance of the ListFactory needs to be retrieved using the static method getInstance() and that then the newList() method needs to be called on the ListFactory object to create the List object. This construct makes it possible to easily call Singleton Factories.</p>
<p>The default factory definition language looks like this: <strong>factory.class#static_method<em>{.instance_method}</em></strong></p>
<p>It is also possible to use MVEL as the factory definition language. MVEL has some advantages over the basic default definition language, for example you can use objects from the bean context as the factory object or  you can call factory methods with parameters. These parameters can be defined within the definition or they can be objects from the bean context. To be able to use MVEL you must set the &#8216;factory.definition.parser.class&#8217; global parameter to &#8216;org.milyn.javabean.factory.MVELFactoryDefinitionParser&#8217;.</p>
<p>Here is an example using MVEL:</p>
<pre class="brush: xml;">
&lt;smooks-resource-list
   xmlns=&quot;http://www.milyn.org/xsd/smooks-1.1.xsd&quot;
   xmlns:jb=&quot;http://www.milyn.org/xsd/smooks/javabean-1.3.xsd&quot;&gt;

	&lt;params&gt;
		&lt;param name=&quot;factory.definition.parser.class&quot;&gt;
			org.milyn.javabean.factory.MVELFactoryDefinitionParser
		&lt;/param&gt;
	&lt;/params&gt;

    &lt;jb:bean
		beanId=&quot;orders&quot;
		class=&quot;java.util.List&quot;
		factory=&quot;some.package.ListFactory.getInstance().newList()&quot;
		createOnElement=&quot;orders&quot;
	&gt;
		&lt;!-- ... bindings --&gt;
    &lt;/jb:bean&gt;

&lt;/smooks-resource-list&gt;
</pre>
<p>Maybe you wonder why we don&#8217;t use MVEL as the default factory definition language? Currently the performance of the basic definition language and MVEL is about equal. The reason that the basic definition language isn&#8217;t faster is because it currently uses reflection to call the factory methods. However there are plans to use byte code generation instead of reflection. This should improve the performance dramatically. If MVEL where the default language then we couldn&#8217;t do anything to improve the performance for those people who don&#8217;t need any thing more then the basic features that the basic definition language offers.</p>
<p>If you have any questions or remarks then I would gladly hear them.</p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Maurice <a href="http://blog.smooks.org/2009/10/12/introduction-using-a-factory-to-instantiate-beans-with-the-javabean-cartridge/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>I would like to introduce the new factory feature in the Javabean cartridge of the up coming Smooks 1.3 release. This new features makes it possible to use a static factory method or a factory object to instantiate objects with the Javabean cartridge.</p>
<p><span id="more-354"></span></p>
<p>Before this new feature you could only instantiate new beans by providing the class name of the bean and the bean would then be created using it&#8217;s public parameterless constructor. So it was mandatory to have a parameterless constructor on the Javabean. Here is an example:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.ArrayList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>But now it is possible to use a factory to instantiate the bean. So you don&#8217;t need a public parameterless constructur anymore. You even don&#8217;t have to define the actual class name any more. Any of the interfaces that the class implements suffices. However only the methods of that interface are available for binding then. Here is an example where we instantiate an ArrayList object using a static factory method:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.List&quot;
   factory=&quot;some.package.ListFactory#newList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>With the factory attribute you set the factory definition. The class attributes defines that a List object is returned. What kind of List object (ArrayList, LinkedList) is up to the ListFactory to decide. Here is another example:</p>
<pre class="brush: xml;">
&lt;jb:bean
   beanId=&quot;orders&quot;
   class=&quot;java.util.List&quot;
   factory=&quot;some.package.ListFactory#getInstance.newList&quot;
   createOnElement=&quot;orders&quot;
&gt;
     &lt;!-- ... bindings --&gt;
&lt;/jb:bean&gt;
</pre>
<p>Here we define that an instance of the ListFactory needs to be retrieved using the static method getInstance() and that then the newList() method needs to be called on the ListFactory object to create the List object. This construct makes it possible to easily call Singleton Factories.</p>
<p>The default factory definition language looks like this: <strong>factory.class#static_method<em>{.instance_method}</em></strong></p>
<p>It is also possible to use MVEL as the factory definition language. MVEL has some advantages over the basic default definition language, for example you can use objects from the bean context as the factory object or  you can call factory methods with parameters. These parameters can be defined within the definition or they can be objects from the bean context. To be able to use MVEL you must set the &#8216;factory.definition.parser.class&#8217; global parameter to &#8216;org.milyn.javabean.factory.MVELFactoryDefinitionParser&#8217;.</p>
<p>Here is an example using MVEL:</p>
<pre class="brush: xml;">
&lt;smooks-resource-list
   xmlns=&quot;http://www.milyn.org/xsd/smooks-1.1.xsd&quot;
   xmlns:jb=&quot;http://www.milyn.org/xsd/smooks/javabean-1.3.xsd&quot;&gt;

	&lt;params&gt;
		&lt;param name=&quot;factory.definition.parser.class&quot;&gt;
			org.milyn.javabean.factory.MVELFactoryDefinitionParser
		&lt;/param&gt;
	&lt;/params&gt;

    &lt;jb:bean
		beanId=&quot;orders&quot;
		class=&quot;java.util.List&quot;
		factory=&quot;some.package.ListFactory.getInstance().newList()&quot;
		createOnElement=&quot;orders&quot;
	&gt;
		&lt;!-- ... bindings --&gt;
    &lt;/jb:bean&gt;

&lt;/smooks-resource-list&gt;
</pre>
<p>Maybe you wonder why we don&#8217;t use MVEL as the default factory definition language? Currently the performance of the basic definition language and MVEL is about equal. The reason that the basic definition language isn&#8217;t faster is because it currently uses reflection to call the factory methods. However there are plans to use byte code generation instead of reflection. This should improve the performance dramatically. If MVEL where the default language then we couldn&#8217;t do anything to improve the performance for those people who don&#8217;t need any thing more then the basic features that the basic definition language offers.</p>
<p>If you have any questions or remarks then I would gladly hear them.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/10/12/introduction-using-a-factory-to-instantiate-beans-with-the-javabean-cartridge/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Smooks Persistence part 2: How to use Hibernate/JPA</title>
		<link>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/</link>
		<comments>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 11:20:09 +0000</pubDate>
		<dc:creator>Maurice</dc:creator>
				<category><![CDATA[Java Binding]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Scribe]]></category>
		<category><![CDATA[Smooks]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=113</guid>
		<description><![CDATA[<p>With the new Smooks Persistence cartridge in Smooks 1.2 you can directly use several entity persistence frameworks from within Smooks. In this post I will show you how this works with Hibernate and any other JPA compatible framework.</p>
<p><span id="more-113"></span></p>
<p>This post is part of a multi post article. You can find the previous post here: <a title="Smooks Persistence part 1: The Introduction" href="/2009/02/26/smooks-persistence-part-1-the-introduction/">Smooks Persistence part 1: The Introduction</a></p>
<p>In this post we will look at an example of how to persist Hibernate Entities. This example is based on the example of the previous post.</p>
<p>First, lets take a look at the data we are going to process. In this example we are processing XML data.  It should be noted however, that the input data could also be <strong>CSV</strong>, <strong>JSON</strong>, <strong>EDI</strong>, <strong>Java</strong> or any other structured/hierarchical data format.  The same principals apply, no matter what the data format is!</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>These are the Hibernate entities we are going to use:</p>
<pre class="brush: java;">@Entity
@Table(name="orders")
public class Order {

	@Id
	private Integer ordernumber;

	@Basic
	private String customerId;

	@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
	private List orderItems = new ArrayList();

	public void addOrderLine(OrderLine orderLine) {
		orderItems.add(orderLine);
	}

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name="orderlines")
public class OrderLine {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;

	@ManyToOne
	@JoinColumn(name="orderid")
	private Order order;

	@Basic
	private Integer quantity;

	@ManyToOne
	@JoinColumn(name="productid")
	private Product product;

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name = "products")
@NamedQuery(name="product.byId", query="from Product p where p.id = :id")
public class Product {

	@Id
	private Integer id;

	@Basic
	private String name;

       // Getters and Setters....
}</pre>
<p>The Smooks configuration looks like this:</p>
<pre class="brush: xml;">
&lt;!--
	In this example, we don't need to reference the Hibernate Session
	anywhere in the configuration. Later on, in the Smooks execution
	code (following snippet), you will see that we have set the
	Session as the default Session. This means that you don't need
	to reference it by name.  In the configuration of the previous
	post, we needed to reference every DAO by its name.
--&gt;
&lt;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" xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

	&lt;!--
		This is a normal Javabean binding. It creates the order bean and binds
		data into it.
	--&gt;
	&lt;jb:bindings beanId="order" class="example.entity.Order"
		createOnElement="order"&gt;

		&lt;jb:value property="ordernumber" data="ordernumber" /&gt;
		&lt;jb:value property="customerId" data="customer" /&gt;
		&lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This is a normal Javabean binding. Notice that we have a wiring on
		'product'. The Product entity will not be created, but looked up by a
		locator.
	--&gt;
	&lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
		createOnElement="order-item"&gt;

		&lt;jb:value property="quantity" data="quantity" decoder="Integer" /&gt;
		&lt;jb:wiring property="order" beanIdRef="order" /&gt;
		&lt;jb:wiring property="product" beanIdRef="product" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This locator calls (via Scribe) the SessionDaoAdapter#lookupByQuery()
		method. The result will be added to the bean repository under the bean
		id 'product'. An exception is thrown when no result is found.
	--&gt;
	&lt;dao:locator beanId="product" lookupOnElement="order-item"
		onNoResult="EXCEPTION" uniqueResult="true"&gt;

		&lt;dao:query&gt;from Product p where p.id = :id&lt;/dao:query&gt;
		&lt;dao:params&gt;
			&lt;dao:value name="id" data="product" decoder="Integer" /&gt;
		&lt;/dao:params&gt;
	&lt;/dao:locator&gt;

	&lt;!--
		The inserter calls (via Scribe) the SessionDaoAdapter#insert() method
		at the visitAfter of the Order element. The SessioDaoAdapter#insert()
		uses the Hibernate Session#save() method to persist the entity to the
		database.
	--&gt;
	&lt;dao:inserter beanId="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>If we want to use the named query &#8216;productById&#8217; instead of the query string then the DAO locator configuration will look like this:</p>
<pre class="brush: xml;">	&lt;!--
		The lookup parameter is the query name
	--&gt;
    &lt;dao:locator beanId="product" lookupOnElement="order-item" lookup="product.byId"
    				onNoResult="EXCEPTION" uniqueResult="true"&gt;
    	&lt;dao:params&gt;
    		&lt;dao:value name="id" data="product" decoder="Integer"/&gt;
    	&lt;/dao:params&gt;
    &lt;/dao:locator&gt;</pre>
<p>The following code executes Smooks. Note that we use a SessionRegister object so that we can access the Hibernate Session from within Smooks.</p>
<pre class="brush: java;">
        // Note: In a real world application you should cache the Smooks instance
        // else you will have enormous performance penalties.
        Smooks smooks = new Smooks("smooks-config.xml");

        ExecutionContext executionContext = smooks.createExecutionContext();

        // The SessionRegister provides the bridge between Hibernate and the
        // Persistence Cartridge. We provide it with the Hibernate session.
        // The Hibernate Session is set as default Session.
        DaoRegister register = new SessionRegister(session);

        // This sets the DAO Register in the executionContext for Smooks
        // to access it.
        PersistenceUtil.setDAORegister(executionContext, register);

        Transaction transaction = session.beginTransaction();

        Source source = new StreamSource(new File("order.xml"));        

        smooks.filter(source, null, executionContext);

        transaction.commit();</pre>
<p>If you want to take a JPA version of this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you’ll find it in the “dao-router” folder.  It also shows you how to use custom DOA&#8217;s with the Persistence Cartridge.</p>
<p>With Scribe and the Persistence Cartridge it is very easy to use Hibernate, JPA and most other persistence frameworks within Smooks. Later on in this series I will explain how too write your own DAO Adapters, so that you can add support for other persistence frameworks.</p>
<p>In the next post of the series I will explain how you can use Ibatis with the Persistence Cartridge.</p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Maurice <a href="http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>With the new Smooks Persistence cartridge in Smooks 1.2 you can directly use several entity persistence frameworks from within Smooks. In this post I will show you how this works with Hibernate and any other JPA compatible framework.</p>
<p><span id="more-113"></span></p>
<p>This post is part of a multi post article. You can find the previous post here: <a title="Smooks Persistence part 1: The Introduction" href="/2009/02/26/smooks-persistence-part-1-the-introduction/">Smooks Persistence part 1: The Introduction</a></p>
<p>In this post we will look at an example of how to persist Hibernate Entities. This example is based on the example of the previous post.</p>
<p>First, lets take a look at the data we are going to process. In this example we are processing XML data.  It should be noted however, that the input data could also be <strong>CSV</strong>, <strong>JSON</strong>, <strong>EDI</strong>, <strong>Java</strong> or any other structured/hierarchical data format.  The same principals apply, no matter what the data format is!</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>These are the Hibernate entities we are going to use:</p>
<pre class="brush: java;">@Entity
@Table(name="orders")
public class Order {

	@Id
	private Integer ordernumber;

	@Basic
	private String customerId;

	@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
	private List orderItems = new ArrayList();

	public void addOrderLine(OrderLine orderLine) {
		orderItems.add(orderLine);
	}

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name="orderlines")
public class OrderLine {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Integer id;

	@ManyToOne
	@JoinColumn(name="orderid")
	private Order order;

	@Basic
	private Integer quantity;

	@ManyToOne
	@JoinColumn(name="productid")
	private Product product;

       // Getters and Setters....
}</pre>
<pre class="brush: java;">@Entity
@Table(name = "products")
@NamedQuery(name="product.byId", query="from Product p where p.id = :id")
public class Product {

	@Id
	private Integer id;

	@Basic
	private String name;

       // Getters and Setters....
}</pre>
<p>The Smooks configuration looks like this:</p>
<pre class="brush: xml;">
&lt;!--
	In this example, we don't need to reference the Hibernate Session
	anywhere in the configuration. Later on, in the Smooks execution
	code (following snippet), you will see that we have set the
	Session as the default Session. This means that you don't need
	to reference it by name.  In the configuration of the previous
	post, we needed to reference every DAO by its name.
--&gt;
&lt;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" xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

	&lt;!--
		This is a normal Javabean binding. It creates the order bean and binds
		data into it.
	--&gt;
	&lt;jb:bindings beanId="order" class="example.entity.Order"
		createOnElement="order"&gt;

		&lt;jb:value property="ordernumber" data="ordernumber" /&gt;
		&lt;jb:value property="customerId" data="customer" /&gt;
		&lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This is a normal Javabean binding. Notice that we have a wiring on
		'product'. The Product entity will not be created, but looked up by a
		locator.
	--&gt;
	&lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
		createOnElement="order-item"&gt;

		&lt;jb:value property="quantity" data="quantity" decoder="Integer" /&gt;
		&lt;jb:wiring property="order" beanIdRef="order" /&gt;
		&lt;jb:wiring property="product" beanIdRef="product" /&gt;
	&lt;/jb:bindings&gt;

	&lt;!--
		This locator calls (via Scribe) the SessionDaoAdapter#lookupByQuery()
		method. The result will be added to the bean repository under the bean
		id 'product'. An exception is thrown when no result is found.
	--&gt;
	&lt;dao:locator beanId="product" lookupOnElement="order-item"
		onNoResult="EXCEPTION" uniqueResult="true"&gt;

		&lt;dao:query&gt;from Product p where p.id = :id&lt;/dao:query&gt;
		&lt;dao:params&gt;
			&lt;dao:value name="id" data="product" decoder="Integer" /&gt;
		&lt;/dao:params&gt;
	&lt;/dao:locator&gt;

	&lt;!--
		The inserter calls (via Scribe) the SessionDaoAdapter#insert() method
		at the visitAfter of the Order element. The SessioDaoAdapter#insert()
		uses the Hibernate Session#save() method to persist the entity to the
		database.
	--&gt;
	&lt;dao:inserter beanId="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>If we want to use the named query &#8216;productById&#8217; instead of the query string then the DAO locator configuration will look like this:</p>
<pre class="brush: xml;">	&lt;!--
		The lookup parameter is the query name
	--&gt;
    &lt;dao:locator beanId="product" lookupOnElement="order-item" lookup="product.byId"
    				onNoResult="EXCEPTION" uniqueResult="true"&gt;
    	&lt;dao:params&gt;
    		&lt;dao:value name="id" data="product" decoder="Integer"/&gt;
    	&lt;/dao:params&gt;
    &lt;/dao:locator&gt;</pre>
<p>The following code executes Smooks. Note that we use a SessionRegister object so that we can access the Hibernate Session from within Smooks.</p>
<pre class="brush: java;">
        // Note: In a real world application you should cache the Smooks instance
        // else you will have enormous performance penalties.
        Smooks smooks = new Smooks("smooks-config.xml");

        ExecutionContext executionContext = smooks.createExecutionContext();

        // The SessionRegister provides the bridge between Hibernate and the
        // Persistence Cartridge. We provide it with the Hibernate session.
        // The Hibernate Session is set as default Session.
        DaoRegister register = new SessionRegister(session);

        // This sets the DAO Register in the executionContext for Smooks
        // to access it.
        PersistenceUtil.setDAORegister(executionContext, register);

        Transaction transaction = session.beginTransaction();

        Source source = new StreamSource(new File("order.xml"));        

        smooks.filter(source, null, executionContext);

        transaction.commit();</pre>
<p>If you want to take a JPA version of this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you’ll find it in the “dao-router” folder.  It also shows you how to use custom DOA&#8217;s with the Persistence Cartridge.</p>
<p>With Scribe and the Persistence Cartridge it is very easy to use Hibernate, JPA and most other persistence frameworks within Smooks. Later on in this series I will explain how too write your own DAO Adapters, so that you can add support for other persistence frameworks.</p>
<p>In the next post of the series I will explain how you can use Ibatis with the Persistence Cartridge.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/03/25/smooks-persistence-part-2-how-to-use-hibernatejpa/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Smooks Persistence part 1: The Introduction</title>
		<link>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/</link>
		<comments>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 11:31:44 +0000</pubDate>
		<dc:creator>Maurice</dc:creator>
				<category><![CDATA[Java Binding]]></category>
		<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Scribe]]></category>
		<category><![CDATA[Smooks]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=61</guid>
		<description><![CDATA[<p>One of the major new features in Smooks v1.2 will be the new Persistence Cartridge. This cartridge enables the use of several entity persistence frameworks from within Smooks, currently targeting Hibernate, Ibatis and any JPA compatible framework. It also allows you to use your own Data Access Objects (DAOs).</p>
<p>This cartridge is great for those cases where you already have your data access layer and want to use its power from within Smooks. It also allows you to reuse these persistence resources on any format of data, not just XML e.g. EDI, CSV, JSON etc.</p>
<p>This is the first post of a series of posts about the persistence cartridge. This post is an introduction of the cartridge.  I will give an overview of what the cartridge can do and also show an example where I use custom DAO&#8217;s to persist the data of an XML document.  In the next posts in this series, I will show examples of how Hibernate, JPA and Ibatis entities can be used.</p>
<p><span id="more-61"></span></p>
<p>The Persistence cartridge is build around a data access layer abstraction library called &#8220;Scribe&#8221;.  Scribe is a new Milyn subproject, born out of the needs of the Persistence cartridge. It enables the Persistence cartridge to use your DAOs without it actually needing to know the details of your DAOs. In fact, they don&#8217;t need to be DAOs at all.  You can also use any entity persistence framework without the Persistence cartridge seeing the difference.  Scribe supports abstracting the default actions you can expect from any DAO or persistence library like inserting, updating, deleting and querying for entities.</p>
<p>For Scribe to understand how to use your DAOs, it needs a mapping. Scribe offers two methods for doing this:</p>
<ul>
<li><strong>Java Annotations</strong><br />
Scribe has a set of Java Annotations like @Insert, @Update, @Delete and @Locate. These annotations enable you to map your DAOs to the DAO actions.</li>
<li><strong>Java Interfaces</strong><br />
Scribe defines a set of Java interfaces like DAO, Locator and Queryable.  You build your DAOs By combining and implementing these interfaces. These interfaces are primarily meant to be used for implementing adapters for persistence frameworks.</li>
</ul>
<p>The Persistence Cartridge defines a set of Smooks Visitor components that use the DAO actions defined by Scribe.  For example, the <strong>Inserter </strong>visitor can insert your entities by calling the method defined by the DAO action mapping.  We see an example of this later.</p>
<p>The cartridge has the following Smooks Visitor components:</p>
<ul>
<li><strong>Inserter<br />
</strong>Inserts/Persists entities</li>
<li><strong>Updater<br />
</strong>Updates/Merges entities</li>
<li><strong>Deleter</strong><br />
Deletes entities</li>
<li><strong>Locator</strong><br />
Locates entities with a query or with your own lookup method.</li>
</ul>
<p>Now that you have an idea of what the Persistence cartridge can do, let&#8217;s take a look at a DAO based example.  We will see Hibernate, IBatis and JPA examples in the followup posts in this series.</p>
<p>The example will read an XML file containing order information (note that this works just the same for EDI, CSV etc).  Using the javabean cartridge, it will bind the XML data into a set of entity beans.  Using the id of the products within the order items (the &lt;product&gt; element) it will locate the product entities and bind them to the order entity bean.  Finally, the order bean will be persisted.</p>
<p>The order XML message looks like this:</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>The following custom DAO will be used to persist the Order entity:</p>
<pre class="brush: java;">@Dao
public class OrderDao {

   private final EntityManager em;

   public OrderDao(EntityManager em) {
     this.em = em;
   }

   @Insert
   public void insertOrder(Order order) {
     em.persist(order);
   }
}</pre>
<p>When looking at this class you should notice the <strong>@Dao</strong> and <strong>@Insert</strong> annotations. The <strong>@Dao</strong> annotation declares that the OrderDao is a DAO object. The <strong>@Insert</strong> annotation declares that the insertOrder method should be used to insert Order entities.</p>
<p>The following custom DAO will be used to lookup the Product entities:</p>
<pre class="brush: java;">@Dao
public class ProductDao {

   private final EntityManager em;

   public ProductDao(EntityManager em) {
      this.em = em;
   }

   @Lookup(name="id")
   public Product findProductById(@Param("id") int id) {
      return em.find(Product.class, id);
   }
}</pre>
<p>When looking at this class, you should notice the <strong>@Lookup</strong> and <strong>@Param</strong> annotation. The <strong>@Lookup</strong> annotation declares that the <strong>ProductDao#findByProductId</strong> method is used to lookup <strong>Product</strong> entities. The<strong> name</strong> parameter in the <strong>@Lookup</strong> annotation sets the lookup name reference for that method. When the name isn&#8217;t declared, the method name will be used. The optional <strong>@Param</strong> annotation let&#8217;s you name the parameters. This creates a better  abstraction between Smooks and the DAO. If you don&#8217;t declare the <strong>@Param</strong> annotation the parameters are resolved by there position.</p>
<p>The Smooks configuration look likes this:</p>
<pre class="brush: xml;">&lt;!--
    In this configuration you will see that we reference to the
    DAO's via the names 'order'  and 'product'. The persistence cartridge uses
    a DAO Register to map the DAO's to there names.
    Later on, in the java code that executes Smooks, you will see how that is done.
--&gt;
&lt;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"
   xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

   &lt;!--
    This is a normal Javabean binding. It creates the order bean
    and binds data into it.
   --&gt;
   &lt;jb:bindings beanId="order" class="example.entity.Order"
                 createOnElement="order"&gt;
      &lt;jb:value property="ordernumber" data="ordernumber"/&gt;
      &lt;jb:value property="customerId" data="customer"/&gt;
      &lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This is a normal Javabean binding. Notice that we have a wiring on
    'product'. The Product entity will not be created, but looked up
    by a locator.
   --&gt;
   &lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
                 createOnElement="order-item"&gt;
      &lt;jb:value property="quantity" data="quantity"/&gt;
      &lt;jb:wiring property="order" beanIdRef="order"/&gt;
      &lt;jb:wiring property="product" beanIdRef="product"/&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This locator calls (via Scribe) the ProductDao#findById() method.
    The result will be added to the bean repository under
    the bean id 'product'.
    An exception is thrown when no result is found.
   --&gt;
   &lt;dao:locator beanId="product" dao="product" lookup="id"
           lookupOnElement="order-item" onNoResult="EXCEPTION"&gt;
      &lt;dao:params&gt;
         &lt;dao:value name="id" data="product" decoder="Integer"/&gt;
      &lt;/dao:params&gt;
   &lt;/dao:locator&gt;

   &lt;!--
    The inserter calls the OrderDao#insertOrder() method at
    end of Order message.
   --&gt;
   &lt;dao:inserter beanId="order" dao="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>The following code executes Smooks:</p>
<pre class="brush: java;">Smooks smooks = new Smooks("./smooks-configs/smooks-dao-config.xml");
ExecutionContext executionContext = smooks.createExecutionContext();

// The register is used to map the DAO's to a DAO name. The DAO name isbe used in
// the configuration.
// The MapRegister is a simple Map like implementation of the DaoRegister.
DaoRegister&lt;object&gt; register =
	MapRegister.builder()
		.put("product", new ProductDao(em))
		.put("order", new OrderDao(em))
		.build();

PersistenceUtil.setDAORegister(executionContext, mapRegister);

// Transaction management from within Smooks isn't supported yet,
// so we need to do it outside the filter execution
EntityTransaction tx = em.getTransaction();
tx.begin();

smooks.filter(new StreamSource(messageIn), null, executionContext);

tx.commit();</pre>
<p>If you want to take this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you&#8217;ll find it in the &#8220;dao-router&#8221; folder.  It also shows you how to use JPA directly, without any DAOs in between.</p>
<p>The cartridge is almost ready for it&#8217;s first release.  There is one thing that I am still not completely sure about and it would be great if people could provide some feedback.  I am not completely happy about the action names: <strong>insert</strong>, <strong>update </strong>and <strong>delete</strong>.  In the world of persistence frameworks, different sets of names are used for these actions.  JPA, for instance, uses <strong>persist</strong>, <strong>merge </strong>and <strong>remove</strong>.  Hibernate (outside of JPA) uses <strong>save, update</strong> and <strong>delete </strong>and Ibatis uses <strong>insert</strong>, <strong>update</strong> and <strong>delete</strong>. Which names would you choose and why?</p>
<p>In the next post of the series I will explain how to use Hibernate directly.</p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Maurice <a href="http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>One of the major new features in Smooks v1.2 will be the new Persistence Cartridge. This cartridge enables the use of several entity persistence frameworks from within Smooks, currently targeting Hibernate, Ibatis and any JPA compatible framework. It also allows you to use your own Data Access Objects (DAOs).</p>
<p>This cartridge is great for those cases where you already have your data access layer and want to use its power from within Smooks. It also allows you to reuse these persistence resources on any format of data, not just XML e.g. EDI, CSV, JSON etc.</p>
<p>This is the first post of a series of posts about the persistence cartridge. This post is an introduction of the cartridge.  I will give an overview of what the cartridge can do and also show an example where I use custom DAO&#8217;s to persist the data of an XML document.  In the next posts in this series, I will show examples of how Hibernate, JPA and Ibatis entities can be used.</p>
<p><span id="more-61"></span></p>
<p>The Persistence cartridge is build around a data access layer abstraction library called &#8220;Scribe&#8221;.  Scribe is a new Milyn subproject, born out of the needs of the Persistence cartridge. It enables the Persistence cartridge to use your DAOs without it actually needing to know the details of your DAOs. In fact, they don&#8217;t need to be DAOs at all.  You can also use any entity persistence framework without the Persistence cartridge seeing the difference.  Scribe supports abstracting the default actions you can expect from any DAO or persistence library like inserting, updating, deleting and querying for entities.</p>
<p>For Scribe to understand how to use your DAOs, it needs a mapping. Scribe offers two methods for doing this:</p>
<ul>
<li><strong>Java Annotations</strong><br />
Scribe has a set of Java Annotations like @Insert, @Update, @Delete and @Locate. These annotations enable you to map your DAOs to the DAO actions.</li>
<li><strong>Java Interfaces</strong><br />
Scribe defines a set of Java interfaces like DAO, Locator and Queryable.  You build your DAOs By combining and implementing these interfaces. These interfaces are primarily meant to be used for implementing adapters for persistence frameworks.</li>
</ul>
<p>The Persistence Cartridge defines a set of Smooks Visitor components that use the DAO actions defined by Scribe.  For example, the <strong>Inserter </strong>visitor can insert your entities by calling the method defined by the DAO action mapping.  We see an example of this later.</p>
<p>The cartridge has the following Smooks Visitor components:</p>
<ul>
<li><strong>Inserter<br />
</strong>Inserts/Persists entities</li>
<li><strong>Updater<br />
</strong>Updates/Merges entities</li>
<li><strong>Deleter</strong><br />
Deletes entities</li>
<li><strong>Locator</strong><br />
Locates entities with a query or with your own lookup method.</li>
</ul>
<p>Now that you have an idea of what the Persistence cartridge can do, let&#8217;s take a look at a DAO based example.  We will see Hibernate, IBatis and JPA examples in the followup posts in this series.</p>
<p>The example will read an XML file containing order information (note that this works just the same for EDI, CSV etc).  Using the javabean cartridge, it will bind the XML data into a set of entity beans.  Using the id of the products within the order items (the &lt;product&gt; element) it will locate the product entities and bind them to the order entity bean.  Finally, the order bean will be persisted.</p>
<p>The order XML message looks like this:</p>
<pre class="brush: xml;">&lt;order&gt;
    &lt;ordernumber&gt;1&lt;/ordernumber&gt;
    &lt;customer&gt;123456&lt;/customer&gt;
    &lt;order-items&gt;
        &lt;order-item&gt;
            &lt;product&gt;11&lt;/product&gt;
            &lt;quantity&gt;2&lt;/quantity&gt;
        &lt;/order-item&gt;
        &lt;order-item&gt;
            &lt;product&gt;22&lt;/product&gt;
            &lt;quantity&gt;7&lt;/quantity&gt;
        &lt;/order-item&gt;
    &lt;/order-items&gt;
&lt;/order&gt;</pre>
<p>The following custom DAO will be used to persist the Order entity:</p>
<pre class="brush: java;">@Dao
public class OrderDao {

   private final EntityManager em;

   public OrderDao(EntityManager em) {
     this.em = em;
   }

   @Insert
   public void insertOrder(Order order) {
     em.persist(order);
   }
}</pre>
<p>When looking at this class you should notice the <strong>@Dao</strong> and <strong>@Insert</strong> annotations. The <strong>@Dao</strong> annotation declares that the OrderDao is a DAO object. The <strong>@Insert</strong> annotation declares that the insertOrder method should be used to insert Order entities.</p>
<p>The following custom DAO will be used to lookup the Product entities:</p>
<pre class="brush: java;">@Dao
public class ProductDao {

   private final EntityManager em;

   public ProductDao(EntityManager em) {
      this.em = em;
   }

   @Lookup(name="id")
   public Product findProductById(@Param("id") int id) {
      return em.find(Product.class, id);
   }
}</pre>
<p>When looking at this class, you should notice the <strong>@Lookup</strong> and <strong>@Param</strong> annotation. The <strong>@Lookup</strong> annotation declares that the <strong>ProductDao#findByProductId</strong> method is used to lookup <strong>Product</strong> entities. The<strong> name</strong> parameter in the <strong>@Lookup</strong> annotation sets the lookup name reference for that method. When the name isn&#8217;t declared, the method name will be used. The optional <strong>@Param</strong> annotation let&#8217;s you name the parameters. This creates a better  abstraction between Smooks and the DAO. If you don&#8217;t declare the <strong>@Param</strong> annotation the parameters are resolved by there position.</p>
<p>The Smooks configuration look likes this:</p>
<pre class="brush: xml;">&lt;!--
    In this configuration you will see that we reference to the
    DAO's via the names 'order'  and 'product'. The persistence cartridge uses
    a DAO Register to map the DAO's to there names.
    Later on, in the java code that executes Smooks, you will see how that is done.
--&gt;
&lt;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"
   xmlns:dao="http://www.milyn.org/xsd/smooks/persistence-1.2.xsd"&gt;

   &lt;!--
    This is a normal Javabean binding. It creates the order bean
    and binds data into it.
   --&gt;
   &lt;jb:bindings beanId="order" class="example.entity.Order"
                 createOnElement="order"&gt;
      &lt;jb:value property="ordernumber" data="ordernumber"/&gt;
      &lt;jb:value property="customerId" data="customer"/&gt;
      &lt;jb:wiring setterMethod="addOrderLine" beanIdRef="orderLine" /&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This is a normal Javabean binding. Notice that we have a wiring on
    'product'. The Product entity will not be created, but looked up
    by a locator.
   --&gt;
   &lt;jb:bindings beanId="orderLine" class="example.entity.OrderLine"
                 createOnElement="order-item"&gt;
      &lt;jb:value property="quantity" data="quantity"/&gt;
      &lt;jb:wiring property="order" beanIdRef="order"/&gt;
      &lt;jb:wiring property="product" beanIdRef="product"/&gt;
   &lt;/jb:bindings&gt;

   &lt;!--
    This locator calls (via Scribe) the ProductDao#findById() method.
    The result will be added to the bean repository under
    the bean id 'product'.
    An exception is thrown when no result is found.
   --&gt;
   &lt;dao:locator beanId="product" dao="product" lookup="id"
           lookupOnElement="order-item" onNoResult="EXCEPTION"&gt;
      &lt;dao:params&gt;
         &lt;dao:value name="id" data="product" decoder="Integer"/&gt;
      &lt;/dao:params&gt;
   &lt;/dao:locator&gt;

   &lt;!--
    The inserter calls the OrderDao#insertOrder() method at
    end of Order message.
   --&gt;
   &lt;dao:inserter beanId="order" dao="order" insertOnElement="order" /&gt;

&lt;/smooks-resource-list&gt;</pre>
<p>The following code executes Smooks:</p>
<pre class="brush: java;">Smooks smooks = new Smooks("./smooks-configs/smooks-dao-config.xml");
ExecutionContext executionContext = smooks.createExecutionContext();

// The register is used to map the DAO's to a DAO name. The DAO name isbe used in
// the configuration.
// The MapRegister is a simple Map like implementation of the DaoRegister.
DaoRegister&lt;object&gt; register =
	MapRegister.builder()
		.put("product", new ProductDao(em))
		.put("order", new OrderDao(em))
		.build();

PersistenceUtil.setDAORegister(executionContext, mapRegister);

// Transaction management from within Smooks isn't supported yet,
// so we need to do it outside the filter execution
EntityTransaction tx = em.getTransaction();
tx.begin();

smooks.filter(new StreamSource(messageIn), null, executionContext);

tx.commit();</pre>
<p>If you want to take this example for a spin, simply check out the examples from subversion (http://svn.codehaus.org/milyn/trunk/smooks-examples/) and you&#8217;ll find it in the &#8220;dao-router&#8221; folder.  It also shows you how to use JPA directly, without any DAOs in between.</p>
<p>The cartridge is almost ready for it&#8217;s first release.  There is one thing that I am still not completely sure about and it would be great if people could provide some feedback.  I am not completely happy about the action names: <strong>insert</strong>, <strong>update </strong>and <strong>delete</strong>.  In the world of persistence frameworks, different sets of names are used for these actions.  JPA, for instance, uses <strong>persist</strong>, <strong>merge </strong>and <strong>remove</strong>.  Hibernate (outside of JPA) uses <strong>save, update</strong> and <strong>delete </strong>and Ibatis uses <strong>insert</strong>, <strong>update</strong> and <strong>delete</strong>. Which names would you choose and why?</p>
<p>In the next post of the series I will explain how to use Hibernate directly.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/02/26/smooks-persistence-part-1-the-introduction/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Java to XML, without a template??</title>
		<link>http://blog.smooks.org/2009/01/28/java-to-xml-without-a-template/</link>
		<comments>http://blog.smooks.org/2009/01/28/java-to-xml-without-a-template/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 17:13:00 +0000</pubDate>
		<dc:creator>Tom Fennelly</dc:creator>
				<category><![CDATA[Java Binding]]></category>

		<guid isPermaLink="false">http://blog.smooks.org/?p=16</guid>
		<description><![CDATA[<p>Some people use Smooks as a Java Binding framework for marshalling and unmarshalling XML, in a similar fashion to how JAXB can be used.  An &#8220;issue&#8221; that has been raised by a number of people is the fact that, with Smooks, you need to define a template for serializing the populated Java Object model (to XML, or other format).  Some people find this a bit of a drag.  They expect Smooks to be able to do it automagically.  JAXB etc support it, so why can&#8217;t Smooks?</p>
<p><span id="more-16"></span>So first off&#8230; why do I think this is not easy with Smooks?  The main issue I see is that in order for Smooks to be able perform out-of-the-box unmarshalling and marshalling, without having to use a template to serialize back to XML (or whatever), it would really need to know the schema for the input/output message and how it maps to/from the associated Java object model.</p>
<p>As I see it, one of the advantages of Smooks from a pure Java Binding perspective is the ability to bind data from an input message without requiring knowledge of the full structure of the message being processed.  Smooks is fragment based, so the binding configs can be targeted at message fragments and as long as the selector is specific enough to select the bind data, you&#8217;re OK.</p>
<p>So, without knowing the full message structure (schema) and how exactly that schema maps to/from the java object model, it&#8217;s not really possible (in a practical sense) to take the populated object model and serialize it back out to an XML structure that conforms to the same schema as the input message.</p>
<p>Possible solutions:</p>
<ol>
<li>If all you&#8217;re doing is marshalling and unmarshalling a message for which you have the schema (i.e. you&#8217;re not transforming it), well then you could just use JAXB, XStream etc.  Smooks might not be what you want!</li>
<li>One suggestion that has been made was to use the binding selectors to &#8220;infer&#8221; the message structure and from that, build a template that can be used to serialize.  This might work in a few use cases, but it really is a hack and would be broken more often than not.  Our hearts would also be broken answering questions on &#8220;why it doesn&#8217;t work&#8221; in lots of situations.</li>
<li>To Smooks, add support for serialization via some of these other binding frameworks (JAXB etc).  We already have some JIRAs for this.  I don&#8217;t think it would be a lot of work!</li>
</ol>
<p>Personally, I prefer option #3 because it&#8217;s going to produce the most dependable result.  So, taking an example where you need to transform an EDI message to XML, you could do the following:</p>
<ol>
<li>Get/create the mapping model for the EDI message.</li>
<li>Get an XSD for the target XML and from it, generate a JAXB model.</li>
<li>Create the binding configs that bind the data from the EDI message into the JAXB model.</li>
<li>In the same binding config (#3 above), configure a new JAXBSerializer visitor to fire at the end of the message ($document visitAfter), outputting the result of the JAXB model Serialization as the result.</li>
</ol>
<p>So in that example, you&#8217;re using Smooks to bind the data from the EDI data stream into the XML Structure (JAXB model), and then using JAXB to serialize it in conformance to the XML&#8217;s schema.</p>
<p>Alternatively, you could just do what I&#8217;d do and write a template to generate the required output.  Seems like a more direct route to me <img src='http://blog.smooks.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div style="display:block"><small><em>posted in <a href="http://blog.smooks.org/category/java-binding/">Java Binding</a> by Tom Fennelly <a href="http://blog.smooks.org/2009/01/28/java-to-xml-without-a-template/#comments">Leave A Comment</a></em></small></div>]]></description>
			<content:encoded><![CDATA[<p>Some people use Smooks as a Java Binding framework for marshalling and unmarshalling XML, in a similar fashion to how JAXB can be used.  An &#8220;issue&#8221; that has been raised by a number of people is the fact that, with Smooks, you need to define a template for serializing the populated Java Object model (to XML, or other format).  Some people find this a bit of a drag.  They expect Smooks to be able to do it automagically.  JAXB etc support it, so why can&#8217;t Smooks?</p>
<p><span id="more-16"></span>So first off&#8230; why do I think this is not easy with Smooks?  The main issue I see is that in order for Smooks to be able perform out-of-the-box unmarshalling and marshalling, without having to use a template to serialize back to XML (or whatever), it would really need to know the schema for the input/output message and how it maps to/from the associated Java object model.</p>
<p>As I see it, one of the advantages of Smooks from a pure Java Binding perspective is the ability to bind data from an input message without requiring knowledge of the full structure of the message being processed.  Smooks is fragment based, so the binding configs can be targeted at message fragments and as long as the selector is specific enough to select the bind data, you&#8217;re OK.</p>
<p>So, without knowing the full message structure (schema) and how exactly that schema maps to/from the java object model, it&#8217;s not really possible (in a practical sense) to take the populated object model and serialize it back out to an XML structure that conforms to the same schema as the input message.</p>
<p>Possible solutions:</p>
<ol>
<li>If all you&#8217;re doing is marshalling and unmarshalling a message for which you have the schema (i.e. you&#8217;re not transforming it), well then you could just use JAXB, XStream etc.  Smooks might not be what you want!</li>
<li>One suggestion that has been made was to use the binding selectors to &#8220;infer&#8221; the message structure and from that, build a template that can be used to serialize.  This might work in a few use cases, but it really is a hack and would be broken more often than not.  Our hearts would also be broken answering questions on &#8220;why it doesn&#8217;t work&#8221; in lots of situations.</li>
<li>To Smooks, add support for serialization via some of these other binding frameworks (JAXB etc).  We already have some JIRAs for this.  I don&#8217;t think it would be a lot of work!</li>
</ol>
<p>Personally, I prefer option #3 because it&#8217;s going to produce the most dependable result.  So, taking an example where you need to transform an EDI message to XML, you could do the following:</p>
<ol>
<li>Get/create the mapping model for the EDI message.</li>
<li>Get an XSD for the target XML and from it, generate a JAXB model.</li>
<li>Create the binding configs that bind the data from the EDI message into the JAXB model.</li>
<li>In the same binding config (#3 above), configure a new JAXBSerializer visitor to fire at the end of the message ($document visitAfter), outputting the result of the JAXB model Serialization as the result.</li>
</ol>
<p>So in that example, you&#8217;re using Smooks to bind the data from the EDI data stream into the XML Structure (JAXB model), and then using JAXB to serialize it in conformance to the XML&#8217;s schema.</p>
<p>Alternatively, you could just do what I&#8217;d do and write a template to generate the required output.  Seems like a more direct route to me <img src='http://blog.smooks.org/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smooks.org/2009/01/28/java-to-xml-without-a-template/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
