<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-6137205730562326735</id><updated>2026-04-03T04:44:40.177-07:00</updated><category term="cdi"/><category term="seam"/><category term="contexts"/><category term="ejb"/><category term="jsf"/><category term="architecture"/><category term="jee"/><category term="jquery"/><category term="richfaces"/><category term="ajax"/><category term="dependency injection"/><category term="google guice"/><category term="gwt"/><category term="jogger"/><category term="mokai"/><title type='text'>Thoughts on Software Architecture</title><subtitle type='html'>Discussion regarding Java Frameworks and Architecture.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>14</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-2053350087834952067</id><published>2012-05-14T10:02:00.000-07:00</published><updated>2012-05-14T12:37:12.930-07:00</updated><title type='text'>Jogger design decisions FAQ</title><content type='html'>&lt;a href=&quot;https://github.com/germanescobar/jogger&quot; target=&quot;_blank&quot;&gt;Jogger&lt;/a&gt; is a lightweight library for building Web Applications that provides a routing mechanism and a view template engine based on &lt;a href=&quot;http://freemarker.sourceforge.net/&quot; target=&quot;_blank&quot;&gt;FreeMarker&lt;/a&gt;. The source and documentation are on &lt;a href=&quot;https://github.com/germanescobar/jogger&quot; target=&quot;_blank&quot;&gt;Github&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
In this post, however, I would like to answer some questions about design decisions I made with Jogger that will help you understand the philosophy behind.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why do we need another Java Web Framework?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
I wanted a super simple Java web framework that would allow me to:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Map HTTP requests to Java methods: similar to Play! Framework (which is inspired by Ruby on Rails).&lt;/li&gt;
&lt;li&gt;Use a better request/response API than the one provided by the Servlet API.&lt;/li&gt;
&lt;li&gt;Define views and layouts: reuse layouts in multiple views.&lt;/li&gt;
&lt;li&gt;Plug into any project: let me choose the project structure and the libraries/frameworks I want to use; don’t make this hard on me.&lt;/li&gt;
&lt;li&gt;Deploy into any Servlet Container: such as Jetty or Tomcat.&lt;/li&gt;
&lt;li&gt;Easy testing: test controllers and views without having to start a Servlet Container.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why not a component based framework like JSF, Wicket, etc.?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Short answer is that they couldn&#39;t keep the promise of isolating the user from client side development and the request/response nature of HTTP. Long answer is &lt;a href=&quot;http://www.germanescobar.net/2012/05/java-web-development-back-to-basics.html&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why not using the Servlet API directly?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Because it sucks! It&#39;s difficult to test, it has an endless hierarchy of classes, exposes hundreds of useless methods and provides an inconvenient configuration mechanism. The only good part is that it doesn&#39;t try to hide the request/response nature of HTTP.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why using FreeMarker for the view?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
JSP&#39;s (Java Server Pages) were dismissed from the beginning, you just can&#39;t create and reuse a layout with them. My first options were Jade and Haml but there is not a decent implementation for Java that I know. The truth is that I am happy with FreeMarker now.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why not using annotations instead of the routes.config file?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
First, with annotations you would have all this routing configuration scattered in multiple Java files. I wanted to keep this information centralized and as simple as I could. Second, I&#39;m against of scanning the classpath (one of the reasons I moved away from JEE), it just doesn&#39;t scale. Third, it would be a problem for hot deployment.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why exposing the Jogger Request and Response in the controller actions?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Because I think we should embrace the fact that HTTP is a request/response protocol. You retrieve things from the request and use the response to, well, respond.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Why testing without starting a Servlet Container?&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
First, it&#39;s an unnecessary overhead. Besides, you wan&#39;t to test that your routing is working as expected, that your controller is rendering the correct template, etc. and I think that mocking the Servlet Container works well in this cases. It really depends on how you need to test your application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
If you have another question or think that an answer is not clear enough, ping me and I will add it or improve it. Thanks.&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/2053350087834952067/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2012/05/jogger-design-decisions-faq.html#comment-form' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/2053350087834952067'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/2053350087834952067'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2012/05/jogger-design-decisions-faq.html' title='Jogger design decisions FAQ'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-3789798379496353613</id><published>2012-05-12T17:26:00.001-07:00</published><updated>2012-05-14T08:43:52.776-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ajax"/><category scheme="http://www.blogger.com/atom/ns#" term="jogger"/><category scheme="http://www.blogger.com/atom/ns#" term="jquery"/><category scheme="http://www.blogger.com/atom/ns#" term="jsf"/><title type='text'>Java web development: back to basics</title><content type='html'>The first post that I wrote on this blog is titled &lt;a href=&quot;http://www.germanescobar.net/2009/10/ajax-jquery-google-web-toolkit-or.html&quot;&gt;AJAX: JQuery, Google Web Toolkit or RichFaces&lt;/a&gt;. There, I praise RichFaces for being built on top of JSF (Java Server Faces):&lt;br /&gt;
&lt;br /&gt;
&lt;blockquote class=&quot;tr_bq&quot;&gt;
&quot;If you haven&#39;t work with JSF, I really suggest you do as it is one of the most powerful, easy to learn Web technologies, very similar to swing with heavy use of components and events. It also has a really good support for managing the state in the server using plain Java objects (POJO’s)&quot;&lt;/blockquote&gt;
&lt;br /&gt;
What has happened since? Well, after working with &lt;a href=&quot;http://wicket.apache.org/&quot; target=&quot;_blank&quot;&gt;Wicket&lt;/a&gt; and &lt;a href=&quot;https://vaadin.com/home&quot; target=&quot;_blank&quot;&gt;Vaadin&lt;/a&gt; (which I still use in one of &lt;a href=&quot;https://github.com/germanescobar/mokai&quot; target=&quot;_blank&quot;&gt;my open source projects&lt;/a&gt;), &lt;b&gt;I have drifted away from component based web development&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
The reason is simple. It doesn&#39;t have to do with performance, number of components or the size of the community. It&#39;s just that &lt;b&gt;component based web frameworks couldn&#39;t keep the promise of isolating the programmer from client side development and the request/response nature of HTTP&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;A leaky abstraction&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Yes, I know. &lt;a href=&quot;http://www.joelonsoftware.com/articles/LeakyAbstractions.html&quot; target=&quot;_blank&quot;&gt;Every abstraction, to some degree, is leaky&lt;/a&gt;. However, the problem with this specific abstraction is that it leaks way too fast. You end up investing large amounts of time understanding how the framework works underneath and how to tweak it in order to achieve what you want. It&#39;s a real pain in the ass. The productivity that they promise in their &lt;i&gt;&quot;build an app in 10 minutes or less videos&quot;&lt;/i&gt; is dead in the eleventh minute or so.&lt;br /&gt;
&lt;br /&gt;
The other problem is that the technology underneath is moving too fast. HTML5 introduced a lot of new features such as web sockets, canvas and new data storage options. Web development is also moving towards stateless REST services and heavy clients. The future is not clear yet, though.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: x-large;&quot;&gt;Back to basics&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Lately, I have been working with &lt;a href=&quot;http://rubyonrails.org/&quot; target=&quot;_blank&quot;&gt;Ruby on Rails&lt;/a&gt; and &lt;a href=&quot;http://expressjs.com/&quot; target=&quot;_blank&quot;&gt;Express.js&lt;/a&gt; (&lt;a href=&quot;http://nodejs.org/&quot; target=&quot;_blank&quot;&gt;Node.js&lt;/a&gt;). I think that their success lies in the fact that they embraced the request/response nature of HTTP. However, I don&#39;t buy the &lt;i&gt;&quot;Ruby made programming fun again&quot;&lt;/i&gt; bullshit - a topic for another post -.&amp;nbsp;I still like Java. &lt;br /&gt;
&lt;br /&gt;
I also tried &lt;a href=&quot;http://www.playframework.org/&quot; target=&quot;_blank&quot;&gt;Play! Framework&lt;/a&gt; for a few weeks. It&#39;s an interesting option but I don&#39;t think that the solution is to copy exactly how Ruby on Rails works in Java/Scala. It&#39;s not really about productivity, it&#39;s about&amp;nbsp;maintainability.&lt;br /&gt;
&lt;br /&gt;
So, I&#39;m actually using a &lt;a href=&quot;https://github.com/germanescobar/jogger&quot; target=&quot;_blank&quot;&gt;super simple Java request/response based framework I made&lt;/a&gt;, HTML5, CSS3, Javascript and JQuery.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/3789798379496353613/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2012/05/java-web-development-back-to-basics.html#comment-form' title='20 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/3789798379496353613'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/3789798379496353613'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2012/05/java-web-development-back-to-basics.html' title='Java web development: back to basics'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>20</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-4536693291296188250</id><published>2010-09-26T21:07:00.000-07:00</published><updated>2010-10-04T15:42:13.814-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="architecture"/><title type='text'>Extension points (plug-in) design</title><content type='html'>&lt;p&gt;In a plug-in architecture, extension points allow other users to extend the functionality of your application, usually by implementing interfaces or extending abstract classes (known as the Service Provider Interface or SPI). Designing a good SPI is as important as designing a good API; it should be easy to learn and use, powerful enough to support multiple scenarios and should evolve without breaking existing implementations.&lt;/p&gt;  &lt;p&gt;Starting with a simple interface is simple, the problem is keeping it like that as new requirements arrive. For example, take a look at the following &lt;em&gt;MessageSender&lt;/em&gt; interface that allow other users to implement different ways of sending messages (e.g. SMS, Email, Twitter, etc.):&amp;#160; &lt;/p&gt;  &lt;pre class=&quot;brush: java&quot;&gt;public interface MessageSender {

  void send(Message message) throws Exception;

}&lt;/pre&gt;

&lt;p&gt;Nice interface; it’s simple and easy to implement. However, suppose that implementations could have an optional name, an optional description and methods to setup and destroy. After adding the required methods to the &lt;em&gt;MessageSender&lt;/em&gt; interface, it ends up like this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface MessageSender {

  // clean up resources
  void destroy() throws Exception;

  // return null or &amp;quot;&amp;quot; for empty description
  void getDescription() throws Exception;

  // return null or &amp;quot;&amp;quot; for empty name
  void getName() throws Exception;

  void send(Message message) throws Exception;

  // setup resources
  void setup() throws Exception;

}&lt;/pre&gt;

&lt;p&gt;Besides breaking existing implementations, this changes will make the interface much harder to implement. So, how can we keep the &lt;em&gt;MessageSender&lt;/em&gt; interface as simple as it was before and support the new requirements? Let’s take a look at two different approaches that will keep our SPI simple and extensible: creating optional interfaces and using annotations.&lt;/p&gt;

&lt;h3&gt;Optional interfaces&lt;/h3&gt;

&lt;p&gt;Instead of having all those methods in the &lt;em&gt;MessageSender&lt;/em&gt; interface, we are going to split them up in three interfaces: &lt;em&gt;MessageSender&lt;/em&gt;, &lt;em&gt;Nameable&lt;/em&gt; and &lt;em&gt;Configurable&lt;/em&gt;.&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface MessageSender {

  void send(Message message) throws Exception;

}&lt;/pre&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface Nameable {

  String getName();
  String getDescription();

}&lt;/pre&gt;

&lt;pre class=&quot;brush: java&quot;&gt;public interface Configurable {

  void setup() throws Exception;
  void destroy() throws Exception;

}&lt;/pre&gt;

&lt;p&gt;Now, we’ve cleaned up the &lt;em&gt;MessageSender&lt;/em&gt; interface. Users can implement &lt;em&gt;Nameable&lt;/em&gt; and/or &lt;em&gt;Configurable&lt;/em&gt; if they need to (they are optional). You’ll have to check at runtime if the optional interfaces are implemented and call the corresponding methods where applicable. For example, the following helper method will call the setup method if the MessageSender implementation implements Configurable:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;...
  public static void setup(MessageSender ms) throws Exception {
  
    // check if ms implements Configurable
    if (Configurable.isInstance(ms)) {

      // cast to Configurable and call setup method
      Configurable configurable = (Configurable) ms;
      configurable.setup();
    }
  }
...&lt;/pre&gt;

&lt;h3&gt;Annotations&lt;/h3&gt;

&lt;p&gt;Another option, besides splitting into multiple interfaces, is to create annotations; for our example, we will need four: @Name, @Description, @SetUp and @Destroy. Implementations can place these annotations as needed. For example, a &lt;em&gt;MessageSender&lt;/em&gt; implementation (e.g. SmsMessageSender) with a name “SMS Message Sender” that needs to be destroyed at the end will look like this:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;@Name(“SMS Message Sender”)
public void SmsMessageSender implements MessageSender {

  public void sendMessage(Message message) throws Exception {
    // send the message (connect if not connected)
  }

  @Destroy
  public void destroy() throws Exception {
    // disconnect from the SMSC
  }
}&lt;/pre&gt;

&lt;p&gt;As you can see, we have placed the @Name annotation above the class declaration and the @Destroy annotation in the method that will release the resources. Again, we are going to need some helper methods to check if the implementation has the annotations and call the corresponding methods. For example, the following code will check if the @Destroy method exists and will call it accordingly:&lt;/p&gt;

&lt;pre class=&quot;brush: java&quot;&gt;...
  public static void destroy(MessageSender ms) throws Exception {
		
    Method destroyMethod = locateDestroyMethod(ms);
    if (destroyMethod != null) {
      destroyMethod.invoke(ms);
    }
  }
	
  private static Method locateDestroyMethod(MessageSender ms) {
    Method[] methods = ms.getClass().getMethods();
    for (Method method : methods) {
      // check if the @Destroy annotation is present
      if (method.isAnnotationPresent(Destroy.class)) {
        return method;
      }
    }
		
    // no method has the @Destroy annotation
    return null;
  }
...&lt;/pre&gt;

&lt;p&gt;Annotations gives us more flexibility than optional interfaces as users will only have to add the required annotations. However, both options will make your interfaces simpler, so it’s up to you.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;Regardless of the approach you choose, keeping the interfaces (extension points) as clean as possible will allow you to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Lower the learning curve of the interfaces. Users can now focus on the core methods that need to be implemented in order to add new functionality. &lt;/li&gt;

  &lt;li&gt;Make your documentation simpler, especially for the 101 examples. Then, you can create more advanced examples that include more complex scenarios. &lt;/li&gt;

  &lt;li&gt;Evolve the interfaces without breaking existing implementations. &lt;/li&gt;
&lt;/ul&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/4536693291296188250/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/09/extension-points-plug-in-design.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/4536693291296188250'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/4536693291296188250'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/09/extension-points-plug-in-design.html' title='Extension points (plug-in) design'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-7010891446321329129</id><published>2010-09-20T12:15:00.001-07:00</published><updated>2010-09-20T12:34:05.110-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="architecture"/><category scheme="http://www.blogger.com/atom/ns#" term="mokai"/><title type='text'>Mokai: Architecture of a Messaging Gateway</title><content type='html'>&lt;p&gt;Software architecture is all about simplicity. In this post, I’ll show you the process of building the architecture of &lt;strong&gt;Mokai&lt;/strong&gt;, an open source Java Messaging Gateway capable of receiving and routing messages through a variety of mechanisms and protocols including HTTP, Mail, SMPP and JMS (Java Message Service), among others.&lt;/p&gt;  &lt;h3&gt;The black box&lt;/h3&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/black-box.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;Applications send and receive messages to and from external services such as an SMSC, a SMTP server, a JMS queue, etc. In the picture, we can identify the first three challenges of the gateway:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Receiving messages from applications using any protocol. &lt;/li&gt;    &lt;li&gt;Sending messages to external services using any protocol. &lt;/li&gt;    &lt;li&gt;Routing messages internally.&lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Normalizing messages&lt;/h3&gt;  &lt;p&gt;Let’s start with the last point. How do we route messages internally? Well, with so many protocols for receiving and sending messages, we’ll need a Message class we can manipulate inside &lt;strong&gt;Mokai&lt;/strong&gt;. It will contain some basic information, a body and a map of properties. This way, we can encapsulate any type of information we want inside the message (in the body or properties).&lt;/p&gt;  &lt;p&gt;When &lt;strong&gt;Mokai&lt;/strong&gt; receives a message, it will have to be normalized (i.e. encapsulated in a Message object) so it can be routed through the gateway. Once we are ready to send the message to an external service, it will have to be de-normalized (i.e. converted to a protocol that the external service can understand). Easy, right?&lt;/p&gt;  &lt;h3&gt;Receivers and Processors&lt;/h3&gt;  &lt;p&gt;The other two challenges we have described above involve extensibility. Anyone should be able to create new protocols for receiving messages or routing them outside the gateway. When creating extension points for your application, make them as simple as you can. In this case, we will introduce two interfaces: Receiver and Processor. Users will have to implement these interfaces to introduce new protocols for receiving or sending messages.&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/receivers-processors.png&quot; /&gt;&amp;#160; &lt;/p&gt;  &lt;p&gt;The Processor interface is really straightforward. Nothing strange in there. It just exposes two methods; one for checking if the processor supports a Message and other to process it (de-normalizing it to the desire protocol).&lt;/p&gt;  &lt;p&gt;The Receiver interface is even simpler; it exposes no methods, but it uses an instance of a MessageProducer to route the received messages inside &lt;strong&gt;Mokai&lt;/strong&gt;. The MessageProducer will be injected automatically to the Receiver at runtime.&lt;/p&gt;  &lt;h3&gt;Routing messages&lt;/h3&gt;  &lt;p&gt;When &lt;strong&gt;Mokai&lt;/strong&gt; receives a message from an application, it will have to decide which processor will handle it. To achieve this, each processor will have a collection of acceptors attached. Acceptors are an extension point of the application, so we introduce the Acceptor interface. &lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/acceptor.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;The Acceptor interface exposes only one method that returns true if the acceptor accepts the message or false if it rejects it. When a message is received, a router will query each group of acceptors, based on a priority, to select the processor that will process the message. &lt;/p&gt;  &lt;p&gt;So far, our architecture looks like this:&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/routing-engine-partial.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;We have introduced a new element in the diagram: a router; it’s task is to query all acceptors and processors to see who will handle the message.&lt;/p&gt;  &lt;h3&gt;Executing actions on messages&lt;/h3&gt;  &lt;p&gt;It is possible that we might want to execute actions on a message such as validate it, transform it or re-route it to a different location. For this cases, we introduce a new extension point, the Action interface.&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/action.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;The Action interface exposes only one method to execute the action on the message. There are three places where we can execute actions on a message:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;After a message is received (post-receiving actions). &lt;/li&gt;    &lt;li&gt;Before the message is processed (pre-processing actions). &lt;/li&gt;    &lt;li&gt;After the message is processed (post-processing actions). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now, with the introduction of actions, the complete architecture of &lt;strong&gt;Mokai&lt;/strong&gt; looks like this:&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/routing-engine.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;We have encapsulated the receiver in a Receiver Service and the processor in a Processor Service. A Processor Service also has a collection of post-receiving actions not shown in the diagram (processors can act as receivers too). We have also introduced two queues to store the messages until they are processed.&lt;/p&gt;  &lt;h3&gt;The class diagram&lt;/h3&gt;  &lt;p&gt;Now that we’ve seen the architecture of &lt;strong&gt;Mokai&lt;/strong&gt;, let’s see the final class diagram that models the architecture.&lt;/p&gt;  &lt;p&gt;&lt;img style=&quot;display: block; float: none; margin-left: auto; margin-right: auto&quot; src=&quot;http://mokai.googlecode.com/svn/wiki/images/api-model.png&quot; /&gt; &lt;/p&gt;  &lt;p&gt;&lt;/p&gt;  &lt;p&gt;In this diagram we can see all the elements described in the architecture and their relationships. &lt;/p&gt;  &lt;h3&gt;Wrapping up&lt;/h3&gt;  &lt;p&gt;As you can see, &lt;strong&gt;Mokai’s&lt;/strong&gt; architecture is simple, elegant and powerful. It provides all the elements we need to extend the platform to our will, keeping extension points simple and manageable. &lt;/p&gt;  &lt;p&gt;In the first release of &lt;strong&gt;Mokai&lt;/strong&gt;, there are also additional services such as message persistence, a plugin mechanism, an administration console and a configuration module, among others. You can check the &lt;a href=&quot;http://code.google.com/p/mokai/&quot;&gt;project homepage&lt;/a&gt; for more information. &lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/7010891446321329129/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/09/mokai-architecture-of-messaging-gateway.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/7010891446321329129'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/7010891446321329129'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/09/mokai-architecture-of-messaging-gateway.html' title='Mokai: Architecture of a Messaging Gateway'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-4091604140915371441</id><published>2010-04-09T05:42:00.000-07:00</published><updated>2010-04-09T05:59:39.691-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="cdi"/><category scheme="http://www.blogger.com/atom/ns#" term="ejb"/><category scheme="http://www.blogger.com/atom/ns#" term="jee"/><category scheme="http://www.blogger.com/atom/ns#" term="jsf"/><title type='text'>4 areas of possible confusion in JEE 6</title><content type='html'>&lt;p&gt;The JEE specification is released and maintained through the Java Community Process, which defines the different API’s that will be included in each release, and how they relate to each other. Due to the technical and political factors involved in the process, besides the time constraint, is no surprise that some areas of the specification may be confusing to new developers, especially with the rising number of annotations introduced by each API.&lt;/p&gt;  &lt;p&gt;In this post, I will try to explain four areas where developers might find themselves confused when working with JEE 6.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;1. Managed Beans and EL access&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The following two annotations from the JEE 6 API are both used to access a bean from the Expression Language (i.e. using the #{} notation):&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;@javax.faces.bean.&lt;strong&gt;ManagedBean&lt;/strong&gt; – Defined in the JSF 2.0 Managed Bean Annotations specification (JSR-314), it provides an alternative to the declaration of managed beans in the faces-config.xml descriptor file. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.inject.&lt;strong&gt;Named&lt;/strong&gt; – Defined in the Dependency Injection (JSR-330) specification, is one of the built-in qualifier types of CDI (JSR-299) used to provide a name to a bean, making it accessible through EL. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So, which one to use? Always use the &lt;strong&gt;@Named&lt;/strong&gt; annotation, unless you are working in a JSF 2.0 environment without CDI (a very unlikely scenario). There is just no reason to use JSF Managed Beans if CDI is present. You can check &lt;a href=&quot;http://weblogs.java.net/blog/cayhorstmann/archive/2009/12/23/javaxfacesbeanmanagedbean-dead-arrival&quot; target=&quot;_blank&quot;&gt;this article&lt;/a&gt; for more information.&lt;/p&gt;  &lt;p&gt;Furthermore, there is another &lt;strong&gt;@ManagedBean&lt;/strong&gt; annotation you might also get confused with:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;@javax.annotation.&lt;strong&gt;ManagedBean&lt;/strong&gt; – Defined by the Commons Annotations specification (JSR-250), it is used to declare a managed bean as specified in the Managed Beans specification (JSR-316). &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Most likely, you will never need to use this annotation. Let’s look why.&lt;/p&gt;  &lt;p&gt;First, don’t confuse Managed Beans with JSF Managed Beans, they are different things. The Managed Beans specification, a subset of the JSR-316, is an effort to provide services like dependency injection, lifecycle callbacks and interceptors to POJO’s (Plain Old Java Objects), which is really cool! So, why not to use it?&lt;/p&gt;  &lt;p&gt;CDI treats all POJO’s as Managed Beans! There is no need to explicitly annotate the POJO with @javax.annotation.&lt;strong&gt;ManagedBean&lt;/strong&gt;. Nothing stops you from doing it though.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;2. Duplicated @…Scoped annotations &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;The following annotations are duplicated in the JEE 6 API:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;@javax.faces.bean.&lt;strong&gt;RequestScoped&lt;/strong&gt; and @javax.enterprise.context.&lt;strong&gt;RequestScoped&lt;/strong&gt;. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.faces.bean.&lt;strong&gt;SessionScoped&lt;/strong&gt; and @javax.enterprise.context.&lt;strong&gt;SessionScoped&lt;/strong&gt;. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.faces.bean.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; and @javax.enterprise.context.&lt;strong&gt;ApplicationScoped&lt;/strong&gt;. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The @javax.faces.bean… annotations are defined in the JSF Managed Beans specification (JSR-314) and the @javax.enterprise.context… annotations are defined in the CDI specification (JSR-299).&amp;#160; &lt;/p&gt;  &lt;p&gt;So, which ones to use? Always use the CDI annotations, unless you are working in a JSF 2.0 environment without CDI (a very unlikely scenario). As discussed above, there is no reason to use JSF Managed Beans if CDI is present.&lt;/p&gt;  &lt;p&gt;One scope that is missing in CDI is the &lt;strong&gt;@ViewScoped&lt;/strong&gt; of JSF. However, the problem is solved by creating a portable extension which will be included in the &lt;a href=&quot;http://www.seamframework.org/Seam3/FacesModule&quot; target=&quot;_blank&quot;&gt;Seam 3 Faces Module&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;3. Defining a Singleton&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;There are four annotations that provide very similar functionality: &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;@javax.ejb.&lt;strong&gt;Singleton – &lt;/strong&gt;A new type of EJB from the JSR-318 specification, it is used to maintain a single shared instance; it’s thread safe and transactional. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.inject.&lt;strong&gt;Singleton – &lt;/strong&gt;From the Dependency Injection specification (JSR-330), marks a type the injector will only instantiate once. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.enterprise.inject.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; – One of the built-in scopes from the Contexts and Dependency Injection specification (JSR-299), specifies that a bean is application scoped. &lt;/li&gt; &lt;/ul&gt;  &lt;ul&gt;   &lt;li&gt;@javax.faces.bean.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; – Defined in the JSF 2.0 (JSR-314) Managed Beans specification, specifies that a JSF managed bean is application scoped. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;They all guarantee a single instance of the class. But, which one to use?&lt;/p&gt;  &lt;p&gt;We have already discussed the duplicated &lt;strong&gt;@ApplicationScoped&lt;/strong&gt; annotations above, so we will just dismiss @javax.faces.bean.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; to move on. That leaves us with just 3 options.&lt;/p&gt;  &lt;p&gt;@javax.ejb.&lt;strong&gt;Singleton&lt;/strong&gt; is the only one that will give you out-of-the-box “enterprise” services such as concurrency and transaction management. So, if you need these features, this is the annotation to use. You can optionally add the @javax.enterprise.inject.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; annotation but you will not feel the difference, although, CDI will treat it differently. You can check &lt;a href=&quot;http://seamframework.org/Community/SingletonEJBs&quot; target=&quot;_blank&quot;&gt;this forum thread&lt;/a&gt; for more information.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; even though it is possible to use @javax.enterprise.inject.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; with a Stateful Session Bean, I can’t find any good reason to use it given that EJB 3.1 has introduced the Singleton Beans.&lt;/p&gt;  &lt;p&gt;If you want to use POJO’s (called Managed Beans in the JEE world), instead of EJB’s, you can also annotate them with @javax.enterprise.inject.&lt;strong&gt;ApplicationScoped&lt;/strong&gt; to guarantee that the class is instantiated only once. Be aware that you will lose all of the services provided by EJB’s such as concurrency and transaction management.&lt;/p&gt;  &lt;p&gt;I would not suggest using @javax.inject.&lt;strong&gt;Singleton&lt;/strong&gt; unless you are working in a JS2E environment without CDI support. You can check the &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/scopescontexts.html#d0e1921&quot; target=&quot;_blank&quot;&gt;Weld documentation&lt;/a&gt; and &lt;a href=&quot;http://seamframework.org/Community/SingletonPseudoScope&quot; target=&quot;_blank&quot;&gt;this forum thread&lt;/a&gt; for more information about how this annotation is handled in CDI.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; none of the annotations discussed above will guarantee a shared single instance in a clustered environment. Usually, you will have one singleton instance per JVM.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;4. @Inject or @EJB &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;They are both used for injection. &lt;strong&gt;@Inject&lt;/strong&gt; is from the Dependency Injection specification (JSR-330) and &lt;strong&gt;@EJB&lt;/strong&gt; from the EJB specification (JSR-318).&lt;/p&gt;  &lt;p&gt;So, which one to use?&lt;/p&gt;  &lt;p&gt;In most of the cases you will use &lt;strong&gt;@Inject&lt;/strong&gt; over &lt;strong&gt;@EJB&lt;/strong&gt; unless you are working on an environment with EJB’s but no CDI (very unlikely since JEE 6), or if you need to define an EJB resource. You can check the &lt;a href=&quot;http://seamframework.org/Community/InjectingWithEJBOrInject&quot; target=&quot;_blank&quot;&gt;this forum thread&lt;/a&gt; for more information.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;If you need to access a bean through EL (i.e. from a JSF page), annotate the bean with @Named. &lt;/li&gt;    &lt;li&gt;Usually, you will never need none of the &lt;strong&gt;@ManagedBean&lt;/strong&gt; annotations. &lt;/li&gt;    &lt;li&gt;Always use the @…Scoped annotations from the javax.enterprise.context package (CDI). &lt;/li&gt;    &lt;li&gt;To define a singleton, use the &lt;strong&gt;@ApplicationScoped&lt;/strong&gt; annotation. If you need the EJB services such as concurrency and transaction, add the @javax.ejb.&lt;strong&gt;Singleton&lt;/strong&gt; annotation. &lt;/li&gt;    &lt;li&gt;Always use &lt;strong&gt;@Inject&lt;/strong&gt; instead of &lt;strong&gt;@EJB&lt;/strong&gt;, unless you really have a motive to do so. &lt;/li&gt; &lt;/ol&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/4091604140915371441/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/04/4-areas-of-possible-confusion-in-jee6.html#comment-form' title='27 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/4091604140915371441'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/4091604140915371441'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/04/4-areas-of-possible-confusion-in-jee6.html' title='4 areas of possible confusion in JEE 6'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>27</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-5022867285872539218</id><published>2010-03-28T12:07:00.001-07:00</published><updated>2010-03-28T15:19:10.519-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="cdi"/><category scheme="http://www.blogger.com/atom/ns#" term="contexts"/><category scheme="http://www.blogger.com/atom/ns#" term="ejb"/><category scheme="http://www.blogger.com/atom/ns#" term="jee"/><title type='text'>What’s so wrong with EJB’s?</title><content type='html'>&lt;p&gt;It’s not that they are heavy. It’s not that they are difficult to write. So, what’s wrong with EJB’s?&lt;/p&gt;  &lt;p&gt;EJB’s can be either &lt;em&gt;Stateless&lt;/em&gt;, &lt;em&gt;Stateful&lt;/em&gt; or &lt;em&gt;Singleton&lt;/em&gt;. However, when you are working on a web environment for example, these lifecycles will not suffice. &lt;em&gt;Request&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt; and &lt;em&gt;application&lt;/em&gt; lifecycles would be much better suited in that case. Another example is a business process application, where you could have a &lt;em&gt;task&lt;/em&gt; or a &lt;em&gt;process&lt;/em&gt; lifecycle; again, EJB’s will not match those lifecycles. This is what I call the &lt;strong&gt;Lifecycle Mismatch&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;Through the years, EJB’s have become more POJO-like, through the use of annotations and without requirements such as XML descriptors and Java interfaces. However, it doesn’t matter how simple they get, until they don’t remove the lifecycle restriction, you will end up creating additional layers in your application and different component models to adapt your required lifecycles.&lt;/p&gt;  &lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; The lifecycles I’m referring are also known as contexts or scopes in other frameworks/specifications.&lt;/p&gt;  &lt;p&gt;For example, take a look at JSF. They introduced the &lt;em&gt;JSF Managed Beans&lt;/em&gt; to handle this problem. JSF Managed Beans can be bound to &lt;em&gt;request&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt; or &lt;em&gt;application&lt;/em&gt; contexts. From there, you are on your own on how you connect them to the EJB’s different lifecycle.&lt;/p&gt;  &lt;p&gt;CDI (Contexts and Dependency Injection) is a specification, part of the JEE stack, that is trying to fill that gap. It provides dependency injection and lifecycle management to POJO’s and EJB’s. But providing lifecycle management to EJB’s doesn’t feels right, because they already provide their own. CDI does its best effort to accommodate this mismatch.&lt;/p&gt;  &lt;p&gt;On the other hand, CDI could provide to POJO’s, all the services EJB’s currently have, through extensions. So, do we really need EJB’s? Well, not really! You can check my post &lt;a href=&quot;http://www.germanescobar.net/2009/12/ejbs-time-to-let-them-go.html&quot; target=&quot;_blank&quot;&gt;EJB’s - Time to let them go?&lt;/a&gt; for more information.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;EJB’s have become light weighted and easy to write. But the lifecycle mismatch is still there. POJO’s, on the other hand, don’t have this restriction and, with CDI, they could have all the services EJB’s currently provide.&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/5022867285872539218/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/03/whats-so-wrong-with-ejbs.html#comment-form' title='34 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/5022867285872539218'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/5022867285872539218'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/03/whats-so-wrong-with-ejbs.html' title='What’s so wrong with EJB’s?'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>34</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-6003460243877134056</id><published>2010-03-04T04:44:00.000-08:00</published><updated>2010-03-05T02:22:38.315-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="cdi"/><category scheme="http://www.blogger.com/atom/ns#" term="dependency injection"/><category scheme="http://www.blogger.com/atom/ns#" term="google guice"/><category scheme="http://www.blogger.com/atom/ns#" term="seam"/><title type='text'>Understanding and Comparing Dependency Injection Frameworks</title><content type='html'>&lt;p&gt;If you have used a modern Dependency Injection (DI) framework like JBoss Seam, Google Guice or CDI (Contexts and Dependency Injection), you might already be familiar with the following line of code:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Inject MyBean myBean;
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;But, to really understand how a DI framework works and what makes one different from the other, we are going to build one from scratch. Let’s call it &lt;strong&gt;OurDI&lt;/strong&gt;. Then, we will compare it with some of the most popular DI frameworks out there.&lt;/p&gt;&lt;p&gt;So, let’s start by writing a Quick Start Guide for &lt;strong&gt;OurDI&lt;/strong&gt; that shows how it works.&lt;/p&gt;&lt;h4&gt;Quick Start Guide&lt;/h4&gt;&lt;p&gt;As any other modern DI framework, &lt;strong&gt;OurDI &lt;/strong&gt;allows you to inject dependencies using annotations as in the following example:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public class UsesInjection {
  @Inject MyBean myBean;
  ... 
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;In order to configure &lt;strong&gt;OurDI&lt;/strong&gt;, all you need to do is to populate a class named &lt;em&gt;Injector&lt;/em&gt; with all the objects that can be injected at runtime; each object must be identified by a unique name. In the following example, we are going to configure the &lt;em&gt;Injector&lt;/em&gt; with two classes &lt;em&gt;MyBean&lt;/em&gt; and &lt;em&gt;AnotherBean&lt;/em&gt;, bound to the names “myBean” and “anotherBean” respectively:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public class Main {
  public final static void main(String[] args) {  
    Injector injector = Injector.instance();  
    injector.bind(“myBean”, new MyBean());  
    injector.bind(“anotherBean”, new AnotherBean(); 
  }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;So, when a method of the &lt;em&gt;UsesInjection&lt;/em&gt; class (defined above) is called, a search will be done for the name of the attribute “myBean” on the &lt;em&gt;Injector&lt;/em&gt; instance, and the value associated with that name will be injected.&lt;/p&gt;&lt;h4&gt;Building the framework&lt;/h4&gt;&lt;p&gt;Well, that was a quick Quick Start Guide! Now let&#39;s see how &lt;strong&gt;OurDI&lt;/strong&gt; works underneath.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;OurDI&lt;/strong&gt; is composed of two classes and an annotation: &lt;/p&gt;&lt;ul&gt;&lt;li&gt;A singleton class named &lt;em&gt;Injector&lt;/em&gt;, that will store the bound objects. &lt;/li&gt;
&lt;li&gt;A class named &lt;em&gt;InjectorInterceptor&lt;/em&gt;, which will use AOP (Aspect Oriented Programming) to inject the dependencies at runtime. &lt;/li&gt;
&lt;li&gt;The @Inject annotation. &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Let’s take a look at the &lt;em&gt;Injector&lt;/em&gt; class:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public class Injector {

  private Map&amp;lt;String,Object&amp;gt; bindings = new HashMap&amp;lt;String,Object&amp;gt;();

  // static instance, private constructor and static instance() method 
 
  public void bind(String name, Object value) {
    bindings.put(name, value);
  }
 
  public Object get(String name) {
    return bindings.get(name);
  }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;As you can see, &lt;em&gt;Injector&lt;/em&gt; is singleton class backed by a &lt;em&gt;Map&lt;/em&gt;&amp;lt;String,Object&amp;gt; that binds each object to a unique name. Now, let’s see how injection is done when an @Inject annotation is found.&lt;/p&gt;&lt;p&gt;We can use any AOP library to intercept method calls and look for all the dependencies that need to be injected on the target object. In this case, we are going to use AspectJ: &lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Aspect
public class InjectorInterceptor {

  @Around(&quot;call(* *.*(..)) &amp;&amp; !this(InjectorInterceptor)&quot;)
  public Object aroundInvoke(ProceedingJoinPoint joinPoint) throws Throwable {
  
    // this should return the target class
    Class&lt;?&gt; clazz = joinPoint.getTarget().getClass();
  
    // inject fields annotated with @Inject
    for (Field field : clazz.getDeclaredFields()) {
      if (field.isAnnotationPresent(Inject.class)) {
        doInjection(joinPoint.getTarget(), field);
      }
    }
  
    return joinPoint.proceed();
  }
 
  private void doInjection(Object target, Field field) throws IllegalAccessException {
    String name = field.getName();
    field.setAccessible(true);
    field.set(target, Injector.instance().get(name));
  }
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Before each method call, the aroundInvoke method will be called. It will look at all the fields of the target object to see if it finds any @Inject annotation. For each of the annotated fields, it uses the name of the field to find the corresponding object in the &lt;em&gt;Injector&lt;/em&gt; class.&lt;/p&gt;&lt;p&gt;Finally, here is our @Inject annotation:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Target(value={FIELD})
@Retention(value=RUNTIME)
@Documented
public @interface Inject {}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;That’s all! you can check the full source &lt;a href=&quot;http://gist.github.com/320581&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Now, let’s check some aspects of our solution and compare them with other popular frameworks out there.&lt;/p&gt;&lt;h4&gt;Configuration&lt;/h4&gt;&lt;p&gt;In &lt;strong&gt;OurDI&lt;/strong&gt;, we have to manually populate the &lt;em&gt;Injector&lt;/em&gt; instance with the objects that are going to be injected. This is similar to Google Guice. However, in Guice, there is no need to use a name and, instead of binding objects, we bind classes:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;Injector injector = Guice.createInjector(new Module() {
  public void configure(Binder binder) {
    binder.bind(Notifier.class).to(SendSMS.class);
    binder.bind(Database.class).to(MySqlDatabase.class);
  }
});
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;JBoss Seam and CDI take a different approach. Instead of binding each class manually, they scan all your classes on bootstrap to populate the “injector”. In JBoss Seam, you will need to register the Seam Servlet Listener on your web.xml; for CDI, no configuration is required (besides the beans.xml descriptor), the application server will do the scanning automatically (one of the benefits of being part of the JEE stack).&lt;/p&gt;&lt;p&gt;Scanning all classes and choosing the ones suitable for injection can take a while. So, Google Guice (and &lt;strong&gt;OurDI&lt;/strong&gt;) will be faster starting up. However, with JBoss Seam or CDI, you won’t have to worry about binding each class/object manually.&lt;/p&gt;&lt;h4&gt;Type safety&lt;/h4&gt;&lt;p&gt;As you might already have noticed, &lt;strong&gt;OurDI&lt;/strong&gt; will break at runtime with a ClassCastException if the injected object is not of the expected type. The same happens with JBoss Seam, which also uses a name-based approach (components are named using the @Name annotation). &lt;/p&gt;&lt;p&gt;On the other hand, Google Guice and CDI are type safe, meaning that the injected objects are not identified by a name, but by their type.&lt;/p&gt;&lt;h4&gt;Overriding/changing implementations&lt;/h4&gt;&lt;p&gt;In &lt;strong&gt;OurDI&lt;/strong&gt;, to override/change the implementation of an injected class, all we need to do is change the object bound to the &lt;em&gt;Injector&lt;/em&gt; class. This is very similar to Google Guice as shown before.&lt;/p&gt;&lt;p&gt;For JBoss Seam and CDI, we need to provide more information about the classes we want to use. I won’t dive into the details but you can check how this works in the &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/injection.html&quot; target=&quot;_blank&quot;&gt;Weld documentation&lt;/a&gt; for CDI and in &lt;a href=&quot;http://www.germanescobar.net/2010/02/overriding-component-in-jboss-seam.html&quot; target=&quot;_blank&quot;&gt;this post&lt;/a&gt; for JBoss Seam.&lt;/p&gt;&lt;h4&gt;Constructor and method injection&lt;/h4&gt;&lt;p&gt;Besides field injection, some DI frameworks provide constructor and method injection to initialize your objects. &lt;strong&gt;OurDI&lt;/strong&gt; doesn’t support any of these, neither JBoss Seam. Both &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/injection.html#d0e1107&quot; target=&quot;_blank&quot;&gt;CDI&lt;/a&gt; and &lt;a href=&quot;http://code.google.com/docreader/#p=google-guice&amp;amp;s=google-guice&amp;amp;t=Injections&quot; target=&quot;_blank&quot;&gt;Google Guice&lt;/a&gt; support them.&lt;/p&gt;&lt;h4&gt;Injection of external resources&lt;/h4&gt;&lt;p&gt;Sometimes, you need to inject things you don’t have control of. For example, DataSources, 3rd party libraries, JNDI resources, etc. &lt;strong&gt;OurDI&lt;/strong&gt; doesn’t support this. JBoss Seam supports it with &lt;a href=&quot;http://docs.jboss.org/seam/2.2.0.GA/reference/en-US/html/concepts.html#d0e4345&quot; target=&quot;_blank&quot;&gt;factories and manager components&lt;/a&gt;, Google Guice supports it with &lt;a href=&quot;http://code.google.com/docreader/#p=google-guice&amp;amp;s=google-guice&amp;amp;t=ProvidesMethods&quot; target=&quot;_blank&quot;&gt;provider methods&lt;/a&gt; and CDI supports it with &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/beanscdi.html#d0e942&quot; target=&quot;_blank&quot;&gt;producer methods and fields&lt;/a&gt;.&lt;/p&gt;&lt;h4&gt;Scopes&lt;/h4&gt;&lt;p&gt;Scopes, also known as Contexts, are a fundamental part of development. They allow you to define different lifecycles for each object (i.e. request, session, or application). &lt;strong&gt;OurDI&lt;/strong&gt; doesn’t support scopes. However, Google Guice, JBoss Seam and CDI, all support scopes in one way or another. You can read more about scopes and their importance on &lt;a href=&quot;http://www.germanescobar.net/2009/11/understanding-seam-contexts-part-1.html&quot; target=&quot;_blank&quot;&gt;this post&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;You can also check the documentation of scopes for each framework/specification: &lt;a href=&quot;http://code.google.com/docreader/#p=google-guice&amp;amp;s=google-guice&amp;amp;t=Scopes&quot; target=&quot;_blank&quot;&gt;Google Guice&lt;/a&gt;, &lt;a href=&quot;http://docs.jboss.org/seam/2.2.0.GA/reference/en-US/html/concepts.html&quot; target=&quot;_blank&quot;&gt;JBoss Seam&lt;/a&gt; and &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/scopescontexts.html&quot; target=&quot;_blank&quot;&gt;CDI&lt;/a&gt;.&lt;/p&gt;&lt;h4&gt;Static vs. Dynamic Injection&lt;/h4&gt;&lt;p&gt;In &lt;strong&gt;OurDI&lt;/strong&gt;, every time a method is called, it will scan the object to find dependencies that need to be injected. This is called Dynamic Injection and is how JBoss Seam works. The advantage of dynamic injection is that if a dependent object is changed, the new object will be injected in the next method call, so, you’ll always end up with the “correct” instance.&lt;/p&gt;&lt;p&gt;Google Guice and CDI uses Static Injection, which means that injection will only occur once after the object is created. The problem here, as stated above, is that if a dependent object is changed, you will still have the reference to the old object. CDI solves this problem by using proxies that will always point to the correct instance. So, even though it uses static injection (the field is injected only once), it works like dynamic injection. &lt;/p&gt;&lt;h4&gt;Lazy Loading of objects&lt;/h4&gt;&lt;p&gt;In &lt;strong&gt;OurDI&lt;/strong&gt;, you will need to instantiate all the classes that need to be injected on startup. This is definitely not a good idea as you are loading things in memory that you are not still using. Google Guice, JBoss Seam and CDI all use a lazy loading approach where the objects will be loaded only when needed, which is a good thing.&lt;/p&gt;&lt;h4&gt;Aspect Oriented Programming&lt;/h4&gt;&lt;p&gt;Most DI frameworks provide some type of method interceptor mechanism that simplifies AOP development, usually with annotations. This is another feature that &lt;strong&gt;OurDI&lt;/strong&gt; lacks! However, &lt;a href=&quot;http://code.google.com/docreader/#p=google-guice&amp;amp;s=google-guice&amp;amp;t=AOP&quot; target=&quot;_blank&quot;&gt;Google Guice&lt;/a&gt;, &lt;a href=&quot;http://docs.jboss.org/seam/2.2.0.GA/reference/en-US/html/events.html#d0e5556&quot; target=&quot;_blank&quot;&gt;JBoss Seam&lt;/a&gt; and &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/interceptors.html&quot; target=&quot;_blank&quot;&gt;CDI&lt;/a&gt;, all support this feature with a very similar approach.&lt;/p&gt;&lt;h4&gt;Integration&lt;/h4&gt;&lt;p&gt;Integration with other environments is really simple with &lt;strong&gt;OurDI&lt;/strong&gt; and Google Guice. You just need to configure the &lt;em&gt;Injector&lt;/em&gt; on startup and that’s it. JBoss Seam is a complete development platform that integrates multiple technologies and it would be almost impossible to integrate it on a different environment different from JEE. CDI is part of the JEE 6 stack, however, implementations like Weld can run on different environments with the appropriate hookups.&amp;#160; &lt;/p&gt;&lt;h4&gt;Conclusion&lt;/h4&gt;&lt;p&gt;Ok, let’s face it. &lt;strong&gt;Our&lt;/strong&gt; own &lt;strong&gt;DI&lt;/strong&gt; framework sucks!: &lt;/p&gt;&lt;ul&gt;&lt;li&gt;It doesn’t support constructor or method injection (or provide an alternate solution). &lt;/li&gt;
&lt;li&gt;It doesn’t support injection of external resources. &lt;/li&gt;
&lt;li&gt;It needs all classes to be instantiated on startup. &lt;/li&gt;
&lt;li&gt;It doesn’t support scopes.&amp;#160; &lt;/li&gt;
&lt;li&gt;It doesn’t provides a method interceptor mechanism.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;However, I hope &lt;strong&gt;OurDI&lt;/strong&gt; was useful enough to compare different DI frameworks. We only talked about Google Guice, JBoss Seam and CDI, but you can do the exercise with any other DI framework out there.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/6003460243877134056/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/03/understanding-and-comparing-dependency.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6003460243877134056'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6003460243877134056'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/03/understanding-and-comparing-dependency.html' title='Understanding and Comparing Dependency Injection Frameworks'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-6830229359572367301</id><published>2010-02-18T02:05:00.000-08:00</published><updated>2010-02-18T06:40:36.995-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="seam"/><title type='text'>Overriding a component in JBoss Seam</title><content type='html'>&lt;p&gt;A few days ago, I was asked to explain how to change/override/mock a component in JBoss Seam. So, here is it.&lt;/p&gt;&lt;p&gt;To override a component in Seam, all you need to do is to create a second component that satisfies the following conditions: &lt;/p&gt;&lt;ol&gt;&lt;li&gt;It must have the &lt;em&gt;same name&lt;/em&gt; as the component you are overriding. &lt;/li&gt;
&lt;li&gt;It must be of the same type than the component you are overriding. Or you will end up with a ClassCastException on injection. &lt;/li&gt;
&lt;li&gt;It must have a higher &lt;strong&gt;precedence &lt;/strong&gt;than the component you are overriding. &lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;The first two points need no further explanation. However, the third one raises the following questions: What is the &lt;strong&gt;precedence&lt;/strong&gt; of a component? How do I change it? &lt;/p&gt;&lt;p&gt;The precedence of a component is a numeric attribute all components have, which by default is 20. You can change the precedence of a component using the @Install annotation:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&quot;myBean&quot;)
@Install(precedence=40)
public class MyBean {
 ...
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;On startup, if Seam finds more than one component with the same name, it will choose the one with the higher &lt;strong&gt;precedence&lt;/strong&gt; value. If it finds two components with the same name and the same &lt;strong&gt;precedence&lt;/strong&gt;, an Exception is thrown.&lt;/p&gt;&lt;p&gt;Let’s take a look at an example. Suppose that you have an interface called &lt;em&gt;CodeGenerator&lt;/em&gt; with two implementations: &lt;em&gt;DefaultCodeGenerator&lt;/em&gt; and an alternate &lt;em&gt;MockCodeGenerator&lt;/em&gt;.&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public interface CodeGenerator {

 public String generateCode();
 
}
&lt;/pre&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&quot;codeGenerator&quot;)
public class DefaultCodeGenerator implements CodeGenerator {

 public String generateCode() {
  ...
 }
}
&lt;/pre&gt;&lt;em&gt;DefaultCodeGenerator.&lt;/em&gt; No @Install annotation; it will have a precedence of 20 (the default value).&lt;br /&gt;
&lt;pre class=&quot;brush: java&quot;&gt;@Name(&quot;codeGenerator&quot;)
@Install(precedence=Install.MOCK)
public class MockCodeGenerator implements CodeGenerator {
 
 public String generateCode() {
  ...
 }
}
&lt;/pre&gt;&lt;em&gt;MockCodeGenerator&lt;/em&gt;. Notice that it has the @Install annotation with a precedence of 40 (see the table below).&lt;br /&gt;
&lt;/p&gt;&lt;p&gt;Now, suppose both &lt;em&gt;DefaultCodeGenerator&lt;/em&gt; and &lt;em&gt;MockCodeGenerator&lt;/em&gt; are on the classpath and that we have the following injection point:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&quot;testCodeGenerator&quot;)
public class TestCodeGenerator {
 ...
 @In
 private CodeGenerator codeGenerator;
 ...
}
&lt;/pre&gt;&lt;p&gt;Which component will be injected? Seam will choose the one with the higher precedence. In this case: &lt;em&gt;MockCodeGenerator&lt;/em&gt;. So, a common usage is to have a separate JAR with the alternate implementation that can be included on the classpath only when needed (i.e. added to the WAR or EAR archive).&lt;/p&gt;&lt;p&gt;Seam defines some predefined precedence values:&lt;/p&gt;&lt;table cellspacing=&quot;0&quot; cellpadding=&quot;5&quot; width=&quot;600&quot; align=&quot;center&quot; border=&quot;0&quot;&gt;&lt;tbody&gt;
&lt;tr style=&quot;font-weight: bold; color: #ffffff; background-color: #000000&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Constant&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;Value&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;Description&lt;/td&gt;     &lt;/tr&gt;
&lt;tr style=&quot;background-color: #eaeaea&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Install.BUILT_IN&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;0&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;Built in Seam components have this precedence.&lt;/td&gt;     &lt;/tr&gt;
&lt;tr style=&quot;background-color: #eaeaea&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Install.FRAMEWORK&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;10&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;&amp;#160;&lt;/td&gt;     &lt;/tr&gt;
&lt;tr style=&quot;background-color: #eaeaea&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Install.APPLICATION&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;20&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;The default precedence&lt;/td&gt;     &lt;/tr&gt;
&lt;tr style=&quot;background-color: #eaeaea&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Install.DEPLOYMENT&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;30&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;&amp;#160;&lt;/td&gt;     &lt;/tr&gt;
&lt;tr style=&quot;background-color: #eaeaea&quot;&gt;       &lt;td valign=&quot;top&quot;&gt;Install.MOCK&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;40&lt;/td&gt;        &lt;td valign=&quot;top&quot;&gt;For mock objects used in testing&lt;/td&gt;     &lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; It is recommended to use one of this constants for the precedence. However, nothing stops you to set a different value.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Using components.xml&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Another way of overriding a component in Seam is to define the component in the components.xml descriptor file &lt;em&gt;instead of using the @Name annotation&lt;/em&gt;. XML-based configuration is discouraged by Seam but valid anyway. This way you can change the class directly in the XML without re-compiling. &lt;/p&gt;&lt;p&gt;What I usually do is to have a default implementation annotated with the @Name annotation which has the default &lt;strong&gt;precedence&lt;/strong&gt;. When I need to override it, I define a second component in the components.xml descriptor with a higher precedence (this way, I’m only using the XML file to install the alternate implementations). For example, instead of annotating the MockCodeGenerator with @Name and @Install, we could have added it to the components.xml:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;components&amp;gt;
 ...
 &amp;lt;component name=&amp;quot;codeGenerator&amp;quot; class=&amp;quot;org.test.MockCodeGenerator&amp;quot; precedence=&amp;quot;40&amp;quot; /&amp;gt;
 ...
&amp;lt;/components&amp;gt;
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Other options&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;The @Install annotation is much more powerful than what I’ve just shown you. It allows you to “install” a component only when certain conditions are satisfied. For example:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;When you are working on debug mode. &lt;/li&gt;
&lt;li&gt;When a class or group of classes are present on the classpath. &lt;/li&gt;
&lt;li&gt;When a component or group of components are present on the classpath. &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;When you are working on your development environment, you might want to mock some components to: simulate external systems you don’t have access to, simulate emails, sms, etc., disable some functionality, etc. For these cases, you can have some components annotated with @Install(debug=true) that override the default ones. They will be installed only when working on debug mode (this setting is configured in components.xml). &lt;/p&gt;&lt;p&gt;More advanced options allow you to install a component if some classes or other components are present on the classpath. You can do some complex stuff here but that is out of the scope of this post.&lt;/p&gt;&lt;p&gt;Finally, you can always rely on @Install(false) which won’t install the component by default. You will have to install it manually in the components.xml descriptor file. Al lot of built-in components of Seam are configured this way so you can install them only when needed.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Seam offers you a variety of ways in which you can override components, or, how Seam calls it, conditionally install components. It offers you so many options, it can sometimes get tricky. However, once understood, it is a very powerful feature.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/6830229359572367301/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/02/overriding-component-in-jboss-seam.html#comment-form' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6830229359572367301'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6830229359572367301'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/02/overriding-component-in-jboss-seam.html' title='Overriding a component in JBoss Seam'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-6820214222138140269</id><published>2010-01-28T18:37:00.000-08:00</published><updated>2010-01-28T21:22:09.943-08:00</updated><title type='text'>JMX Portable Extension for CDI</title><content type='html'>&lt;p&gt;CDI (Contexts and Dependency Injection) is a new standard that makes application development easier by providing type safety dependency injection, scope binding (request, session, application, etc.) and contextual lifecycle management of Java components. It also&amp;#160; exposes a powerful SPI (Service Provider Interface) to extend its functionality through portable extensions. &lt;/p&gt;  &lt;p&gt;JMX (Java Management Extensions) provides a consistent, well defined interface to monitor and manage your applications by exposing objects (MBeans) through an MBeanServer. Currently, there are two ways to expose an object as an MBean: you can either provide an interface of your class, in which case, you won’t be able to add textual descriptions for your exposed fields and methods; or you can implement javax.management.DynamicMBean, which is cumbersome and difficult to maintain. &lt;/p&gt;  &lt;table cellspacing=&quot;0&quot; cellpadding=&quot;5&quot; width=&quot;90%&quot; align=&quot;center&quot; border=&quot;1&quot;&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td style=&quot;background-color: #eaeaea&quot; valign=&quot;top&quot;&gt;JSR-255, the JMX specification 2.0, is an initiative that will make the writing of MBeans easier through annotations. However, by the time of this writing, the JSR is inactive as stated &lt;a href=&quot;http://weblogs.java.net/blog/2009/06/16/jsr-255-jmx-api-20-postponed&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;I’ve decided to write my first own portable extension that will allow you to expose any object automatically or manually through JMX by just adding some simple annotations. You can download the complete code from &lt;a href=&quot;http://jmx-annotations.googlecode.com&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;Let’s take a look at the following example:&lt;/p&gt;  &lt;p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;
@ApplicationScoped
@MBean(&quot;org.gescobar:type=VisitorCounter&quot;)
@Description(&quot;Counts the number of visits&quot;)
public class VisitorCounter {  
  
  @ManagedAttribute(readable=true,writable=true)  
  private int counter;  
  
  public void addVisitor() {    
    counter++;  
  }  

  @ManagedOperation(impact=Impact.ACTION)  
  public void resetCounter() {    
    counter = 0;  
  }  

  // getter and setters
}
&lt;/script&gt;&lt;/p&gt;  &lt;p&gt;When the bean is instantiated by CDI, a dynamic MBean is created and registered on an MBeanServer to expose the attributes and methods annotated with @ManagedAttribute and @ManagedOperation respectively. You can then use any JMX Agent Viewer to monitor and manage your code. &lt;/p&gt;  &lt;p&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgDzcsgnzQ_15H7bm97fSm24zwyRiioCiDzQCToljVEBuJITFiImcHk4lMH8xc9EVM-_X4cnsrwFudCRekctk-wJAIwYWrqEcRNVMW-PcRD41cKfrxAF1vgWZlGEz0KgBp31EtMv1Zt5nbJ/s1600-h/jmx-view%5B7%5D.jpg&quot;&gt;&lt;img title=&quot;jmx-view&quot; style=&quot;border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px&quot; height=&quot;116&quot; alt=&quot;jmx-view&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjj1Luv00q_j2YLLQqaJXfm3k2xBPbA5e3xchB1tYfVIAT607YG0LuKBawZOjMf7cEqJY-Hq6d9UXfmZyV6mPPPOyLMYUGDRs1-F5cZm-Ce7SdZsHDbO-dKSJ-jPZVmkfPnDtJxo8S1EOzR/?imgmax=800&quot; width=&quot;291&quot; border=&quot;0&quot; /&gt;&lt;/a&gt;&amp;#160; &lt;br /&gt;&lt;font size=&quot;1&quot;&gt;Figure 1. JBoss AS JMX Console. A view of an MBean.&lt;/font&gt; &lt;/p&gt;  &lt;p&gt;You don’t have to worry anymore about obtaining an MBeanServer, registering the MBean and unregistering it. This is all done automatically for you. It’s a simple way of instrumenting your code without writing complex and uneven administration interfaces! &lt;/p&gt;  &lt;table cellspacing=&quot;0&quot; cellpadding=&quot;5&quot; width=&quot;90%&quot; align=&quot;center&quot; border=&quot;1&quot;&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td style=&quot;background-color: #eaeaea&quot; valign=&quot;top&quot;&gt;Creation and registration of the MBean is done when the bean is instantiated by CDI, not on startup. If you want the MBean to be registered on startup, you will have to annotate your class with the @Singleton and @Startup annotations.&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;If you don’t want the object to be automatically registered on instantiation but still want to register it yourself later in the code, you can set the autoRegister property of the @MBean to false. To register your object programmatically, you use the MBeanFactory service to create a DynamicMBean instance, and then register it to an MBeanServer. For example:&lt;/p&gt;  &lt;p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;
@ApplicationScoped
@MBean(autoRegister=false)
@Description(&quot;Counts the number of visits&quot;)
public class VisitorCounter {
  ...
}

public class VisitorCounterRegistrator {  
  // object we want to expose  
  @Inject VisitorCounter counter;  

  // the service to create the MBean  
  @Inject MBeanFactory mBeanFactory;  

  public void register() throws Exception {    
    DynamicMBean mBean = mBeanFactory.createMBean(counter);    
    ObjectName name = new ObjectName(&quot;org.gescobar:type=VisitorCounter&quot;);    
    MBeanServer mBeanServer = MBeanServerLocator.instance().getmBeanServer();    
    mBeanServer.registerMBean(mBean, name);  
  }  

  public void unregister() throws Exception {    
    ObjectName name = new ObjectName(&quot;org.gescobar:type=VisitorCounter&quot;);    
    MBeanServer mBeanServer = MBeanServerLocator.instance().getmBeanServer();    
    mBeanServer.unregisterMBean(name);  
  }
}
&lt;/script&gt;&lt;/p&gt;  &lt;p&gt;You can even expose objects that are not annotated with @MBean. In this case, all fields and methods from the class are exposed. Any @ManagedAttribute or @ManagedOperation annotations will be ignored.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;CDI Integration&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Writing the portable extension was pretty straightforward. First, I created a class org.gescobar.management.cdi.ManagementExtension that extends javax.enterprise.inject.spi.Extension with a method to observe the ProcessInjectionTarget event:&lt;/p&gt;  &lt;p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;
public class ManagementExtension implements Extension {  

  private static Logger log = LoggerFactory.getLogger(ManagementExtension.class);  

  public &lt;T&gt; void processInjectionTarget(@Observes ProcessInjectionTarget&lt;T&gt; pit) {    
    
    // check if the MBean annotation is present    
    AnnotatedType&lt;T&gt; at = pit.getAnnotatedType();    
    if (at.isAnnotationPresent(MBean.class)) {     
 
      // check if automatic registration is on      
      MBean mBeanAnnotation = at.getAnnotation(MBean.class);      
      if (!mBeanAnnotation.autoRegister()) {        
        log.debug(at.getJavaClass().getName() + &quot;has the MBean annotation with autoRegister=false&quot;);        
        return;      
      }      

      log.debug(&quot;adding automatic JMX registration for: &quot; + at.getJavaClass().getName());      

      // decorate the InjectionTarget      
      final InjectionTarget&lt;t&gt; delegate = pit.getInjectionTarget();      
      InjectionTarget&lt;t&gt; wrapper = new ManagementInjectionTarget&lt;t&gt;(at, delegate);      
      
      // change the InjectionTarget with the decorated one      
      pit.setInjectionTarget(wrapper);    
    }  
  }
}
&lt;/script&gt;&lt;/p&gt;  &lt;p&gt;Basically, what we are doing here is replacing the InjectionTarget with a wrapper class that will register and unregister the MBean if the @MBean annotation is present and autoRegister is true&lt;/p&gt;  &lt;p&gt;To register the portable extension, I created a file called javax.enterprise.inject.spi.Extension with only one line:&lt;/p&gt;  &lt;p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;org.gescobar.management.cdi.ManagementExtension&lt;/script&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;I used TestNG and Arquillian to write and execute the tests inside a remote JBoss AS 6.0.0.M1 container. One of the tests looks like this:&lt;/p&gt;  &lt;p&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;
public class TestAutoRegistration extends Arquillian {  

  private static Logger log = Logger.getLogger(&quot;TestAutoRegistration&quot;);   

  @Deployment  public static JavaArchive createDeployment() {    
    ...  
  }  

  @Inject  
  private CounterAutoRegisterNoName counterNoName;  

  @Test  
  public void shouldRegisterAnnotatedWithNoNameMBean() throws Exception {    
    Assert.assertNotNull(counterNoName);    
    Assert.assertEquals(counterNoName.getCounter(), 0);    

    MBeanServer mBeanServer = MBeanServerLocator.instance().getmBeanServer();    
    ObjectName name = new ObjectName(&quot;org.gescobar.management.test:type=Counter&quot;);    
    Object result = mBeanServer.getAttribute(name, &quot;counter&quot;);    

    Assert.assertNotNull(result);  
  }
}
&lt;/script&gt;&lt;/p&gt;  &lt;p&gt;Arquillian is a JBoss project for running tests on different containers. By the time of this writing, it hasn’t been release but you can download the code from SVN and build it using Maven 2. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;What’s next?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;It would be nice to support the following:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Automatic and manual registration of MBeans for JBoss Seam. &lt;/li&gt;    &lt;li&gt;Manual registration of MBeans in any J2SE environment. &lt;/li&gt;    &lt;li&gt;@ManagedAttribute annotation on methods that return information. &lt;/li&gt;    &lt;li&gt;Name for operation parameters. &lt;/li&gt;    &lt;li&gt;Notifications using annotations. &lt;/li&gt;    &lt;li&gt;Message keys from resource bundles for descriptions. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;You can check the project on Google Code &lt;a href=&quot;http://jmx-annotations.googlecode.com&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Please, feel free to download it and give it a try!&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/6820214222138140269/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/01/cdi-portable-extension-jmx.html#comment-form' title='34 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6820214222138140269'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/6820214222138140269'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/01/cdi-portable-extension-jmx.html' title='JMX Portable Extension for CDI'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjj1Luv00q_j2YLLQqaJXfm3k2xBPbA5e3xchB1tYfVIAT607YG0LuKBawZOjMf7cEqJY-Hq6d9UXfmZyV6mPPPOyLMYUGDRs1-F5cZm-Ce7SdZsHDbO-dKSJ-jPZVmkfPnDtJxo8S1EOzR/s72-c?imgmax=800" height="72" width="72"/><thr:total>34</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-919916524621413472</id><published>2010-01-17T03:25:00.000-08:00</published><updated>2010-01-19T16:07:40.698-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="cdi"/><category scheme="http://www.blogger.com/atom/ns#" term="contexts"/><category scheme="http://www.blogger.com/atom/ns#" term="seam"/><title type='text'>From JBoss Seam to CDI (JEE6)</title><content type='html'>&lt;p&gt;&lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; is a popular open source application framework that has led to the creation of &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; (Contexts and Dependency Injection), a specification that is now part of the JEE 6 ecosystem. In this post I’ll show you the architectural similarities and differences between both and how &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; has influenced &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;. So lets start!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Contexts&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Contexts are definitely one of the most exciting features of &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; (you can read more about them in &lt;a href=&quot;http://germanescobar.blogspot.com/2009/11/understanding-seam-contexts-part-1.html&quot; target=&quot;_blank&quot;&gt;this post&lt;/a&gt;) and remain in the core of &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;.&amp;#160; &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; defines six stateful contexts: &lt;em&gt;request (event)&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt;, &lt;em&gt;application&lt;/em&gt;, &lt;em&gt;page&lt;/em&gt;, &lt;em&gt;conversation&lt;/em&gt; and &lt;em&gt;business process&lt;/em&gt; context. &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; only define 4, leaving &lt;em&gt;page&lt;/em&gt; and &lt;em&gt;business process&lt;/em&gt; contexts out. However, &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; allows you to define new contexts which was not possible in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;. You can see an example of creating a context (the equivalent of the &lt;em&gt;page&lt;/em&gt; context in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;) by Steven Verborgh &lt;a href=&quot;http://www.verborgh.be/articles/2010/01/06/porting-the-viewscoped-jsf-annotation-to-cdi/&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Additionally, &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; now defines a new “&lt;em&gt;dependent&lt;/em&gt;” context which allows a bean to have the same context as the bean that declares it. They will share the same lifecycle meaning that “it [the dependent bean] is instantiated when the object it belongs to is created and destroyed when the object it belongs is destroyed”, as stated in the &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.0/en-US/html/&quot; target=&quot;_blank&quot;&gt;Weld documentation&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;&lt;strong&gt;Dependency Injection&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Even though &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; and &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; both make heavy use of the Dependecy Injection pattern, they take different approaches to implement it. The most notable differences are the following (I’ll explain each one in more detail below): &lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; uses a string-based approach to search for components which is not type safe while &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; brings type safety to the limit. &lt;/li&gt;
&lt;li&gt;&lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; uses dynamic injection while &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; uses static injection. &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;&lt;em&gt;Type safety&lt;/em&gt;&lt;/p&gt;&lt;p&gt;In &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;, every component has a name defined by the @Name annotation. When an injection occurs, Seam searches for the name of the component which can lead to runtime exceptions. For example, suppose you have the following component:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&amp;quot;myBean&amp;quot;)
public class MyBean {
 ...
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now, suppose you mistakenly inject MyBean into a String like this:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@In
private String myBean;
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;This will compile just fine, but at runtime you will get an exception. In large applications, this is a problem as you will potentially have a lot of bugs at runtime, something you really want to avoid.&lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; implements dependency injection based on the type of the bean like in Google Guice. There is no need to name a bean unless you want to access it from EL, in which case, you will need to annotate your bean with the @Named annotation. Lets look at a simple case of injection in &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;: &lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public class Bean1 {
 ...
}

public class Bean2 {
 @Inject
 private Bean1 bean1;
 ...
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;When Bean2 gets instantiated, Bean1 will be injected on Bean2. As you can see, there is no need to name the beans. &lt;/p&gt;&lt;p&gt;&lt;em&gt;Static vs. Dynamic Injection&lt;/em&gt;&lt;/p&gt;&lt;p&gt;In &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;, injection occurs on each method call. After the method completes, all injected values are desinjected (set to null). This is known as dynamic injection and it has its benefits and drawbacks. The most outstanding benefit is that you can inject components from different contexts (i.e. a request component injected in a conversation component)&amp;#160; and you will always have the “correct” instance on each method call. However, dynamic injection has some problems including performance and null values on concurrency.&lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; uses static injection, meaning that all the values are injected on the creation of the bean and they are not desinjected between method calls. To handle injection of beans from different contexts, it uses proxies that reference the “correct” instance of each bean. A much more elegant solution in my opinion.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Factories&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Remember the @Factory annotation in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;? It allows you to obtain objects that are not &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; components; or it could also be used when you need to perform some custom initialization on a component before returning it. In &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;, there is an equivalent functionality called “producer method”:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Produces
public User getUser {
      ...
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Every time a User object is injected, this method will be called to obtain a reference. &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; provides a simpler alternative to a producer method called a producer field:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Produces
private User user;
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Events&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;In &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;, you can decouple your components using events. Each event must have a name. You can raise an event using the @Raise(“&amp;lt;name_of_event&amp;gt;”) annotation or programmatically using the Events.instance().raiseEvent(“&amp;lt;name_of_event&amp;gt;”) method. To observe for an event, you mark the method you want to be called on the event with the @Observer(“&amp;lt;name_of_event&amp;gt;”) annotation.&lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; grabs this concept from &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; and makes it type safe. So, for raising an event we can obtain an Event object by injection: &lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Inject
private Event&amp;lt;User&amp;gt; userEvent;
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;And then call the fire method on the Event object:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;userEvent.fire(user);
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Now, for observing an event you use the @Observes annotation:&lt;/p&gt;&lt;p&gt;&lt;pre class=&quot;brush: java&quot;&gt;public void observeUserEvent(@Observes User user) {
 ...
}
&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Interceptors&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; relies heavily on interceptors for injection, security, persistence and much more. &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; also provides an interception facility called interceptors bindings, based on the Java Interceptors specification. Furthermore, &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; provides the concept of “decorator”, which is a kind of interceptor for implementing the &lt;a href=&quot;http://en.wikipedia.org/wiki/Decorator_pattern&quot; target=&quot;_blank&quot;&gt;decorator pattern&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Wrapping up&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Let’s take a look at the services provided by &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; and see if they were inspired by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Contexts: heavily inspired by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;. &lt;/li&gt;
&lt;li&gt;Dependency Injection: mostly inspired by Google Guice but we have an equivalent in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; (which is not type safe). &lt;/li&gt;
&lt;li&gt;EL integration (the #{} notation): completely inspired by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;. &lt;/li&gt;
&lt;li&gt;Interceptors: completely inspired by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;. &lt;/li&gt;
&lt;li&gt;Events: heavily inspired by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; but type safe. &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Wait a minute! Are these all the services provided by &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;? What about all the out-of-the-box functionality I used to have in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; (page flows, business process integration, security, scheduling, caching, remoting, etc.)? Don’t worry! Portable Extensions, the only service we are missing in this list, will solve this question, so just keep reading!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Portable Extensions and &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; 3&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Besides the services described above, &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; provides a powerful SPI (Service Provider Interface) you can use to create extensions (called Portable Extensions in &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;). This is where &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; 3 enters the game! &lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; 3 will be a set of portable extensions that will provide almost all of the out-of-the-box functionality you actually have in &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; 2. At the time of this writing, &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; 3 is on its first steps and there is no official release yet. However, you can start developing your own portable extensions on top of &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;. Take a look at &lt;a href=&quot;http://smokeandice.blogspot.com/2009/12/external-cdi-configuration-with.html&quot; target=&quot;_blank&quot;&gt;this post&lt;/a&gt; by Matt Corey to start writing your own first portable extension!&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; has been heavily influenced by &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; with two major architectural changes:&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Instead of providing everything out-of-the-box as &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt;, &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; provides a set of core technologies and a powerful SPI that will enable any one write its own portable extensions. &lt;/li&gt;
&lt;li&gt;Type safety. This was included in every aspect of &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; (Contexts, DI and events), except for the EL integration. &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Remember that &lt;font color=&quot;#004080&quot;&gt;Seam&lt;/font&gt; is a framework and &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt; is a specification (Weld is the Reference Implementation). For more information on &lt;font color=&quot;#ff8040&quot;&gt;CDI&lt;/font&gt;, check the &lt;a href=&quot;http://docs.jboss.org/weld/reference/1.0.0/en-US/html/&quot; target=&quot;_blank&quot;&gt;Weld documentation&lt;/a&gt; and the &lt;a href=&quot;http://jcp.org/en/jsr/detail?id=299&quot; target=&quot;_blank&quot;&gt;CDI specification&lt;/a&gt;.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/919916524621413472/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2010/01/from-seam-to-cdi.html#comment-form' title='13 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/919916524621413472'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/919916524621413472'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2010/01/from-seam-to-cdi.html' title='From JBoss Seam to CDI (JEE6)'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>13</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-2433635015582466749</id><published>2009-12-05T13:30:00.000-08:00</published><updated>2009-12-13T06:34:39.257-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="cdi"/><category scheme="http://www.blogger.com/atom/ns#" term="ejb"/><title type='text'>EJB’s: Time to let them go?</title><content type='html'>If you are a JEE developer, you may already be familiar with the benefits of using EJB’s (Enterprise Java Beans) instead of POJO’s (Plain Old Java Objects) in your applications. The list includes, but is not limited to:  &lt;br /&gt;  &lt;ul&gt;   &lt;li&gt;Transaction management.&lt;/li&gt;    &lt;li&gt;Scalability – you can distribute your application across multiple machines.&lt;/li&gt;    &lt;li&gt;Lifecycle management.&lt;/li&gt;    &lt;li&gt;Security management.&lt;/li&gt;    &lt;li&gt;Dependency Injection.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;EJB’s have been with us for a long time and have certainly evolve in the right direction. From the cumbersome EJB 2.x specification with all those interfaces, a very verbose XML definition and an over-designed Entity Beans, to a more convenient EJB 3.0 spec which uses annotations and better persistence management with the introduction of JPA (Java Persistence API).&amp;#160; The new EJB 3.1 spec even gets simpler with no need of the Local interface and the possibility to run inside a Servlet Container.    &lt;br /&gt;    &lt;br /&gt;On the other hand, we have initiatives like Spring and JBoss Seam that try to bring the benefits of the EJB’s to POJO’s. They have been very successful in this task and are being widely adopted. In fact, the reason EJB’s are getting much more simpler lies in the success of these frameworks. The idea behind them is very easy to understand: use annotations inside your POJO’s when you want the benefits of EJB’s and we will use AOP (Aspect Oriented Programming) to deliver that functionality.     &lt;br /&gt;    &lt;br /&gt;They even go further and bind each object to a scope. So, for example, you may want an object to last through the duration of a request or through the whole session of the user. I will not get into the details of this powerful feature but you can read more in &lt;a href=&quot;http://germanescobar.blogspot.com/2009/11/understanding-seam-contexts-part-1.html&quot; target=&quot;_blank&quot;&gt;this post&lt;/a&gt; where I explain how this works in JBoss Seam.    &lt;br /&gt;    &lt;br /&gt;As you can see, there are two approaches to achieve the same goal. The top-down approach is used by the JCP (Java Community Process) expert group to make EJB’s simpler and the bottom-up approach used by frameworks like Spring and JBoss Seam to empower simple POJO’s with enterprise services.    &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;We still need the standards!     &lt;br /&gt;&lt;/strong&gt;    &lt;br /&gt;Standards are good. They allow us as developers to focus on what we have to learn, facilitates the technology selection process, promotes vendor independence and are easily accepted by the executive team in companies, among other benefits.     &lt;br /&gt;    &lt;br /&gt;There have been some efforts to standardize some of the bottom-up approaches. The JSR-299 (Context and Dependency Injection) is one of these efforts leaded by the Seam group which has been approved by the JCP. With JSR-299 you could have POJO’s that behave like EJB’s with dependency injection support and scope demarcation (contexts). So the question is: do we still need EJB’s?    &lt;br /&gt;    &lt;br /&gt;Well, the answer is we do. Unfortunately, the JCP group wants to keep the EJB specification and the JSR-299 group had to make the concept of component (called bean in the JSR-299) more abstract to support EJB’s. I think is confusing and not good for the Java community. While other languages are moving to the KISS (keep it simple, stupid!) principle, we are making things more confusing to developers. With JSR-299, you will be able to work with or without EJB’s. The only benefit of using EJB’s will be the clustered services and JMS but that is something that could have been added to the JSR-299 component model.    &lt;br /&gt;    &lt;br /&gt;&lt;strong&gt;Conclusion     &lt;br /&gt;&lt;/strong&gt;    &lt;br /&gt;I don’t think it’s healthy to continue changing the EJB specification to adapt it to a new simpler model. The JCP group should really let them go, create a unified component model based on POJO’s and add it to the JSR-299. We really need to keep it that simple ;)     &lt;br /&gt;    &lt;br /&gt;&lt;font color=&quot;#ffffff&quot;&gt;K6QA68WYDWM2&lt;/font&gt;&lt;/p&gt;  </content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/2433635015582466749/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2009/12/ejbs-time-to-let-them-go.html#comment-form' title='39 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/2433635015582466749'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/2433635015582466749'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2009/12/ejbs-time-to-let-them-go.html' title='EJB’s: Time to let them go?'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>39</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-5534281593621143595</id><published>2009-11-22T09:07:00.000-08:00</published><updated>2009-12-03T09:36:57.518-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="contexts"/><category scheme="http://www.blogger.com/atom/ns#" term="jsf"/><category scheme="http://www.blogger.com/atom/ns#" term="richfaces"/><category scheme="http://www.blogger.com/atom/ns#" term="seam"/><title type='text'>Seam and JSF</title><content type='html'>&lt;p&gt;In my &lt;a href=&quot;http://germanescobar.blogspot.com/2009/11/understanding-seam-contexts-part-1.html&quot;&gt;last post&lt;/a&gt;, I talked about Seam contexts and how to use them from your application. Now, I’ll show you how you can access them from JSF, especially how to use the &lt;em&gt;event&lt;/em&gt; context correctly. At the end, I’ll give you some tips you may find useful when developing the web tier of your application with Seam and JSF.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Accessing contexts from your JSF pages&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;In Seam, you can access anything saved in the contexts from a JSF page using the #{} notation. For example, consider the following line of code:&lt;/p&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;h:outputText value=&amp;quot;#{employee.name}&amp;quot; /&amp;gt;
&lt;/pre&gt;&lt;p&gt;This will search all the stateful contexts for the “employee” key using the Contexts.lookupInStatefulContexts() method as I showed you in my last post. Remember that the context search priority is: &lt;em&gt;event&lt;/em&gt;, &lt;em&gt;page&lt;/em&gt;, &lt;em&gt;conversation&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt;, &lt;em&gt;business process&lt;/em&gt; and &lt;em&gt;application&lt;/em&gt;. If the key is not found in any of the contexts, it will return null. Otherwise, it will try to call the getName() method on the object.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;JSF and the event context&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;The &lt;em&gt;event&lt;/em&gt; context is the narrowest of the stateful contexts; it only lasts during a single http request. It is very useful when working with data iteration because Seam binds the iterated variable into the &lt;em&gt;event&lt;/em&gt; context. Consider the following code fragment:&lt;/p&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;rich:dataTable value=&amp;quot;#{employees}&amp;quot; var=&amp;quot;employee&amp;quot;&amp;gt;
 &amp;lt;rich:column&amp;gt;
  &amp;lt;h:outputText value=&amp;quot;#{employee.name}&amp;quot; /&amp;gt;
 &amp;lt;/rich:column&amp;gt;
 &amp;lt;rich:column&amp;gt;
  &amp;lt;h:outputText value=&amp;quot;#{employeeSalaryResolver.netSalary}&amp;quot; /&amp;gt;
 &amp;lt;/rich:column&amp;gt;
&amp;lt;/rich:dataTable&amp;gt;
&lt;/pre&gt;&lt;p&gt;In line 6 we are calling another component called employeeSalaryResolver to retrieve the net salary of the employee. Seam binds the actual employee object into the event context, so, we can just inject it in the EmployeeSalaryResolver component:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&amp;quot;employeeSalaryResolver&amp;quot;)
public class EmployeeSalaryResolver {
 
 @In
 private Employee employee;

 public double getNetSalary() {
  double netSalary = employee.getBaseSalary();
  
  // do other complex calculations (extra hours, bonus, etc.)  
  
  return netSalary;
 }
}
&lt;/pre&gt;&lt;p&gt;The employee attribute is being injected from the iteration variable (the &lt;em&gt;event&lt;/em&gt; context) and used to retrieve the net salary of the employee. This component can be then reused in other use cases.&lt;/p&gt;&lt;p&gt;You can also use the &lt;em&gt;event&lt;/em&gt; context to pass information between pages. For example, imagine a component that searches for an employee using the social security number and shows the result in another page.&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&amp;quot;searchEmployee&amp;quot;)
public class SearchEmployee {
 
 private String ssNumber;
 
 @Out(scope=ScopeType.EVENT,required=false)
 private Employee employee;

 public String search() {
  Employee employee = ...; // search for the employee
  if (employee != null) {
   return &amp;quot;success&amp;quot;;
  }
  
  return null; 
 }
}
&lt;/pre&gt;&lt;p&gt;When the search method is called (from a page I’m not showing) and an employee is found, the searchEmployee component will outject the Employee object to the &lt;em&gt;event&lt;/em&gt; context and render the result in another page. The navigation in pages.xml would be something like this:&lt;/p&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;page view-id=&amp;quot;searchEmployee.xhtml&amp;quot;&amp;gt;
 &amp;lt;navigation&amp;gt;
  &amp;lt;rule if-outcome=&amp;quot;success&amp;quot;&amp;gt;
   &amp;lt;render view-id=&amp;quot;searchResult.xhtml&amp;quot;/&amp;gt;
  &amp;lt;/rule&amp;gt;
 &amp;lt;/navigation&amp;gt;
&amp;lt;/page&amp;gt;
&lt;/pre&gt;&lt;p&gt;If you notice, we are using &lt;em&gt;render&lt;/em&gt; tag instead of &lt;em&gt;redirect&lt;/em&gt; tag. This will forward the request to the searchResult.xhtml page instead of redirecting, so the event context will not be lost. &lt;/p&gt;&lt;p&gt;&lt;strong&gt;Seam and JBoss EL&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Standard EL (the #{} notation you use in your JSF pages) does not allow you to call methods with predefined parameters. However, Seam overcomes this limitation by using JBoss EL, which is an extension of the standard EL. For example, in our employees application, suppose we have a list of employees and we want to add an option on each row to fire employees. So, we create a fireEmployee component with a fire method that receives an Employee as an argument. &lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&amp;quot;fireEmployee&amp;quot;)
public class FireEmployee {

 public void fireEmployee(Employee employee) {
  // fire employee
 }
}
&lt;/pre&gt;&lt;p&gt;Now, we just need to add the action to the employees&#39; page.&lt;/p&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&amp;lt;rich:dataTable value=&amp;quot;#{employees}&amp;quot; var=&amp;quot;employee&amp;quot;&amp;gt;
 &amp;lt;rich:column&amp;gt;
  &amp;lt;h:outputText value=&amp;quot;#{employee.name}&amp;quot; /&amp;gt;
 &amp;lt;/rich:column&amp;gt;
 &amp;lt;rich:column&amp;gt;
  &amp;lt;h:outputText value=&amp;quot;#{employeeSalaryResolver.netSalary}&amp;quot; /&amp;gt;
 &amp;lt;/rich:column&amp;gt;
 &amp;lt;rich:column&amp;gt;
  &amp;lt;s:link value=&amp;quot;Fire Employee&amp;quot; action=&amp;quot;#{fireEmployee.fire(employee)}&amp;quot; /&amp;gt;
 &amp;lt;/rich:column&amp;gt;
&amp;lt;/rich:dataTable&amp;gt;
&lt;/pre&gt;&lt;p&gt;Really cool feature! Look at the &amp;lt;s:link&amp;gt; tag. Seam introduces some JSF tags to ease development. I won’t describe them here, but if you want, you can check them &lt;a href=&quot;http://docs.jboss.org/seam/2.2.0.GA/reference/en-US/html/controls.html&quot;&gt;here&lt;/a&gt;. &lt;/p&gt;&lt;p&gt;&lt;strong&gt;Tips using Seam and JSF&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;1. Backing beans&lt;/em&gt;&lt;/p&gt;&lt;p&gt;In Seam, you can use EJB’s as your backing beans. However, by default, use JavaBeans (POJO’s). The reason is that you usually bind the backing bean to the &lt;em&gt;page&lt;/em&gt; scope, but, if you use EJB Session Beans, you will not be able to do this. &lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Name(&amp;quot;someBean&amp;quot;)
@Scope(ScopeType.PAGE)
@Synchronized
public class SomeBean implements Serializable {

 private static final long serialVersionUID = -2524956479693778917L;

 // your code ...
}
&lt;/pre&gt;&lt;p&gt;You can also bind your backing beans to the &lt;em&gt;conversation&lt;/em&gt; or &lt;em&gt;session&lt;/em&gt; scopes when needed. The @Synchronized annotation tells Seam to serialize requests from the backing beans as concurrency may cause some problems occasionally, especially when you are using AJAX calls. A better approach, however, is to use the eventQueue attribute in your richfaces components. See &lt;a href=&quot;http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/ArchitectureOverview.html#AjaxRequestOptimization&quot;&gt;this&lt;/a&gt; for more information.&lt;/p&gt;&lt;p&gt;&lt;em&gt;2. Use a naming convention for your components&lt;/em&gt;&lt;/p&gt;&lt;p&gt;You have to choose carefully the name you assign to each of your components because as the application starts growing, you may repeat component names and having some conflicts. So, you can use the package as a prefix for the name of the component.&lt;/p&gt;&lt;p&gt;However, if the project is small, you also can use a simpler prefix if you want. For example, you can use the “controller” prefix for your backing beans, “logic” for your business components and “model” for your entities and DAO’s.&lt;/p&gt;&lt;p&gt;&lt;em&gt;3. You can use more than one Backing Bean per page&lt;/em&gt;&lt;/p&gt;&lt;p&gt;A lot of people use one backing bean per page. However, I really discourage this at it does not promotes code reusing and increments coupling. For example, if you have something you show in every page, use a separate backing bean and bind it to the &lt;em&gt;session&lt;/em&gt; scope instead of retrieving the same information in every page.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;Seam allows you to access any component in any context from JSF, this gives you the opportunity to choose how you want to architect your solution with some cool features that help you speed development time.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/5534281593621143595/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2009/11/seam-and-jsf.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/5534281593621143595'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/5534281593621143595'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2009/11/seam-and-jsf.html' title='Seam and JSF'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-7240025612866996053</id><published>2009-11-06T15:40:00.000-08:00</published><updated>2009-11-21T08:54:29.731-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="contexts"/><category scheme="http://www.blogger.com/atom/ns#" term="seam"/><title type='text'>Understanding Seam Contexts</title><content type='html'>&lt;p&gt;One of the most exciting features of JBoss Seam is the contextual component model that radically changes the way we design applications. It has become so important, it is now part of the JEE6 specification through the JSR-299. In this post, I will concentrate on explaining how Seam contexts work and how to use them from your code.&lt;/p&gt;&lt;p&gt;You may already be familiar with the request, session and application scopes of the Servlet specification. They are very useful to save and retrieve data but they have a huge limitation: you can only access them from a Servlet/JSP.&lt;/p&gt;&lt;p&gt;JBoss Seam overcomes this limitation by making the scopes (called contexts in Seam) available to the whole application instead of only to Servlets/JSP’s. So, you’ll find &lt;em&gt;request(event)&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt; and &lt;em&gt;application&lt;/em&gt; contexts and 3 more they’ve created: &lt;em&gt;page&lt;/em&gt;, &lt;em&gt;conversation&lt;/em&gt; and &lt;em&gt;business process&lt;/em&gt; contexts.&lt;/p&gt;&lt;p&gt;The &lt;em&gt;request&lt;/em&gt;(event), &lt;em&gt;session&lt;/em&gt; and &lt;em&gt;application&lt;/em&gt; contexts work exactly as they do in Servlets/JSP’s so I’ll just skip their explanation. I will, however, explain briefly the &lt;em&gt;page&lt;/em&gt;, &lt;em&gt;conversation&lt;/em&gt; and &lt;em&gt;business process&lt;/em&gt; contexts.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Page Context&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;The page context is broader than the request context as it spans multiple requests over the same page. This is very useful if you need to make roundtrips to the server to perform validation, bring information, etc. while maintaining the same page state.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Conversation Context&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;The conversation context is broader than the page context as it can expand to multiple request and pages but narrower than the session context. It is very useful to implement wizards-like interfaces in which the user has to fill data across multiple pages while maintaining the state over the whole process. You control the creation and destruction of each conversation.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Business Process Context&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;As it name implies, it is used to maintain state information during the execution of a business process instance in jBPM.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Using contexts from your code&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;You can use the &lt;em&gt;Contexts&lt;/em&gt; class to gain access to one of the contexts, defined by the &lt;em&gt;Context&lt;/em&gt; interface, and then use the &lt;em&gt;set&lt;/em&gt; or g&lt;em&gt;et&lt;/em&gt; methods to save or retrieve information respectively.&lt;/p&gt;&lt;p&gt;For example, to save the current user information in the session context you use the following code:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;User user = new User();
Contexts.getSessionContext().set(&quot;user&quot;, user);
&lt;/pre&gt;&lt;p&gt;Then, when you need to retrieve the user information, you use:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;User user = (User) Contexts.getSessionContext().get(&quot;user&quot;);
&lt;/pre&gt;&lt;p&gt;Really simple, ah? You can also use the @Out and @In annotations in class attributes to save and retrieve information:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@Out(value=&quot;user&quot;,scope=ScopeType.SESSION)
private User user;
&lt;/pre&gt;&lt;p&gt;What the @Out annotation is telling Seam is to save the User object in the Session context with the key “user”. Then, you can retrieve the user with the following code:&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@In(value=&quot;user&quot;,scope=ScopeType.SESSION)
private User user;
&lt;/pre&gt;&lt;p&gt;Again, the @In attribute is telling Seam to inject the User object from the Session context saved with the “user” key. You don’t have to write any getters or setters in your class, Seam will just outject or inject the information whenever an @Out or @In annotation is present. If no object is found under the “user” key, null will be injected.&lt;/p&gt;&lt;p&gt;As you can see, the &lt;em&gt;value&lt;/em&gt; attribute of the @In and @Out annotations are used as a key for searching or saving data in the contexts. The scope attribute is used to specify the context in which the value should be injected or outjected. This attributes are optional; so, what happens if we don’t specify them as in the following example?&lt;/p&gt;&lt;pre class=&quot;brush: java&quot;&gt;@In
private String name;

@Out
private User user;
&lt;/pre&gt;&lt;p&gt;When you don’t specify the &lt;em&gt;value&lt;/em&gt; attribute, Seam uses the attribute’s name as key by default. In the preceding code fragment, Seam will use “name” as the key for the @In annotation and “user” for the @Out annotation.&lt;/p&gt;&lt;p&gt;If you don’t specify the scope of an @In annotation, Seam will scan all the contexts in the following order: &lt;em&gt;event&lt;/em&gt;, &lt;em&gt;page&lt;/em&gt;, &lt;em&gt;conversation&lt;/em&gt;, &lt;em&gt;session&lt;/em&gt;, &lt;em&gt;business process&lt;/em&gt; and &lt;em&gt;application&lt;/em&gt;. If the key is not found, it will inject null. You can use this feature programmatically by calling the &lt;em&gt;Contexts.lookupInStatefulContexts()&lt;/em&gt; method.&lt;/p&gt;&lt;p&gt;If you don’t specify the scope of an @Out annotation … well, as the @Out JavaDoc states: “If no scope is explicitly specified, the default scope depends upon whether the value is an instance of a Seam component. If it is, the component scope is used. Otherwise, the scope of the component with the @Out attribute is used.” I know, I haven’t talked anything about Seam components as it is not the topic of this article. If you want to know about Seam components &lt;a href=&quot;http://docs.jboss.org/seam/1.0.1.GA/reference/en/html/concepts.html#d0e2184&quot; target=&quot;_blank&quot;&gt;read this&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;I hope this introduction has given you the basics of Seam contexts. It is a very simple, yet powerful, concept that has to be taken seriously when designing your next applications.&lt;/p&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/7240025612866996053/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2009/11/understanding-seam-contexts-part-1.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/7240025612866996053'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/7240025612866996053'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2009/11/understanding-seam-contexts-part-1.html' title='Understanding Seam Contexts'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-6137205730562326735.post-3556468845495151203</id><published>2009-10-29T21:37:00.001-07:00</published><updated>2009-11-19T02:20:58.922-08:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="gwt"/><category scheme="http://www.blogger.com/atom/ns#" term="jquery"/><category scheme="http://www.blogger.com/atom/ns#" term="richfaces"/><title type='text'>AJAX: JQuery, Google Web ToolKit or RichFaces</title><content type='html'>If you are reading this, you probably have already decided to use an AJAX framework for your web application instead of writing plain JavaScript code yourself. However, with so many options out there, picking one is not an easy task. I’ll try to compare JQuery, GWT and RichFaces and hopefully help you to choose the one that suits your needs.   &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;JQuery&lt;/strong&gt;   &lt;br /&gt;
&lt;br /&gt;
JQuery is just a JavaScript library that simplifies AJAX development by allowing you to:   &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Manipulate HTML (i.e. adding and removing css styles, changing input values, etc.) from the client. &lt;/li&gt;
&lt;li&gt;Handle events (i.e. keydown, focus, mouseover, etc.) &lt;/li&gt;
&lt;li&gt;Make AJAX calls to the server (i.e. sending data to a Servlet and processing the returned information)&amp;#160; &lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;JQuery is very simple to setup. All you need to do is download the jquery.js file and reference in the head of your page with the following line: &lt;/p&gt;&lt;pre class=&quot;brush: html&quot;&gt;&amp;lt;script type=&amp;quot;text/javascript&amp;quot; src=&amp;quot;jquery.js&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;/pre&gt;&lt;p&gt;HTML files are written as usually and JQuery is added where needed. There is no need of an application server to use JQuery as it is pure JavaScript. You will need, however, some JavaScript and CSS skills to get the work done. So, if you are not a very good JavaScript developer, you’ll be better with one of the other options. &lt;/p&gt;&lt;p&gt;Server calls are done via HTTP requests so you’ll have to expose your services through Servlets. You can use JSON, XML or plain text to send and receive information but you’ll have to manage object serialization/deserialization and state between requests yourself.    &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Google Web ToolKit&lt;/strong&gt;     &lt;br /&gt;
&lt;br /&gt;
GWT is based on Java. It allows you to write code in Java and &amp;quot;convert&amp;quot; it into JavaScript. As you may know, GWT is used in some of the Google Applications including the new Google Wave and Google AdWords, so it is really fast! It now has a Plugin for Eclipse that makes development simpler. &lt;/p&gt;&lt;p&gt;GWT is not as easy to setup as JQuery, but still relatively simple. You can use either the Eclipse Plugin or a command utility called webAppCreator to create the skeleton of the project.    &lt;br /&gt;
&lt;br /&gt;
Even though you wont need to know JavaScript at all, GWT is the most difficult to learn as it is a completely new technology built from ground-up. Basically, you create your template in HTML, add all the components from a Java class using the GWT API and format those components using a CSS file. You don’t get to see how your interface looks until you compile and run it. However, once you are familiar with the development process, is very straightforward.     &lt;br /&gt;
&lt;br /&gt;
Web server calls are done using GWT RPC or JSON over HTTP. GWT RPC hides the complexity of object serialization/deserialization. You must create a couple of interfaces and a implementation for each “service”. Then, from those services, you can call your business logic. Still not the ideal solution for server calls. Besides, you will still need to manage your state between requests yourself.     &lt;br /&gt;
&lt;br /&gt;
One thing I like about GWT is that it has a really good support for browser history so you can easily avoid problems when the user hits the browser&#39;s back button. However, you will need to spend development effort to achieve this.     &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;RichFaces&lt;/strong&gt;     &lt;br /&gt;
&lt;br /&gt;
The thing about RichFaces is that it is really simple to understand as it is built over an already known technology: JSF (Java Server Faces). If you haven&#39;t work with JSF, I really suggest you do as it is one of the most powerful, easy to learn Web technologies, very similar to swing with heavy use of components and events. It also has a really good support for managing the state in the server using plain Java objects (POJO’s).     &lt;br /&gt;
&lt;br /&gt;
So, RichFaces is really a JSF set of components with AJAX support. You’ll find components such as button, table, calendar, tabs and suggestion box, among others. It also adds AJAX support to existing JSF components such as input texts and buttons.     &lt;br /&gt;
&lt;br /&gt;
Setup is not as easy as JQuery or GWT as you need to configure JSF first and run it using a J2EE web container. RichFaces is great with server calls but has no support for HTML manipulation. So, you’ll need integrate JQuery with RichFaces to speed up your interface which is really simple to do.     &lt;br /&gt;
&lt;br /&gt;
What I really like about RichFaces is the clean separation of concerns (Model, View, Controller) and that it is built on top of JSF, which makes it very powerful and easy to learn.     &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Conclusion&lt;/strong&gt;     &lt;br /&gt;
&lt;br /&gt;
Each framework offers you unique benefits depending on your skills and needs. JQuery is ideal for those JavaScript developers who need to do a lot of HTML manipulation and animation. GWT offers the benefit of JQuery to those who don’t want to write javascript code directly. Finally, if you are planning to use JSF, RichFaces gives you a perfect balance with a set of rich controls for your web interface and AJAX calls to your Backing Beans.     &lt;br /&gt;
&lt;br /&gt;
&lt;strong&gt;Resources&lt;/strong&gt;     &lt;br /&gt;
&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;http://www.jquery.com/&quot; target=&quot;_blank&quot;&gt;JQuery&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://code.google.com/intl/es-CO/webtoolkit/&quot; target=&quot;_blank&quot;&gt;Google Web ToolKit&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;http://www.jboss.org/richfaces&quot; target=&quot;_blank&quot;&gt;RichFaces&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;</content><link rel='replies' type='application/atom+xml' href='http://germanescobar.blogspot.com/feeds/3556468845495151203/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://germanescobar.blogspot.com/2009/10/ajax-jquery-google-web-toolkit-or.html#comment-form' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/3556468845495151203'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/6137205730562326735/posts/default/3556468845495151203'/><link rel='alternate' type='text/html' href='http://germanescobar.blogspot.com/2009/10/ajax-jquery-google-web-toolkit-or.html' title='AJAX: JQuery, Google Web ToolKit or RichFaces'/><author><name>Germán Escobar</name><uri>http://www.blogger.com/profile/05863454066402527692</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjLCry7tbVGAgJYScK5z6LTgQki8w6CIW9B0ptX3KB6Aw1ygKeyG4FnJMQwg2FpCzdPR_1BxPtLtGBslNYjtyUCemjys0q0o08-iMy1AiBKlQ1Hx-dte-vRgxpswzeQjg/s220/foto-perfil.jpg'/></author><thr:total>7</thr:total></entry></feed>