<?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>Xebia Blog &#187; annotations</title>
	<atom:link href="http://blog.xebia.com/tag/annotations/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.xebia.com</link>
	<description>Software development done right!</description>
	<lastBuildDate>Wed, 01 Feb 2012 00:30:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to use annotations for configuration</title>
		<link>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/</link>
		<comments>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 22:34:38 +0000</pubDate>
		<dc:creator>Maarten Winkels</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[jackson]]></category>
		<category><![CDATA[resteasy]]></category>
		<category><![CDATA[Seam]]></category>

	<!-- AutoMeta Start -->
	<category>objectmapper</category>
	<category>annotationintrospector</category>
	<category>ejbexception</category>
	<category>jackson</category>
	<category>customobjectmapper</category>
	<category>objectmapper</category>
	<category>annotationintrospector</category>
	<category>ejbexception</category>
	<category>jackson</category>
	<category>customobjectmapper</category>
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=6460</guid>
		<description><![CDATA[In the java world we have been using and getting used to annotations since Java 1.5. Although there were some critical voices at first, I think most of us have come around and are using annotations now quite extensively. In my experience annotations are mostly used on POJO domain classes to configure frameworks like Hibernate, [...]]]></description>
			<content:encoded><![CDATA[<p>In the java world we have been using and getting used to annotations since Java 1.5. Although there were <a href="http://blog.xebia.com/2007/01/28/a-pojo-with-annotations-is-not-plain/">some</a> <a href="http://blog.xebia.com/2007/04/03/ejb-3-annotations-to-the-max/">critical</a> <a href="http://willcode4beer.blogspot.com/2007/12/annotations-good-bad-and-ugly.html">voices</a> at first, I think most of us have come around and are using annotations now quite extensively. In my experience annotations are mostly used on POJO domain classes to configure frameworks like <a href="http://www.hibernate.org/">Hibernate</a>, <a href="http://www.springsource.org/">Spring</a> and <a href="http://www.seamframework.org/">Seam</a> and <a href="http://xstream.codehaus.org/">many</a> <a href="http://jaxb.java.net/">other</a> <a href="http://www.testng.org/">frameworks</a> to be able to handle the custom objects correctly.</p>
<p>There are as many different approaches to this as there are implementations. In this blog I try to identify a few of the better approaches and a few of the poorer ones. The blog is not so much meant as a critique on the frameworks that the examples are taken from, but more as a guide to designing your own annotations whenever you might be faced with that task.<br />
<span id="more-6460"></span></p>
<h3>Prime examples: JPA annotations</h3>
<p>The best examples of using annotations for configuration &#8211; both good and bad &#8211;  can be found in JPA Entity classes.</p>
<pre class="brush: java; title: ; notranslate">
@Entity
@Table(name=&quot;person&quot;)
public class Person {

  @Id
  @GeneratedValue(strategy=SEQUENCE)
  @Column(name = &quot;personId&quot;)
  private Long id;

  @Valid @NotEmpty
  @OneToMany(cascade = CascadeType.ALL)
  @JoinColumn(name = &quot;personId&quot;, nullable = false)
  @org.hibernate.annotations.Cascade(CascadeType.DELETE_ORPHAN)
  @org.hibernate.annotations.IndexColumn(name = &quot;position&quot;)
  private List&lt;Address&gt; addresses = new ArrayList&lt;Address&gt;();
  ...
}
</pre>
<p>What a wealth of annotations! And in such a few lines of code. Anybody that has dealt with this type of code before however, will testify that this example is not overly complex at all. You&#8217;ll find this ind of code all over.</p>
<p>To start with, let&#8217;s say that I think this type of coding has been extremely successful. So regardless whether we find the usage of annotations in this example recommendable or not, if you work with Java code, you&#8217;ll be reading and writing a lot of code like this, so understanding it is imperative. However success is just one of the indicators for quality and it is always good to think about how things can be improved.</p>
<h3>A perfect annotation</h3>
<p>Of course there is no such thing as a perfect annotation. But as a general rule of thumb a good annotation should <i>describe</i> the annotated element and be meaningful <i>outside its intended context</i>. This last requirement is a little bit vague. I hope it will become more clear once we look at some examples.</p>
<p>Annotations are very often used as a convenient means of configuration. This type of usage breaks the above rule for &#8216;perfect annotations&#8217;, but they are very convenient and very widely used. Drawbacks of this type of usage are:</p>
<ol>
<li>To change the configuration the source code needs to be recompiled.</li>
<li>The annotations (and thus their containing packages and often all of the framework code) need to be on the classpath for compilation and running.</li>
<li>Only one configuration can (usually) be specified. Most frameworks allow for a different means of configuration to circumvent this.</li>
</ol>
<p>&#8230;but these drawbacks do not mean that this type of usage has been less successful in the wild. On the contrary! There are however ways to design frameworks so that they can be configured by annotations that are not impacted by these drawbacks.</p>
<p>Let&#8217;s look at the example above in the light of these </p>
<ol>
<li>The <span style="font-family: monospace">@Entity</span> annotation specifies that instances of this class should contains data that is to be persisted. It describes how the class is intended. It also allows several frameworks to operate on it.</li>
<li>The <span style="font-family: monospace">@Table</span> annotation is pure configuration. It does not describe anything about this class and is tightly bound to its context: Databases.</li>
<li>The <span style="font-family: monospace">@Valid</span> and <span style="font-family: monospace">@NotEmpty</span> annotations describe features of <i>valid</i> instances of this class. They are however quite tightly bound to their context: data validation.</i>
</ol>
<p>For each of the annotations in the example such a analysis can be made. It is interesting to think about how <i>useful</i> the annotations are in relation how <i>perfect</i> they are: The <span style="font-family: monospace">@Entity</span> annotation, although being almost perfect is, is actually superfluous, because it will never be used without the <span style="font-family: monospace">@Table</span> annotation. The <span style="font-family: monospace">@Valid</span> and <span style="font-family: monospace">@NotEmpty</span> annotations are much more useful: They allow very powerful cross-cutting concerns to be implemented with very little code, configuration or dependency of application code on framework code, making it easy to test and reuse this code.</p>
<h3>Configuration annotation patterns in the wild</h3>
<h4> The Worst</h4>
<p>All this dribble about perfect annotations is nice and dandy, but where does it lead us? Maybe it is better to look at the other end of the spectrum, where we find the very worst of annotations:</p>
<pre class="brush: java; title: ; notranslate">
  @XmlJavaTypeAdapter(CurrencyAdapter.class)
  private BigDecimal price;
</pre>
<p>This <a href="http://download.oracle.com/javaee/5/api/javax/xml/bind/annotation/adapters/XmlJavaTypeAdapter.html">JAXB annotation</a>, used to configure the way a value is represented in XML, ties the implementation of a framework interface to the field on the domain class we&#8217;re trying to configure the framework for. We could as well implement the interface in the class itself!</p>
<h4> Better&#8230; Level of indirection</h4>
<p>A better pattern can be found in the seam framework for <a href="http://docs.jboss.org/seam/latest/reference/en-US/html_single/#d0e5568">configuring interceptors</a>. The following code configures an interceptor around a business method to measure the time it takes to complete.</p>
<pre class="brush: java; title: ; notranslate">
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Interceptors(SeamTimingInterceptor.class)
public @interface MeasureCalls {}
</pre>
<pre class="brush: java; title: ; notranslate">
...
	@MeasureCalls
	public void someBusinessMethod() {
		...
	}
...
</pre>
<pre class="brush: java; title: ; notranslate">
@Interceptor(around = {
	BijectionInterceptor.class,
	...
	SeamInterceptor.class,
})
public class SeamTimingInterceptor {

	@AroundInvoke
	public Object timeCall(InvocationContext invocation) throws Exception {
		long t0 = System.nanoTime();
		try {
			return invocation.proceed();
		} finally {
			long dt = System.nanoTime() - t0;
			// Log time.
		}
	}
}
</pre>
<p>The first annotation just defines a cross-cutting feature that we would like to implement in our application. We can easily use it in our application as shown by the second fragment.</p>
<p>Coming to the last code fragment, the actual implementation of the interceptor, i feel that the framework designers went a little overboard and were too annotation-happy: The interceptor could have simply implemented an interface:</p>
<pre class="brush: java; title: ; notranslate">
public interface  AroundMethodInterceptor {
	Object aroundInvoke(InvocationContext invocation);
}
</pre>
<p>This would have made the contract for an interceptor much clearer.</p>
<p>It could also help solve the other problem with this implementation: Now, the business class needs the annotation to compile, the annotation needs the interceptor and the interceptor needs the framework classes. From this perspective, the extra level of indirection has not helped a bit.</p>
<h4>Best&#8230; Classpath scanning and interfaces</h4>
<p>Another approach that is quite elegant is the JAX-RS approach to extending the framework through <a href="http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/ext/Provider.html">Provider</a>s and the <a href="http://www.jboss.org/resteasy">RESTEasy</a> implementation for it. The code below automatically registers an exception mapper, which integrates with the framework and is used to handle EJB exceptions coming from resource methods.</p>
<pre class="brush: java; title: ; notranslate">
@Provider
public class EJBExceptionMapper implements ExceptionMapper&lt;EJBException&gt; {

	@Context
	private Providers providers;

	@Override
	public Response toResponse(EJBException exception) {
		while (exception.getCause() != null
				&amp;&amp; exception.getCause() instanceof EJBException) {
			exception = (EJBException) exception.getCause();
		}
		Exception cause = exception.getCausedByException();
		ExceptionMapper delegate = providers.getExceptionMapper(cause.getClass());
		if (delegate != null) {
			return delegate.toResponse(cause);
		} else {
			return ExceptionUtil.serverError(cause.getMessage());
		}
	}
}
</pre>
<p>The good thing here is that the framework will scan for the annotation and then register the class according to its interface it implements.</p>
<p>Another interesting aspect is the <span style="font-family: monospace">@Context</span> annotation, that basically works as an injector point.</p>
<h4>Extensions for custom annotations</h4>
<p>This mechanism can be used to configure the RESTEasy framework to handle custom annotations for custom serialization. <a href="http://jackson.codehaus.org/">Jackson</a> has a similar mechanism like JAXB for configuring the way a field is seriaized with the <a href="http://jackson.codehaus.org/1.7.0/javadoc/org/codehaus/jackson/map/annotate/JsonSerialize.html">@JsonSerializer</a> annotation. Unfortunately this has the same drawbacks. A better approach can be implemented using the Provider mechanism on the Jackson framework itself.</p>
<pre class="brush: java; title: ; notranslate">
@Provider
public class ObjectMapperResolver implements ContextResolver&lt;ObjectMapper&gt; {

	private AnnotationIntrospector annotationIntrospector;

	public ObjectMapper getContext(Class&lt;?&gt; type) {
		return new CustomObjectMapper();
	}

	class CustomObjectMapper extends ObjectMapper {

		/**
		 * Constructor.
		 */
		public CustomObjectMapper() {
			super(null, null, null,
					new SerializationConfig(
						DEFAULT_INTROSPECTOR,
						pair(annotationIntrospector,DEFAULT_ANNOTATION_INTROSPECTOR),
						STD_VISIBILITY_CHECKER, null),
					new DeserializationConfig(DEFAULT_INTROSPECTOR,
						pair(annotationIntrospector,DEFAULT_ANNOTATION_INTROSPECTOR),
						STD_VISIBILITY_CHECKER, null)
					);
		}
	}
}
</pre>
<p>The above class &#8216;provides&#8217; the Jackson framework with a custom <span style="font-family: monospace">ObjectMapper</span>. This is done automatically, because the class is annotated with <span style="font-family: monospace">@Provider</span> and implements <span style="font-family: monospace">ContextResolver&lt;ObjectMapper></span>. Now the RESTEasy framework recognizes this as a part of the framework that will provide a <span style="font-family: monospace">ObjectMapper</span> to inject into a <span style="font-family: monospace">@Context</span> injection point. The Jackson framework uses the same injection point to find a <span style="font-family: monospace">ObjectMapper</span> to use for serialization.</p>
<p>Now how do we get it to recognize our own annotations? The answer is given by the code below, which is used in the custom <span style="font-family: monospace">ObjectMapper</span>.</p>
<pre class="brush: java; title: ; notranslate">
public class CustomAnnotationInspector extends NopAnnotationIntrospector {

	private Map&lt;Class&lt;? extends Annotation&gt;, String&gt; serializerComponents =
		new HashMap&lt;Class&lt;? extends Annotation&gt;, String&gt;();

	@Override
	public Object findSerializer(Annotated am, BeanProperty bp) {
		if (property != null) {
			for (Annotation annotation : bp.getMember().getAnnotated().getAnnotations()) {
				String name = serializerComponents.get(annotation.annotationType());
				if (name != null) {
					return Component.getInstance(name);
				}
			}
		}
		return super.findSerializer(am, bp);
	}
}
</pre>
<p>This can be used as shown below, when a serializer for the <span style="font-family: monospace">@Currency</span> is configured in the <span style="font-family: monospace">seriliazerComponents</span> map. (We use this in combination with the Seam framework for configuration).</p>
<pre class="brush: java; title: ; notranslate">
@Target({FIELD, METHOD})
@Retention(RUNTIME)
public @interface Currency {}

...
	@Currency
	BigInteger price;
...
</pre>
<h3>Conclusion</h3>
<p>In this blog I&#8217;ve shown a number of patterns for configuring frameworks using annotations. I&#8217;ve also shown some useful classes for extending the RESTEasy and Jackson  frameworks with support for custom annotations. I hope these examples will inspire you to write your own perfect and useful annotations.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2011%2F04%2F15%2Fhow-to-use-annotations-for-configuration%2F&amp;title=How%20to%20use%20annotations%20for%20configuration" id="wpa2a_2"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2011/04/15/how-to-use-annotations-for-configuration/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>@Composite for Unpacking COFF Data</title>
		<link>http://blog.xebia.com/2009/07/04/composite-for-unpacking-coff-data/</link>
		<comments>http://blog.xebia.com/2009/07/04/composite-for-unpacking-coff-data/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 10:37:38 +0000</pubDate>
		<dc:creator>Wilfred Springer</dc:creator>
		<br />
<b>Warning</b>:  Invalid argument supplied for foreach() in <b>/home/blog.xebia.com/www/wp-content/plugins/autometa/autometa.php</b> on line <b>303</b><br />
		<category><![CDATA[Java]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bit syntax]]></category>
		<category><![CDATA[erlang]]></category>

	<!-- AutoMeta Start -->
	<!-- AutoMeta End -->
	
		<guid isPermaLink="false">http://blog.xebia.com/?p=2387</guid>
		<description><![CDATA[A while ago, I compared Preon with Erlang&#8217;s bit syntax. I looked at one one of the examples from &#8220;Programming Erlang&#8221; in particular; an example that illustrates how to decode MPEG headers using Erlang. However, this is not the only example in that chapter, so I decided to take a stab at one of the [...]]]></description>
			<content:encoded><![CDATA[<p>A while ago, I <a href="http://blog.flotsam.nl/2009/02/bit-syntax-for-java-i.html">compared <a href="http://preon.flotsam.nl/">Preon</a> with Erlang&#8217;s bit syntax</a>. I looked at one one of the examples from &#8220;Programming Erlang&#8221; in particular; an example that illustrates how to decode MPEG headers using Erlang. However, this is not the only example in that chapter, so I decided to take a stab at one of the other examples as well.</p>
<p><span id="more-2387"></span></p>
<p>The second example from the bit syntax chapter in &#8220;Programming Erlang&#8221; is about unpacking <a href="http://en.wikipedia.org/wiki/COFF">COFF</a> data. The thing about COFF is that it doesn&#8217;t have an IDL-alike language or anything for defining the data structures: all you have is the definition of C++ data structures, such as the one below:</p>
<pre class="brush: cpp; title: ; notranslate">
typedef struct _IMAGE_RESOURCE_DIRECTORY {
DWORD Characteristics;
DWORD TimeDateStamp;
WORD MajorVersion;
WORD MinorVersion;
WORD NumberOfNamedEntries;
WORD NumberOfIdEntries;
} IMAGE_RESOURCE_DIRECTORY, *PIMAGE_RESOURCE_DIRECTORY;
</pre>
<p>In his book, Joe Armstrong explains that using Erlang&#8217;s bit syntax and macro solutions, you would be able to unpack COFF data characterized by the C++ struct above using the Erlang code listed below.</p>
<pre class="brush: plain; title: ; notranslate">
unpack_image_resource_directory(Dir) -&gt;
  &lt;&lt;Characteristics : ?DWORD,
    TimeDateStamp : ?DWORD,
    MajorVersion : ?WORD,
    MinorVersion : ?WORD,
    NumberOfNamedEntries : ?WORD,
    NumberOfIdEntries : ?WORD, _/binary&gt;&gt; = Dir,
...
</pre>
<p>The key message here is that Erlang not only allows you to unpack binary data easily, but that it also allows you to express that clearly maps to the only source of definition of the data structure: the C++ API.</p>
<p>Now, if you would use Preon only, the C++ data structure above would translate to this:</p>
<pre class="brush: java; title: ; notranslate">
class ImageResourceDirectory {
  @BoundNumber(size=&quot;32&quot;) long characteristics;
  @BoundNumber(size=&quot;32&quot;) long timeDateStamp;
  @BoundNumber(size=&quot;16&quot;) int majorVersion;
  @BoundNumber(size=&quot;16&quot;) int minorVersion;
  @BoundNumber(size=&quot;16&quot;) int numberOfNamedEntries;
  @BoundNumber(size=&quot;16&quot;) int numberOfIdEntries;
}
</pre>
<p>&#8230; and you would be able to decode it by this:</p>
<pre class="brush: java; title: ; notranslate">
Codec&lt;ImageResourceDirectory&gt; codec = Codecs.create(ImageResourceDirectory.class);
Codecs.decode(codec, ...);
</pre>
<p>Now, that&#8217;s not bad, but it doesn&#8217;t have that similarity to the original C++ API code the Erlang example has. However, using Andrew Philips&#8217; <a href="http://blog.xebia.com/2009/06/23/composite-macro-annotations-for-java/">@Composite framework</a>, you <i>would</i> actually be able to write this:</p>
<pre class="brush: java; title: ; notranslate">
class ImageResourceDirectory {
  @DWORD long characteristics;
  @DWORD long timeDateStamp;
  @WORD int majorVersion;
  @WORD int minorVersion;
  @WORD int numberOfNamedEntries;
  @WORD int numberOfIdEntries;
}
</pre>
<p>&#8230; which is already a lot closer to the original C++ struct than what we had before. </p>
<p>Support for @Composite has not been included in Preon yet. At first sight, there appear to be two ways to deal with it. First of all, it could be build into the framework, by the AnnotatedElements interface all over the place. That should work, and it might actually be the most sensible thing to do.</p>
<p>However, there may be an alternative way to get it woven in. Preon already defines a <a href="http://preon.flotsam.nl/preon-binding/apidocs/nl/flotsam/preon/CodecDecorator.html">CodecDecorator</a> interface that allows you wrap Codec implementations around Codec instances created. Looking at that, I started to think that it might actually be quite attractive to also define a CodecFactoryDecorator, wrapping CodecFactories around other CodecFactories in the chain of responsibility.</p>
<pre class="brush: java; title: ; notranslate">
public interface CodecFactory {
    &lt;T&gt; Codec&lt;T&gt; create(AnnotatedElement metadata, Class&lt;T&gt; type,
            ResolverContext context);
}
</pre>
<p>The wrappers created by the CodecFactoryDecorator would be able to intercept any reference to annotations passed down below down the chain, and replace it with an AnnotatedElement that uses <a href="http://code.google.com/p/aphillips/source/browse/at-composite/trunk/src/main/java/com/qrmedia/pattern/compositeannotation/api/AnnotatedElements.java">AnnotatedElements</a> to gain access to the annotations. As a consequence, CodecFactories responsible for creating the actual Codec from metadata passed in would get to see Preon annotations only, instead of the @DWORD and @WORD annotations.</p>
<p>It&#8217;s just a thought. None of this has been implemented yet. Feel free to comment. Expect to see some more of this in the future.</p>
<div name="googleone_share_1" style="position:relative;z-index:5;float: right; margin-left: 10px;"><g:plusone size="small" count="1" href="http://blog.xebia.com/2009/07/04/composite-for-unpacking-coff-data/"></g:plusone></div><p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.xebia.com%2F2009%2F07%2F04%2Fcomposite-for-unpacking-coff-data%2F&amp;title=%40Composite%20for%20Unpacking%20COFF%20Data" id="wpa2a_4"><img src="http://blog.xebia.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.xebia.com/2009/07/04/composite-for-unpacking-coff-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  blog.xebia.com/tag/annotations/feed/ ) in 0.56956 seconds, on Feb 9th, 2012 at 4:25 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 9th, 2012 at 5:25 pm UTC -->
