<?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/"
	>

<channel>
	<title>Baptiste Autin</title>
	<atom:link href="http://www.baptisteautin.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.baptisteautin.com</link>
	<description>Software engineer</description>
	<lastBuildDate>Wed, 23 May 2012 14:33:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Spring Batch: persisting data in the Step Execution Context</title>
		<link>http://www.baptisteautin.com/2012/04/03/spring-batch-persisting-data-step-execution-context/lang/en/</link>
		<comments>http://www.baptisteautin.com/2012/04/03/spring-batch-persisting-data-step-execution-context/lang/en/#comments</comments>
		<pubDate>Tue, 03 Apr 2012 14:31:12 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[Formation]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=256&#038;lang=fr</guid>
		<description><![CDATA[In the method execute() of a Tasklet, if you want to store data in the ExecutionContext of the current Step, be careful. Don&#8217;t write: chunkContext.getStepContext().getStepExecutionContext().put("myKey", "myValue"); Instead write: chunkContext.getStepContext().getStepExecution().getExecutionContext().put("mode", "test"); Indeed, getStepExecutionContext() returns a unmodifiable collection. So you are good for a java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1285) if you try to modify what it returns. Note: if [...]]]></description>
			<content:encoded><![CDATA[<p>In the method <code>execute()</code> of a <code>Tasklet</code>, if you want to store data in the <code>ExecutionContext</code> of the current <code>Step</code>, be careful.<br />
Don&#8217;t write:</p>
<pre class="brush:java">chunkContext.getStepContext().getStepExecutionContext().put("myKey", "myValue");</pre>
<p>Instead write:</p>
<pre class="brush:java">chunkContext.getStepContext().getStepExecution().getExecutionContext().put("mode", "test");</pre>
<p>Indeed, <code>getStepExecutionContext()</code> returns a unmodifiable collection. So you are good for a <code>java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1285)</code><br />
if you try to modify what it returns.</p>
<p><br/><br />
Note: if you use an <code>ItemWriter</code> instead of a <code>Tasklet</code>, you can&#8217;t go wrong, as you have to explicitly add a listener with a <code>@BeforeStep</code>:</p>
<pre class="brush:java">private StepExecution stepExecution;

@BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
    this.stepExecution = stepExecution;
}

(...)

this.stepExecution.getExecutionContext().put("someKey", "myValue");
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2012/04/03/spring-batch-persisting-data-step-execution-context/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mixing inheritance strategies in Hibernate</title>
		<link>http://www.baptisteautin.com/2011/09/27/strategies-heritage-hibernate/lang/en/</link>
		<comments>http://www.baptisteautin.com/2011/09/27/strategies-heritage-hibernate/lang/en/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 18:04:19 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[Formation]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=217&#038;lang=fr</guid>
		<description><![CDATA[Inheritance does not exist in the entity-relationship model as such. In a relational database, one can represent inheritance relationship: Either with two tables and an intermediary association (joined strategy in JPA) Either with a single table in which the two entities have merged, along with an additional column to discriminate the name of the entity [...]]]></description>
			<content:encoded><![CDATA[<p>Inheritance does not exist in the entity-relationship model as such.<br />
In a relational database, one can represent inheritance relationship:</p>
<ul>
<li>Either with two tables and an intermediary association (<em>joined strategy</em> in JPA)</li>
<li>Either with a single table in which the two entities have merged, along with an additional column to discriminate the name of the entity (<em>single_table strategy</em>)</li>
</ul>
<p>A variant of the latter strategy also exists (<em>table per class</em>), but I ignore it for simplicity (it consists in defining one table per concrete class, gathering the attributes of the concrete class as well as those of all the superclasses).</p>
<p>Both of these strategies has advantages and disadvantages in terms of performance, ease of use, scalability, compliance / non-compliance with normal forms&#8230;</p>
<p>Hibernate supports both techniques, and can even mix them.<br />
It is that mixing inheritance strategy that I am going to talk to you now.</p>
<p><strong>Use case</strong></p>
<p>I have taken my inspiration from <a href="http://julesberman.blogspot.com/2007_10_01_archive.html">this article</a>, a bioinformatics paper that proposes an ontology of clinical terms associated with neoplasms.<br />
I will not dwell on ontologies, nor on tumors ; I am just taking the classification scheme provided by the author as an example.</p>
<p>From this scheme, I have extracted the following class diagram:</p>
<p><a href="http://www.baptisteautin.com/wp-content/uploads/class_diagram_neoplasm.png"><img src="http://www.baptisteautin.com/wp-content/uploads/class_diagram_neoplasm.png" alt="" title="Class diagram of neoplasm classification" width="744" height="417" class="aligncenter size-full wp-image-227" /></a></p>
<p>Let&#8217;s assume now that these classes have some attributes and methods (not listed).</p>
<p>Let&#8217;s also assume that the top class (<code>Neoplasm</code>) and the middle classes (<code>NeuralCrest</code>, <code>GermCell</code>, <code>Mesoderm</code>, <code>Trophectoderm</code>, <code>Neuroectoderm</code> and <code>EndodermEctoderm</code>) are abstract.<br />
And the other ones are concrete.</p>
<p>Now imagine that we want to persist instances of concrete classes in a relational database.<br />
How are we going to proceed?<br />
And first, how are we going to map this object model to a physical database model?</p>
<p>To start, it is likely that some of these classes will share common attributes (a latin name, a family, a biological category, a set of associated vocabularies, etc.)<br />
Contrarily, the bottom-level classes will probably have specific very attributes.<br />
For instance:</p>
<p><a href="http://www.baptisteautin.com/wp-content/uploads/neural-crest-class-diagram.png"><img src="http://www.baptisteautin.com/wp-content/uploads/neural-crest-class-diagram.png" alt="" title="Neural crest class diagram" width="559" height="286" class="aligncenter size-full wp-image-228" /></a></p>
<p>Creating one big <strong>single table</strong> &#8220;neoplasm&#8221; including all attributes of all classes, along with an additional field to discriminate the class name, is not very elegant&#8230; even if that solution is probably a winner in terms of performance (no table joins needed). I am saying &#8220;probably&#8221; because it depends on how the database will handle a large number of columns with NULL values. Moreover, indexing a column of that big table means indexing all the recordings of that table&#8230; including, potentially, unnecessary ones.</p>
<p>Creating <strong>one table per concrete class</strong>, with as many foreign keys as there are inheritance relationships, is a classic solution&#8230; But with 26 classes, we need 26 tables.<br />
Moreover, if bottom classes have few attributes of their own, is it really necessary to create dedicated tables only for them?<br />
Couldn&#8217;t we limit the number of tables by combining some tables, locally?</p>
<p>That&#8217;s where <strong>mixing</strong> inheritance strategies comes in handy.</p>
<p>I suggest the following:<br />
- Each top and middle class will be mapped to a dedicated table<br />
- Bottom classes will be merged in the middle class they inherit</p>
<p>For example, classes <code>Molar</code> and <code>Tropoblast</code> will be grouped in the table Tropectoderm, classes <code>NeuroectodermPrimitive</code> and <code>NeuralTube</code> in the table Neuroectoderm, etc.</p>
<p>The table definition for Trophectoderm then becomes: <code>trophectoderm (id, a, b, c, d, e, f, type)</code><br />
Field <code>type</code> is the type discriminator of the class hierarchy (we need one, since we have merged some classes). By default, Hibernate automatically populates this field with the simple name of the Java classes.</p>
<p><strong>Mapping</strong></p>
<p>We set a &#8220;single table&#8221; strategy at the class Neoplasm :</p>
<pre class="brush:java">@Inheritance(strategy = InheritanceType.SINGLE_TABLE)</pre>
<p>Every level 2 class declares a secondary table :</p>
<pre class="brush:java">@SecondaryTable(name="NeuralCrest", pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))</pre>
<p>Level 3 classes use both the secondary table AND the global table (Neoplasm).</p>
<p>Note that JPA annotations are not automatically inherited, and therefore must explicitly be set in all the subclasses.<br />
Also note that it is necessary to redefine the table name in all the <code>@Column</code> annotations that refer to a secondary table:</p>
<pre class="brush:java">@Column (table = TABLE_NAME)
private String s;</pre>
<p>That&#8217;s why my code makes use of a public constant <code>TABLE_NAME</code>, in order to define in one single place the name of the mapped table.</p>
<p>Care should be taken to create a referential integrity constraint on the primary key of each table towards the primary key of Neoplasm (ie Trophectoderm.id -> Neoplasm.id, NeuralCrest.id -> Neoplasm.id, etc..). This will prevent deleting from a secondary table without deleting the associated row in Neoplasm.</p>
<p><strong>Using the API</strong></p>
<p>We can now make persistent our objects. For example:</p>
<pre class="brush:java">
NeuralCrestPrimitive NeuralCrestPrimitive ncp = new ();
ncp.setLatinName ("Pia mater");
ncp.setA ("Example # 1");
ncp.setB ("Example # 2");
session.persist (ncp);</pre>
<p>Hibernate then executes the following two commands:<br />
<code>insert into neoplasm (latinName, type) values ??('Pia Mater', 'NeuralCrestPrimitive')<br />
insert into neural_crest (a, b, id) values ??(Example # 1 Example # 2 [last inserted id])</code></p>
<p><strong>Conclusion</strong><br />
We mapped our object model to a database model containing 7 tables, instead of 26 tables with the usual <em>joined strategy</em>.<br />
A read operation in a bottom table requires only one table join, a write operation two inserts (or updates).<br />
It is a compromise solution, which is particularly interesting:<br />
- When the height of the hierarchical tree is large (at least 3 levels)<br />
- When the bottom classes structuraly differs little from one class to another within the same branch<br />
- When the class structure is very different from one branch to another</p>
<p><strong>Java classes</strong></p>
<pre class="brush:java">
// *********
// Top class
// *********

@Entity
@Table(name = Neoplasm.TABLE_NAME)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
abstract public class Neoplasm {

	public static final String TABLE_NAME = "neoplasm";

	@Id @GeneratedValue
	private int id;

	@Column(name = "latinName")
	private String latinName;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getLatinName() {
		return latinName;
	}
	public void setLatinName(String latinName) {
		this.latinName = latinName;
	}
}

// **************
// Middle classes
// **************

@Entity
@SecondaryTable(name=NeuralCrest.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class NeuralCrest extends Neoplasm {

	public static final String TABLE_NAME = "neural_crest";

	@Column(table=TABLE_NAME)
	private String a;

	@Column(table=TABLE_NAME)
	private String b;

	public String getA() {
		return a;
	}
	public void setA(String a) {
		this.a = a;
	}
	public String getB() {
		return b;
	}
	public void setB(String b) {
		this.b = b;
	}
}

@Entity
@SecondaryTable(name = GermCell.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class GermCell extends Neoplasm {

	public static final String TABLE_NAME = "germ_cell";
}

@Entity
@SecondaryTable(name = Mesoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class Mesoderm extends Neoplasm {

	public static final String TABLE_NAME = "mesoderm";
}

@Entity
@SecondaryTable(name = Neuroectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class Neuroectoderm extends Neoplasm {

	public static final String TABLE_NAME = "neuroectoderm";
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class EndodermEctoderm extends Neoplasm {

	public static final String TABLE_NAME = "endoderm_ectoderm";
}

@Entity
@SecondaryTable(name = Trophectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
abstract public class Trophectoderm extends Neoplasm {

	public static final String TABLE_NAME = "trophectoderm";
}

// **************
// Bottom classes
// **************

@Entity
@SecondaryTable(name = NeuralCrest.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Ectomesenchymal extends NeuralCrest {

	@Column(table=TABLE_NAME)
	private String d;

	public void setD(String d) {
		this.d = d;
	}

	public String getD() {
		return d;
	}
}

@Entity
@SecondaryTable(name = NeuralCrest.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class NeuralCrestEndocrine extends NeuralCrest {

	@Column(table=TABLE_NAME)
	private String d;

	@Column(table=TABLE_NAME)
	private String e;

	public void setD(String d) {
		this.d = d;
	}
	public String getD() {
		return d;
	}
	public void setE(String e) {
		this.e = e;
	}
	public String getE() {
		return e;
	}
}

@Entity
@SecondaryTable(name = NeuralCrest.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class NeuralCrestPrimitive extends NeuralCrest {

	@Column(table = TABLE_NAME)
	private String d;

	public void setD(String d) {
		this.d = d;
	}

	public String getD() {
		return d;
	}
}

@Entity
@SecondaryTable(name = NeuralCrest.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class PeripheralNervousSystem extends NeuralCrest {

	@Column(table=TABLE_NAME)
	private String c;

	@Column(table=TABLE_NAME)
	private String f;

	@Column(table=TABLE_NAME)
	private String g;

	public String getC() {
		return c;
	}
	public void setC(String c) {
		this.c = c;
	}
	public String getF() {
		return f;
	}
	public void setF(String f) {
		this.f = f;
	}
	public String getG() {
		return g;
	}
	public void setG(String g) {
		this.g = g;
	}
}

@Entity
@SecondaryTable(name = Mesoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Coelomic extends Mesoderm {
}

@Entity
@SecondaryTable(name = GermCell.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Differentiated extends GermCell {
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class EndodermEctodermEndocrine extends EndodermEctoderm {
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class EndodermEctodermPrimitive extends EndodermEctoderm {
}

@Entity
@SecondaryTable(name = Mesoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Mesenchymal extends Mesoderm {
}

@Entity
@SecondaryTable(name = Mesoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class MesodermPrimitive extends Mesoderm {
}

@Entity
@SecondaryTable(name = Trophectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Molar extends Trophectoderm {
}

@Entity
@SecondaryTable(name = Neuroectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class NeuralTube extends Neuroectoderm {
}

@Entity
@SecondaryTable(name = Neuroectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class NeuroectodermPrimitive extends Neuroectoderm {
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Odontogenic extends EndodermEctoderm {
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Parenchymal extends EndodermEctoderm {
}

@Entity
@SecondaryTable(name = GermCell.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Primordial extends GermCell {
}

@Entity
@SecondaryTable(name = Mesoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Subelomic extends Mesoderm {
}

@Entity
@SecondaryTable(name = EndodermEctoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Surface extends EndodermEctoderm {
}

@Entity
@SecondaryTable(name = Trophectoderm.TABLE_NAME, pkJoinColumns = @PrimaryKeyJoinColumn(name="id"))
public class Trophoblast extends Trophectoderm {
}
</pre>
<p><strong>Variant</strong><br />
Rather than letting Hibernate save textually the class name in the discriminator column, we could define an entity NeoplasmType(id, name), and set a foreign key in Neoplasm for this entity.<br />
We then must not forget to define the corresponding numerical identifier in every concrete class, with the annotation <code>@DiscriminatorValue</code>.</p>
<p>For example, the mapping of the class <code>Trophectoderm</code> becomes:</p>
<pre class="brush:java">
@Entity
@SecondaryTable(name="trophectoderm", pkJoinColumns=@PrimaryKeyJoinColumn(name="id"))
@DiscriminatorValue("3")	// si "3" est l'identifiant numérique correspondant à "Trophectoderm" dans la table NeoplasmType
abstract class Trophectoderm extends Neoplasm {
	(...)
}
</pre>
<p>We must also specify in Neoplasm that Hibernate should not rely on the class name to discriminate the entity class, but on a numeric identifier and a table join:</p>
<pre class="brush:java">
@Entity
@Table(name = Neoplasm.TABLE_NAME)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "id_type", discriminatorType = DiscriminatorType.INTEGER)
abstract public class Neoplasm {
	(...)
	@ManyToOne
	@JoinColumn(name="id_type", nullable=false, insertable=false, updatable=false)
	private NeoplasmType type;
	(...)
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2011/09/27/strategies-heritage-hibernate/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>EasyMock et Autowiring</title>
		<link>http://www.baptisteautin.com/2011/07/27/easymock-et-autowiring/lang/en/</link>
		<comments>http://www.baptisteautin.com/2011/07/27/easymock-et-autowiring/lang/en/#comments</comments>
		<pubDate>Wed, 27 Jul 2011 17:57:49 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[Formation]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=168&#038;lang=fr</guid>
		<description><![CDATA[Spring Test, JUnit and EasyMock are a good team for unit testing. Unfortunately, classes that inject their properties by autowiring can be difficult to test when these properties have to be mocked (DAO for example). Normally, with Spring, you inject your mocks thanks to the attribute factory-method : &#60;bean class="org.easymock.EasyMock" factory-method="createMock" id="ClientDAO"&#62; &#60;constructor-arg value="com.example.dao.IClientDAO" /&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Spring Test, JUnit and EasyMock are a good team for unit testing.<br />
Unfortunately, classes that inject their properties by autowiring can be difficult to test when these properties have to be mocked (DAO for example).</p>
<p>Normally, with Spring, you inject your mocks thanks to the attribute <code>factory-method</code> :</p>
<pre class="brush:xml">&lt;bean class="org.easymock.EasyMock" factory-method="createMock" id="ClientDAO"&gt;
	&lt;constructor-arg value="com.example.dao.IClientDAO" /&gt;
&lt;/bean&gt;
</pre>
<p>Now, let&#8217;s say that the class to be tested injects its DAO like this:</p>
<pre class="brush:java">@Autowired
protected IClientDAO cDao;
</pre>
<p>The context startup is then likely to fail:</p>
<p><code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.example.dao.IClientDAO] is defined: Unsatisfied dependency of type [interface com.example.dao.IClientDAO]: expected at least 1 matching bean</code></p>
<p>Why? Because Spring determines the type of a factory-method-defined bean <strong>by reflection</strong>. So if the method returns an <code>Object</code> or a parameterized type, just like <code>EasyMock.createMock()</code> does, autowiring by type will not work (even if you specify the bean&#8217;s name with <code>@Qualifier</code>).</p>
<p>Solutions :</p>
<ul>
<li>Utiliser l&#8217;annotation <code>@Resource</code>
<pre class="brush:java">@Resource(name="ClientDAO")
protected IClientDAO cDao;</pre>
<p>But you may not want to use that annotation, or make an explicit reference to the name of a bean.</li>
<li>Use an adapter class, that will explicitely specify the good return type (here, <code>IClientDAO</code>) :
<pre class="brush:java">public class MocksFactory {

	public IClientDAO getClientDAO() {
		return EasyMock.createMock(IClientDAO.class);
	}
}</pre>
<p>Unfortunately, you will have to write as many methods as there are objects to mock, which might be tedious.</p>
<p>If you are not satisfied with any of these two solutions, there is a last possibilty: defining an unmocked version of your class (so that autowiring can work), and then relying on the interface <code>BeanFactoryPostProcessor</code> to replace this unmocked bean, in Spring&#8217;s registry, by a mocked version.<br />
Just two classes are required for that:<br />
- a class <code>MocksFactory</code> to generate the mocked object (thanks to <code>FactoryBean</code>)<br />
- a class <code>MocksFactoryPostProcessor</code> which will receive a list of beans names to redefine.</li>
</ul>
<pre class="brush:java">import org.easymock.classextension.EasyMock;
import org.springframework.beans.factory.FactoryBean;

public class MocksFactory implements FactoryBean {

	private Class<?> type;

	public void setType(final Class<?> type) {
		this.type = type;
	}

	@Override
	public Object getObject() throws Exception {
		return EasyMock.createMock(type);
	}

	@Override
	public Class<?> getObjectType() {
		return type;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}</pre>
<pre class="brush:java">import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;

public class MocksFactoryPostProcessor implements BeanFactoryPostProcessor {

	private static final Class<MocksFactory> factoryClass = MocksFactory.class;

	private String[] beanNames;

	@Override
	public void postProcessBeanFactory(final ConfigurableListableBeanFactory context) throws BeansException {

		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) context;

		for (String beanName : beanNames) {

			BeanDefinition bd = registry.getBeanDefinition(beanName);

			MutablePropertyValues values = new MutablePropertyValues();
			values.addPropertyValue(new PropertyValue("type", bd.getBeanClassName()));

			RootBeanDefinition definition = new RootBeanDefinition(factoryClass, values);
			registry.registerBeanDefinition(beanName, definition);
		}
	}

	public void setBeanNames(String[] beans) {
		this.beanNames = beans;
	}
}
</pre>
<p>Finally, in the applicationContext.xml, the comma-separated list of beans names is set through the property <em>beanNames</em> :</p>
<pre class="brush:java">&lt;bean id="ClientDAO" class="com.example.dao.ClientDAO"/&gt;
&lt;bean id="mocksFactoryPostProcessor" class="com.example.MocksFactoryPostProcessor"&gt;
	&lt;property name="beanNames" value="ClientDAO,ProductDAO,ContractDAO"/&gt;
&lt;/bean&gt;</pre>
<p>Note that this solution requires that you make use of <code>classextension.EasyMock</code> (to mock by concrete class, and not by interface).</p>
<p>Remarque : instead of defining all the bean names, like we are doing, we could browse Spring&#8217;s registry and redefine all those that are injected with <code>@Autowired</code>&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2011/07/27/easymock-et-autowiring/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Date conversion with Castor XML</title>
		<link>http://www.baptisteautin.com/2010/04/04/date-conversion-with-castor-xml/lang/en/</link>
		<comments>http://www.baptisteautin.com/2010/04/04/date-conversion-with-castor-xml/lang/en/#comments</comments>
		<pubDate>Sun, 04 Apr 2010 20:29:00 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[Formation]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=183&#038;lang=fr</guid>
		<description><![CDATA[Castor is a lightweight and efficient Java / XML data binding tool. One of the first pitfalls you can fall into is conversion date. Castor provides a mechanism to customize serialize / deserialize fields via a handler class. The most practical solution I&#8217;ve experienced is to extend the class GeneralizedFieldHandler, as in the example below. [...]]]></description>
			<content:encoded><![CDATA[<p>Castor is a lightweight and efficient Java / XML data binding tool.<br />
One of the first pitfalls you can fall into is <strong>conversion date</strong>.<br />
Castor provides a mechanism to customize serialize / deserialize fields via a handler class. The most practical solution I&#8217;ve experienced is to extend the class <code>GeneralizedFieldHandler</code>, as in the example below.</p>
<p>Here is our Java bean instance:</p>
<pre class="brush:java">package articles;

import java.util.Date;

public class Version {

	private String name;
	private Date releaseDate;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getReleaseDate() {
		return releaseDate;
	}
	public void setReleaseDate(Date date) {
		this.releaseDate = date;
	}
}
</pre>
<p>The Castor mapping file <em>/articles/mapping.xml</em>:</p>
<pre class="brush:xml">&lt;?xml version="1.0"?&gt;
&lt;!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.org/mapping.dtd"&gt;
&lt;mapping&gt;
	&lt;description&gt;&lt;/description&gt;
	&lt;class name="articles.Version"&gt;
		&lt;map-to xml="version" /&gt;
		&lt;field name="releaseDate" type="string" handler="articles.DateHandler"&gt;
			&lt;bind-xml name="releaseDate" /&gt;
		&lt;/field&gt;
		&lt;field name="name" type="string"&gt;
			&lt;bind-xml name="name" /&gt;
		&lt;/field&gt;
	&lt;/class&gt;
&lt;/mapping&gt;</pre>
<p>The sample XML file (for unmarshalling) <em>/articles/history.xml</em>:</p>
<pre class="brush:xml">&lt;?xml version="1.0" standalone="yes"?&gt;
&lt;versions&gt;
	&lt;version&gt;
		&lt;name&gt;JDK 1.1.4&lt;/name&gt;
		&lt;releaseDate&gt;12-09-1997&lt;/releaseDate&gt;
	&lt;/version&gt;
	&lt;version&gt;
		&lt;name&gt;JDK 1.1.5&lt;/name&gt;
		&lt;releaseDate&gt;03-12-1997&lt;/releaseDate&gt;
	&lt;/version&gt;
	&lt;version&gt;
		&lt;name&gt;JDK 1.1.6&lt;/name&gt;
		&lt;releaseDate&gt;typo&lt;/releaseDate&gt;
	&lt;/version&gt;
&lt;/versions&gt;
</pre>
<p>The handler class:</p>
<pre class="brush:java">package articles; 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.exolab.castor.mapping.GeneralizedFieldHandler;

public class DateHandler extends GeneralizedFieldHandler {

	private static final Log logger = LogFactory.getLog(DateHandler.class);

	private static final String FORMAT = "dd-MM-yyyy";

	private SimpleDateFormat formatter = new SimpleDateFormat(FORMAT);

	public Object convertUponGet(Object value) {
		if (value == null) {
			return "13-07-1974";	// default value if null date
		}
		Date date = (Date) value;
		return formatter.format(date);
	}

	public Object convertUponSet(Object value) {
		Date date = null;
		try {
			date = formatter.parse((String) value);
		}
		catch (ParseException px) {
			logger.error("Parse Exception (bad date format) : " + (String) value);
			return null;  // default value for empty/incorrect date
		}
		return date;
	}

	public Class&lt;?&gt; getFieldType() {
		return Date.class;
	}

	public Object newInstance(Object parent) throws IllegalStateException {
		return null;
	}
}
</pre>
<p>And finally the executable:</p>
<pre class="brush:java">package articles;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;

import org.apache.log4j.Logger;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;

public class CastorTest {

	private static Logger logger = Logger.getLogger(CastorTest.class);
	private static Mapping mapping = getMapping();

	final private static String MAPPING_FILE = "/articles/mapping.xml";

	public static void main(String[] args) throws MappingException, MarshalException, ValidationException, IOException {

		/**
		 * Unmarshalling (XML -&gt; Java)
		 */

		Unmarshaller unmarshaller = new Unmarshaller(ArrayList.class);
		unmarshaller.setIgnoreExtraElements(true);
		unmarshaller.setMapping(mapping);

		String dataFile = CastorTest.class.getResource("/articles/history.xml").getPath();
		InputSource source = new InputSource(dataFile);
		ArrayList&lt;Version&gt; list = (ArrayList&lt;Version&gt;) unmarshaller.unmarshal(source);

		logger.debug("Unmarshalling :");
		for (Version item : list) {
			logger.debug("Name = " + item.getName());
			logger.debug("Date = " + item.getReleaseDate());
		}

		/**
		 * Marshalling (Java -&gt; XML)
		 */

		Marshaller marshaller = new Marshaller();
		Writer writer = new StringWriter();

		marshaller.setWriter(writer);
		marshaller.setMapping(mapping);

		Version v = new Version();
		v.setName("New name");
		v.setReleaseDate(new Date());

		marshaller.marshal(v);

		logger.debug("Marshalling :");
		logger.debug(writer.toString());
	}

	static protected Mapping getMapping() {

		String mapFile = CastorTest.class.getResource(MAPPING_FILE).getPath();
		InputSource is = new InputSource(mapFile);

		Mapping mapping = new Mapping();
		mapping.loadMapping(is);

		return mapping;
	}
}
</pre>
<p>Expected traces at runtime :</p>
<p><code>DEBUG [main] (CastorTest.java:39) [] - Unmarshalling :<br />
DEBUG [main] (CastorTest.java:41) [] - Name = JDK 1.1.4<br />
DEBUG [main] (CastorTest.java:42) [] - Date = Fri Sep 12 00:00:00 CEST 1997<br />
DEBUG [main] (CastorTest.java:41) [] - Name = JDK 1.1.5<br />
DEBUG [main] (CastorTest.java:42) [] - Date = Wed Dec 03 00:00:00 CET 1997<br />
DEBUG [main] (CastorTest.java:41) [] - Name = JDK 1.1.6<br />
DEBUG [main] (CastorTest.java:42) [] - Date = null<br />
(...)<br />
DEBUG [main] (CastorTest.java:61) [] - Marshalling :<br />
DEBUG [main] (CastorTest.java:62) [] - &lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />
&lt;version&gt;&lt;releaseDate&gt;04-04-2011&lt;/releaseDate&gt;&lt;name&gt;New name&lt;/name&gt;&lt;/version&gt;</code></p>
<p>Note how the deliberately erroneous date in the third &lt;version&gt; of the list has been handled, and how we get a <code>null</code> instead, as expected.<br />
The advantage of extending <code>GeneralizedFieldHandler</code>, as we do, is that <code>DateHandler</code> can be reused for other date fields. However, if different date formats were expected, we would have to implement <code>ConfigurableFieldHandler</code>.</p>
<p>More information:<br />
<a href="http://www.castor.org/xml-fieldhandlers.html">http://www.castor.org/xml-fieldhandlers.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2010/04/04/date-conversion-with-castor-xml/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Work Study</title>
		<link>http://www.baptisteautin.com/2009/03/23/mes-travaux-scolaires/lang/en/</link>
		<comments>http://www.baptisteautin.com/2009/03/23/mes-travaux-scolaires/lang/en/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 21:12:28 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[Formation]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=114&#038;lang=fr</guid>
		<description><![CDATA[On 14 November 2008, I defended my degree work in computer science at the CNAM high school of Paris, thus completing five years of studies taken in addition to my job. My studies at the CNAM are marked by diversity. They began with a first set of courses called &#8220;Driving System&#8221; (systems architecture, system programming [...]]]></description>
			<content:encoded><![CDATA[<p>On 14 November 2008, I defended my degree work in computer science at the CNAM high school of Paris, thus completing five years of studies taken in addition to my job.</p>
<p>My studies at the CNAM are marked by diversity.<br />
They began with a first set of courses called &#8220;Driving System&#8221; (systems architecture, system programming (C under Linux), software engineering, distributed applications, networks).</p>
<p>My major was database engineering: relationnal/multimedia/spatial databases, indexing, documents searching, as well as the XML standards.</p>
<p>I also wrote a report about metaheuristics (which are particular iterative techniques to optimize combinatorial problems).</p>
<ul>
<li class="download"><a href="/wp-content/uploads/Rapport-Metaheuristiques-Optimisation-Combinatoire.doc">Mon rapport sur les métaheuristiques</a></li>
</ul>
<p>My final report focused on my work at the Institut Curie for 18 months, where I developed a distributed software to integrate biomedical, statistical and genomic data.</p>
<ul>
<li class="download"><a href="/wp-content/uploads/Memoire-Ingenieur-Baptiste-Autin.7z">Mon mémoire d&#8217;ingénieur</a></li>
<li class="download"><a href="http://www.agence-nationale-recherche.fr/AAPProjetsOuverts?NodId=17&#038;lngAAPId=71" rel="external">L&#8217;appel à projet initial</a></li>
</ul>
<p>These courses at the CNAM, added to my initial training as an analyst-programmer (see my <a href="/cv/lang/en">CV</a>) allow me to deal with many problems arising in IT.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2009/03/23/mes-travaux-scolaires/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A web-XML architecture</title>
		<link>http://www.baptisteautin.com/2009/02/10/une-architecture-web-xml/lang/en/</link>
		<comments>http://www.baptisteautin.com/2009/02/10/une-architecture-web-xml/lang/en/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 21:42:42 +0000</pubDate>
		<dc:creator>Baptiste Autin</dc:creator>
				<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.baptisteautin.com/?p=37&#038;lang=fr</guid>
		<description><![CDATA[Sorry, but this post is not available in English]]></description>
			<content:encoded><![CDATA[<p>Sorry, but this post is not available in English</p>
]]></content:encoded>
			<wfw:commentRss>http://www.baptisteautin.com/2009/02/10/une-architecture-web-xml/feed/lang/en/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

