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

<channel>
	<title>Andy Gibson</title>
	<atom:link href="http://www.andygibson.net/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Software Development Blog</description>
	<lastBuildDate>Thu, 04 Mar 2010 00:27:53 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Random Lost Thoughts</title>
		<link>http://www.andygibson.net/blog/index.php/2010/02/25/random-lost-thoughts/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/02/25/random-lost-thoughts/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 03:22:03 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[tv]]></category>
		<category><![CDATA[Lost]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=825</guid>
		<description><![CDATA[Bring out yer dead!
At various points throughout the show, there have been numerous dead bodies and with it, a strong urge to bury the dead. Consider even when Rousseau and Karl were shot by Mercenaries, they took the time to bury the bodies, and it&#8217;s not like their arrival was going to be a secret [...]]]></description>
			<content:encoded><![CDATA[<h4>Bring out yer dead!</h4>
<p>At various points throughout the show, there have been numerous dead bodies and with it, a strong urge to bury the dead. Consider even when Rousseau and Karl were shot by Mercenaries, they took the time to bury the bodies, and it&#8217;s not like their arrival was going to be a secret for long. in LaFleur, when Sawyer and Juliet killed the others attacking Amy, they had to bury the bodies in accordance with The Truce. Now this might be a way to hide the killings, but it also may mean that any dead bodies must be buried. After The Purge, the bodies were put in a shallow grave, but not covered.<br />
<span id="more-825"></span><br />
Christian Shepherd&#8217;s body, like John Lockes body was on its way to be buried, we have no confirmation that Alex was buried. Yemi&#8217;s body wasn&#8217;t buried when the plane crashed although Eko burned the plane but Yemi&#8217;s body was mysteriously missing. Sayid technically did die and was not buried. Claire, if she did die wasn&#8217;t buried either.</p>
<p>So far it seems all of these bodies have been taken over or manipulated by the Smoke Monster/the Man In Black. My thinking is that when bodies are not buried, they are available for claiming by the Man In Black / Smokey, hence the need to ensure that any dead bodies are not left above ground to provide a shell for the MIB to manipulate. Yemi, Locke, Christian (probably) and maybe Claire have been affected by Smokey / MIB to some degree. Incidentally, this could also be a theory for Adam and Eve. One dark, one light, one for the Mib and one for Jacob for the next iteration. I also seem to recall that someone made the comment that the dead on the island tend not to stay dead or some similar phrase. </p>
<h4>Numbers Up</h4>
<p>Throughout the show, <a href="http://lostpedia.wikia.com/wiki/The_numbers">the numbers</a> have been one of the most intriguing mysteries of all. The writers have said a couple of times that there might never be an explanation for the numbers.<br />
<quote>at a certain point, explaining something mystical demystifies it. To try and have a character come and say, &#8220;Here is what the numbers mean,&#8221; actually makes every usage of the numbers up to that point less interesting. </quote> &#8211; Damon Lindelhof</p>
<p>Within the show, the numbers have been a consistent factor all along and while I am willing to concede absolutely that many occurrences of them is just pure coincidence (like the soccer shirts at the airport and hotel rooms), I think there absolutely is some need to explain their meaning. I think it goes beyond coincidence that the same numbers that were imprinted on the hatch end up being broadcast from the island for decades and were entered into the computer for so long. Why not just have the swan operator press the enter key every 108 minutes, why enter anything at all? Why even bother imprinting the numbers on the hatch if there is no relevance? It&#8217;s like writing the show so that every character is called Mike. It&#8217;s either relevant to the purpose they are there or just bloody stupid if you put it down to coincidence. With the last couple of weeks we have seen an introduction of the numbers again assigned to people and even angles on the lighthouse mirror so hopefully we will get the complete answer to the numbers.</p>
<h4>The Loophole</h4>
<p>So, it seems that Jacob and the Man In Black have been playing the same game over and over and this time the MIB finally found a way to kill Jacob. He asks Jacob if he has any idea what he had to go through which raises the interesting question of how long has MIB been manipulating the game? It seems smokey may have been on to John when they first encountered each other in Walkabout which was the fourth episode. John saw something beautiful, perhaps it was his own spiritual reflection, or perhaps it was smokey showing Locke what he needed to see (a common theme in Lost). One quality MIB needed was Locke&#8217;s desire to stay on the Island if he was to go off Island, die and bring everyone back. I&#8217;m sure there were other rules regarding who who could kill Jacob and how and why. Obviously, MIB couldn&#8217;t just kill Ben and then impersonate him as the leader of the others, get an audience with Jacob and then kill him especially since Ben had never had an audience with Jacob so how could he? The MIB had to promote John Locke up to the level of leader in such a way that he would be allowed to see Jacob, along with the requirement that Locke be that special someone who was the right kind of person to lead the Others and be so in tune with the Island that he would get to see Jacob. If this is the case, then it allows one to re-watch Lost with fresh eyes, spotting the places where Locke, and the Others were manipulated along, where Locke was encouraged forwards to the point where he would find his own destiny on the Island, but then meet the needs of returning to the Island dead so the MIB could then assume his identity and role and then manipulate Ben into wanting to kill Jacob. Perhaps MIB has been masquerading as Jacob for the purpose of ignoring Ben to prime the pump so to speak since we know someone else was using Jacobs cabin and he only showed himself to Locke to set the ball rolling.<br />
I think we need to learn a little more about the rules in order to start drawing up what the MIB needed to do in order to create the loophole and how he did it. What would be mind blowing is if along with MIB manipulating the whole show we found out that Jacob had been manipulating the whole show so he could defeat the MIBs plans. After all, in the lighthouse, Jack was outraged that Jacob had been watching him and setting this up his whole life. Perhaps they both have been manipulating the viewers for the whole show. Perhaps Jack is Jacobs hope the same way Locke was MIBs hope, after all Jack versus Locke has been another common thread.</p>
<h4>Random Mysteries</h4>
<p>Here&#8217;s some random mysteries that I keep thinking about and will hopefully get answered.</p>
<ul>
<li>Why broadcast the numbers/enter them into the computer, whats the relevance?</li>
<li>What&#8217;s with the psychic who advised Claire</li>
<li>Why were all those tubes from the Dharma observation station being dumped in the middle of nowhere</li>
<li>Why can&#8217;t women get pregnant?</li>
<li>What happened to Anne? (Darlton claimed she and the volcano were important)</li>
<li>What was the deal with Jin taking that watch to LA?</li>
<li>I&#8217;m sure there&#8217;s more to Cindy than we know</li>
<li>Will we see a Libby backstory?</li>
</ul>
<p>Even as we start to draw down the show in the final season, we still keep getting fresh mysteries, such as who is Jacks ex-wife in the alternative timeline? </p>
<h4>Back to the Beginning</h4>
<p>Interestingly, we seem to be redoing the first season again. Many of the issues are cropping back up, Shannon&#8217;s inhaler, the caves, Adam and Eve, treks into the jungle with Jack and Hurley. Also, the central character for the episode that we see flash sideways for mirrors the season 1 order with Kate, Locke and Jack and Sun is next in both Season 6 and Season 1. It should be interesting the week after since that was a Charlie centric episode. One of the biggest earliest questions was &#8220;What is the smoke monster?&#8221;, after all it was introduced in the first episode. Darlton commented that we wouldn&#8217;t find out till the very last episode. I thought, like many others, he was joking but it seems that this is indeed the case since the MIB (along with Jacob) seems to be final mystery that encapsulates all others and probably will only be answered in the finale.</p>
<p>The parallels with Season 1 casts fuel on to the fire that the whole thing will end with a reset and start at the beginning, but that would seem a rather cruel and clumsy way to end it. Perhaps we see the start of the next iteration with the next group of Losties arriving at the Island. It would certainly open the door to another season or two or more likely, a spin off without having requiring the original actors or writers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/02/25/random-lost-thoughts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Composition in Object Modeling</title>
		<link>http://www.andygibson.net/blog/index.php/2010/02/16/using-composition-in-object-modeling/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/02/16/using-composition-in-object-modeling/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 14:33:35 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[articles]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[modeling]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=765</guid>
		<description><![CDATA[Using composition over inheritance is a common design pattern that is often discussed in terms of designing business logic components. However, composition can solve a number of problems in domain object modeling that are created by relying on inheritance to share interface or functionality. Composition is used to delegate implementation in logical units by enlisting [...]]]></description>
			<content:encoded><![CDATA[<p>Using composition over inheritance is a common design pattern that is often discussed in terms of designing business logic components. However, composition can solve a number of problems in domain object modeling that are created by relying on inheritance to share interface or functionality. Composition is used to delegate implementation in logical units by enlisting the help of a reference to an object that implements the required functionality instead of inheriting from it. This reference can be changed to different implementations depending on the needs at the time making for a more flexible design. This same design can be used in domain modeling to overcome some of the problems caused by inheritance. The typical flawed example of using inheritance in object modeling is the <code>Person</code> class which is often subclassed into <code>Employee</code>, <code>User</code> , <code>Customer</code> and <code>Vendor</code> classes.<br />
<span id="more-765"></span></p>
<pre name="code" class="java">
public class Person {

  private Long id;
  private String firstName;
  private String lastName;
}
</pre>
<pre name="code" class="java">
public class User extends Person {

  private String userName;
  private String password;

}
</pre>
<pre name="code" class="java">
public class Customer extends Person {

  private int creditLimit;

}
</pre>
<pre name="code" class="java">
public class Employee extends Person {

  private Date beginDate;
  private Date endDate;

}
</pre>
<p>The classic problems here are that a customer may not always be a person, and a person may be both a customer and a vendor and possibly even be an employee and user. It also ignites the age old debate of whether a user must be an employee or all employees are also users. Using inheritance severely restricts us by taking away our one chance to inherit from a single class and limits our future plans since we are claiming some hard rules such as &#8220;every user is a person&#8221;. </p>
<p>Also, how do we handle a person that leaves the company and comes back? Do we have two different instances of this person in the system? For that matter, most Person instances will be duplicated if a person is a customer and a user and employee. This also leads to problems with things like name changes where one version gets updated but the other doesn&#8217;t.</p>
<h4>Role your own</h4>
<p>One common solution to this problem is to let the <code>Person</code> entity have a collection of roles that they perform so they can be either a user,an employee, a customer or vendor at the same time. This does solve the problems of not having to worry about inheritance hierarchies and whether a user is an employee or vice versa and also lets a person play all those roles at once. However, it only works where you know that every user, customer, vendor or employee will be a person.<br />
It&#8217;s also not very clear how we should reference these entities. If I have an order and need to reference a customer, do I reference the person or the persons customer role? </p>
<h4>Compose Yourself</h4>
<p>Alternatively you can use composition to model the relationship instead of inheritance. We can define a <code>Person</code> class which models just a person and we model Customers and Employees as separate classes that encapsulate the information specific to that role and has a reference to the person associated with it.The benefit here is that the different classes do not have to be subclassed from the <code>Person</code> class which lets us inherit from whatever we want.</p>
<pre name="code" class="java">
public class User {

  private Long id;
  private String userName;
  private String password;
  private Person person;
}
</pre>
<p>and</p>
<pre name="code" class="java">
public class Customer {

  private Long id;
  private Person person;
  private int creditLimit;
}
</pre>
<pre name="code" class="java">
public class Employee {

  private Long id;
  private Person person;
  private Date beginDate;
  private Date endDate;
}
</pre>
<p>We don&#8217;t have to worry about whether <code>Employee</code> should inherit from a <code>User</code> or vice versa since they are entirely different entities but they reference the same person instance. We still have the ability to check for things like users that are employees by finding users and employees that have a matching person reference. Modeling for each of the entities is kept specific to what the entity represents. A customer contains customer information and an employee contains employee information with only a single reference to the person it is representing. </p>
<p>This solves our original problems, but also gives us far more in return. It is a far more flexible design because we can expand the definitions of the classes beyond the hard restriction that every customer must be a person. Let&#8217;s consider a situation where the developers have been asked to allow businesses to also be defined as customers in the system. With the Customer subclassing from Person design it would be a nightmare to change the code to accommodate this. On the other hand, if we designed Customer to use composition, we can easily resolve the problem.</p>
<pre name="code" class="java">
public abstract class AbstractCustomer {

  private Long id;
  private int creditLimit;
  public abstract String getName();
}
</pre>
<p>We can create a person based customer by subclassing it and adding a reference to the person.</p>
<pre name="code" class="java">
public class PersonCustomer extends AbstractCustomer {

  private Person person;

  public abstract String getName() {
    return person.getName();
  }
}
</pre>
<p>For a company based customer, we can again subclass it, this time adding a <code>Company</code> reference. </p>
<pre name="code" class="java">
public class CompanyCustomer extends AbstractCustomer {

  private Company company;

  public abstract String getName() {
    return company.getName();
  }
}
</pre>
<p>Notice that in the abstract base class, we define the <code>getName()</code> method to return the name of the customer. This is made abstract and must be implemented in subclasses specific to the type of customer we are implementing. As a general rule, like any inheritance, common attributes that apply to all types of the entity should go in the base class because then you will be able to call those methods on references to the entity as the base class type instead of having to use a more specific subclass type. For example</p>
<pre name="code" class="java">
  String msg = "Hi There "+customer.getName();
</pre>
<p>is much cleaner than</p>
<pre name="code" class="java">
  String msg = "Hi There ";

  if (customer instanceof PersonCustomer) {
    msg = msg+((PersonCustomer)customer).getPerson.getPersonName();
  }

  if (customer instanceof CompanyCustomer) {
    msg = msg+((CompanyCustomer)customer).getCompany.getCompanyName();
  }
</pre>
<p>Another nice effect of this is modularity since you can add new customer types and the old queries will work the same way. For example, if you start with <code>PersonCustomer</code> you might have a query which lists the customers with a certain credit limit.</p>
<pre name="code" class="sql">
select c from Customer c where c.creditLimit > 500
</pre>
<p>If you suddenly add the <code>CompanyCustomer</code> class to the application, the query will still work and will now include company based customers in the list. Remember, the more attributes defined on the base class, the more attributes you will be able access or query on when obtaining instances as the base class. However, note that code driven attributes such as the <code>getName()</code> example above cannot be used for querying in JPA since the attribute does not resolve to a database field. To query by person name you would have to drop down to using the actual class name to query the name fields in the person reference. </p>
<h4>Unique People, non-unique references</h4>
<p>If an employee leaves the company and comes back, we can deal with this much easier because we can set the end date for the existing <code>Employee</code> instance when they leave and when they come back, we can create a new employee instance that references the same <code>Person</code> entity. We still only have one <code>Person</code> instance that is referenced by both <code>Employee</code> instances and thus there is no duplication. This kind of modeling is not only more accurate in that one person was an employee on two different occasions, but it also provides a form of auditing trail for that person. If you store the <code>Employee</code> reference, you can still use either the person or the employee id to search for data. If you wanted to see what orders this specific employee had filled in, you can search using either the employee id which would get the orders for this version of the employee only, or you could match based on the person id and see what orders that person had ever filled in as either employee instance. This also reflects the real world better since there is only ever one person, but they could have multiple periods as an employee. </p>
<h4>Modeling with JPA</h4>
<p>It is fairly easy to model the basic composition in JPA by adding a <code>@ManyToOne</code> annotation to the entity reference (in this case the person). </p>
<p>If you plan on creating subclasses that are backed by different entities (i.e. <code>PersonCustomer</code> and <code>CompanyCustomer</code>) then you have to choose between different inheritance strategies. If there only a few differences between subclasses, you can probably just use a single table. If there are bigger differences between the subclasses, you might want to use a joined table inheritance strategy while keeping the core attributes of the parent class in the main table. </p>
<p>For legacy databases, you could be faced with the problem that the referenced entity id, such as the company or person id in the customer subclass, is stored in the same field in the database record. You can use the same field name for the reference in the subclasses and JPA will work with it.</p>
<pre name="code" class="java">
public class PersonCustomer extends AbstractCustomer {

  @ManyToOne
  @JoinColumn(name="REF_ID")
  private Person person;

}

public class CompanyCustomer extends AbstractCustomer {

  @ManyToOne
  @JoinColumn(name="REF_ID")
  private Company company;

}
</pre>
<p>Obviously, this method eliminates the opportunity to use foreign keys since a foreign key cannot reference two different tables. New designs should not use this method for this reason even though JPA allows it. If you let JPA drop and create the tables for you, with Hibernate at least, you will end up with a foreign key on the <code>REF_ID</code> field to either the person or company table that will be incorrect when you assign the other subclass type to it. Through luck, it may not raise an error the first time around (if you happen to have an instance of one entity that has the same Id as the other entity type) but it will at some point.</p>
<p>If you really need this design, then you can just build the tables yourself without the foreign key, but you should use a separate field even though it means that each record will have blank field in it. With a separate or join table inheritance strategy, you have no choice but to use separate fields for the references.</p>
<h4>A technique with many uses</h4>
<p>This technique has many applications, but I haven&#8217;t really seen it discussed that much. Obviously, most published application examples (i.e. Pet store or my own Issue Tracker) are trivial or incomplete so they don&#8217;t really require this level of attention to modeling detail. However you start to find all sorts of places this technique can be used for larger domain models either to provide functionality needed now or a flexible design to meet future requirements. Obviously, we don&#8217;t want to use this for everything in case we want to extend any object in our model, but refactoring models once you have gone live can be problematic as it not only involves code refactoring, but database refactoring as well. Adopting this technique early (i.e. pre production) in places it is likely to be needed can save a lot of headaches later on.</p>
<p>As another example, let&#8217;s say you wanted to define a <code>Location</code> which is basically an address and a few other attributes. These locations can be used for all sorts of things in various places in the application. We already have an <code>Address</code> class used throughout our code and we can embed it in our <code>Location</code>.</p>
<pre name="code" class="java">
public class Location {

  @Embedded
  private Address address;

  private Date createdOn;
  private String description;

}
</pre>
<p>Half way through your project you find that since this location class is used everywhere, the needs have changed somewhat and in some places need to have a dynamic address that belongs to a person and needs to be updated when the persons address changes, and some places need a static fixed address that never changes (i.e. delivery address an order was sent to which never changes). </p>
<p>We can easily implement this by creating a <code>Location</code> class that is subclassed into the different implementations that source the address from different places.</p>
<pre name="code" class="java">

public abstract class Location {

  public Address getAddress();
  private String description;
  private Date createdOn;

}

public class FixedLocation extends Location {
  @Embedded
  private Address address;

  public Address getAddress() {
    return address;
  }
}

public class PersonLocation extends Location {

  @ManyToOne
  private Person person;

  public Address getAddress() {
    return person.getPrimaryAddress();
  }

}
</pre>
<p>Not only have we provided a solution for our fixed and dynamic address problem, since <code>FixedLocation</code> will store the address internally while the others will dynamically obtain the latest address from the <code>Person</code>, but we have provided a structure that will allow us to turn any entity into an address provider for our <code>Location</code> class. In some ways, we are using it as more of an adapter pattern since the address sources no longer have a common type. We are using an adapter pattern to make the different implementation sources fit with our <code>Location</code> interface.</p>
<p>I have found a number of uses for such compositions/adapters in places where inheritance would have severely limited my options or provided some difficult challenges,  and by implementing this concept I&#8217;ve been able to make my models far more flexible and be able to accommodate new needs quickly. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/02/16/using-composition-in-object-modeling/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Weld 1.0.1-CR2 is available</title>
		<link>http://www.andygibson.net/blog/index.php/2010/02/14/weld-1-0-1-cr2-is-available/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/02/14/weld-1-0-1-cr2-is-available/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 17:28:54 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[jsf]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=830</guid>
		<description><![CDATA[Dan Allen posted that the latest CR version of Weld is available. This should contain a number of bug fixes from the initial release of Weld, including the two problems I had with the request scope being available in EJB timeouts and problems with the ability to proxy stateless beans. This last bug was for [...]]]></description>
			<content:encoded><![CDATA[<p>Dan Allen <a href="http://in.relation.to/14291.lace">posted</a> that the latest CR version of Weld is available. This should contain a number of bug fixes from the initial release of Weld, including the two problems I had with the request scope being available in EJB timeouts and problems with the ability to proxy stateless beans. This last bug was for me rather crucial since there was no easy way to implement DAO (just data management) type components with transactional annotations that could be injected into business logic beans. Without that, you end up having to write your own transaction handling code. </p>
<p>Also in the comments of the announcement, Max Anderson notes that the nightly builds of JBoss Tools 3.1 now supports CDI auto completion and JSF 2.0. I had a very quick look at it yesterday and it looks promising. I also tried it out with the latest JBoss 6 snapshot and am very pleased to say that the redeployment times on JBoss 6 are much faster and more in line with the performance on  Glassfish which is something I have raved about. </p>
<p>I&#8217;ll be looking at it some more and probably write up a couple of tutorial posts. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/02/14/weld-1-0-1-cr2-is-available/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LA X / What Kate Does</title>
		<link>http://www.andygibson.net/blog/index.php/2010/02/13/la-x-what-kate-does/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/02/13/la-x-what-kate-does/#comments</comments>
		<pubDate>Sat, 13 Feb 2010 15:28:34 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Lost]]></category>
		<category><![CDATA[tv]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=827</guid>
		<description><![CDATA[By now, the repetitions that we have seen across several seasons are coming thick and fast, another Lostie faces a &#8216;test&#8217; and fails, Kate almost ends up delivering Claires baby, Sayid is strapped to a bed and electrocuted and tortured and we have another woman who comes to the Island pregnant, delivers a baby which [...]]]></description>
			<content:encoded><![CDATA[<p>By now, the repetitions that we have seen across several seasons are coming thick and fast, another Lostie faces a &#8216;test&#8217; and fails, Kate almost ends up delivering Claires baby, Sayid is strapped to a bed and electrocuted and tortured and we have another woman who comes to the Island pregnant, delivers a baby which is stolen and then she goes a delightful mix of crazy feral. When Kate tells Sawyer she never should have come after him, Sawyer asks &#8220;Which time?&#8221;. Even the characters are pointing out the repetition.<br />
<span id="more-827"></span><br />
After 6 seasons, our mad Lost watching skillz have been so honed we should know that whenever a document is shown with a date on it&#8217;s usually important, and the ultrasound was no different as any parent would know. I missed it first time round but a quick rewind on the DVR shows the date to be October 22nd 2004, one month after the original flight 815 flew. </p>
<p>I don&#8217;t plan on doing blow by blow recaps since there are plenty around the web and I don&#8217;t have time so consider this some general thoughts over the last two episodes, LA X parts 1 and 2 and What Kate Does. I have some concerns over this whole alternate timeline/sideways flash. Incidentally, note how when transitioning between the main and alternate timeline we have a sucking jet engine sound as opposed to the sucking whoosh sound we had with the flashbacks for the first few seasons. The alternate time, and I&#8217;m not sure that is what it is, but let&#8217;s stick with that for now, has the losties landing in LAX and the island underwater. To me, that says that the bomb never went off and as a result, &#8216;the incident&#8217; was the unhindered drilling at the swan hatch that probably ended up causing the Island to sink. In the main timeline, the losties on flight 815 crashed, fought the others, went back in time and blew up the swan hatch before the incident. Miles commented in &#8220;The Incident&#8221; whether anyone had thought that setting the bomb off caused the events of their future (the swan being built and their plane crashing). This solution not only makes sense, but is paradox free, and yet the writers in their pod cast last week said that the island sinking was because the bomb went off which is quite annoying. </p>
<p>So far, we have seen in the alternative timeline how things are similar, but different in small and subtle ways. I&#8217;m a proponent of Whatever Happened, Happened as opposed to the idea that the losties can change their future (and therefore their past). Once you open the door for alternate timelines you open the door for multiple timelines. Furthermore, the additional timeline would have always existed regardless of the actions of the losties on the Island so it really doesn&#8217;t make sense as to why we are seeing this particular timeline. There are probably timelines where 815 crashed on take off and Jack is a drug addicted rock star, Locke is a marathon runner and Charlie became a priest. Why show us this timeline? I think the answer lies in the fact that our losties in this timeline have some kind of link of conciousness to the main timeline as we see them have bouts of recognition and familiarity with the main time line. In LA X, I thought the writers were just messing with us in the initial scenes were we see Jack on 815 looking disoriented. However, What Kate Does, they make those links stronger. The name Aaron just pops into Claires head, Kate and Jack have a moment of recognition as she drives off in the taxi, and the friendship of Claire and Kate probably made it that much easier for Kate to be more sympathetic to Claire to go and help her. I therefore think that the writers will somehow pull these two timelines together somehow and the introduction of the new timeline is not accidental and arbitrary. </p>
<p>It is also worth noting that there might only be a single timeline and the start of LA X is where the &#8216;main&#8217; timeline is leading to. If you ignore the &#8216;main&#8217; timeline on the island, we are seeing the end of lost, i.e. what happens to the 815&#8242;ers if they never crash. It could be that the final episodes show us how the main timeline leads up to the start of the LA X &#8216;alternate&#8217; timeline. This is possible if you consider that the island moves through time, although it mostly seems to move back in time which I think is relevant. If the losties start moving back in time as soon as they crash on the Island, the Island isolates them from the rest of the world as they pass back in time, therefore there won&#8217;t be two Jacks in the timeline because alternate Jack is travelling on a plane on October 22nd 2004 while main timeline Jack is shifting slowly back in time on an Island which will never cross paths with main timeline Jack. Perhaps that is how the island avoids detection, it moves through time and only stays in places where it knows there is nobody looking if you go for the idea of being able to see all time at once.</p>
<p>Anyway, I give the writers a 50/50 chance of pulling this all together in a sensible way. The fact that they already introduced a paradox regarding the bomb going off and sinking the island and the cherry picking of alternative universes is a bad sign though. Of course, we could be mis-interpreting this completely and the alternative story is very relevant to the main story and will merge seamlessly.</p>
<p>For a while there, I forgot it was a Kate centric story which usually means it blows, it&#8217;s not actually the Kate centric story that blows, it&#8217;s just that more screen time reminds us of how Kate is like the flame that Sawyer and Jack both fly close to. After 6 seasons, I&#8217;m sure there is going to be some allegory to how Kate is the axle that keeps the Jack and Sawyer wheels on the same track without which they would both fly off in different directions. However, after 6 seasons it&#8217;s hard to imagine that either of them would be interested in someone who changes her mind more often than her underwear (it&#8217;s an island people, there isn&#8217;t a lot of underwear). </p>
<p>WKD also introduced a few new mysteries, what did Kate do? She tells the garage mechanic she was wanted for murder, then tells Claire she&#8217;s innocent, which I might actually believe. It seems that so far, people in this timeline are much nicer. The interaction between Locke and Boone, and Locke and Jack was enjoyable to watch, even hinting there there is a mutual respect of each others beliefs in science and faith and even that they both have a healthy dose of each. Kate might even be innocent of all charges, Hugo thinks he&#8217;s lucky, and while Sawyer may not be squeaky clean, I think he&#8217;s in a much better place morally. I think Sawyer gave Hugo a genuine warning as opposed to the warning that was the opening moves of a con like he did in &#8220;Every Man For Himself&#8221;. Charlie is the only one who it seems is not better off, even to the point that in the alternate timeline, he is still destined for death by suffocation. The motto for Season 6 is Destiny Found, is this their destiny? Is all this about getting them to the point where the can continue onwards?</p>
<p>I was also very surprised that there actually was a family that Claire was supposed to meet. I suspected that the psychic knew the flight would go down and Claire would have no choice but to raise the baby instead of it being raised by another. Why else would he be so specific about the flight? Of course, this is the alternative timeline and he may have actually arranged someone to adopt Aaron since the plane wouldn&#8217;t be crashing. Unfortunately, I think &#8220;It&#8217;s an alternative timeline&#8221; is going to be the new scapegoat for any weird changes or unanswered questions. We still have to address the issue of &#8216;fake&#8217; psychic Richard Malkin and his daughter Charlotte coming back to life screaming about John Locke.</p>
<p>Here&#8217;s a thought, the idea is that around October 22nd 2004, the timelines split or separated which introduced changes in the timelines. Let&#8217;s go back to the old mystery of the changing photographs and their frames in Mrs Gardner&#8217;s house when Miles comes to do his ghostbusting bit. That took place around the time the wreckage was supposedly found which could put it around a month after the crash. Perhaps these changes are a result of the same event that caused the splitting timelines on 22nd October 2004, we just didn&#8217;t realize it at the time. </p>
<p>It seems Locke gets back in on the action next week, and he might be up for manipulating Sawyer. I&#8217;m hoping that the story arc doesn&#8217;t have Sawyer end up the way he came onto the island. Prior to the crash, Sawyer had been manipulated into killing Frank Duckett by Hibbs who took advantage of the tragedy in his life. I&#8217;m hoping fake Locke doesn&#8217;t use the same mechanims to manipulate Sawyer into doing something stupid.</p>
<p>Still lots of mysteries to go, with new ones being added, and in true Lost fashion, most answered mysteries result in the addition of new ones. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/02/13/la-x-what-kate-does/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>(One of the) Best Burgers Ever</title>
		<link>http://www.andygibson.net/blog/index.php/2010/01/14/best-burger-ever/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/01/14/best-burger-ever/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 02:24:30 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[personal]]></category>
		<category><![CDATA[food]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=808</guid>
		<description><![CDATA[Believe it or not, but I find Applebees burgers to be the best burgers I have ever tasted! This may be heresy coming from a self confessed foodie, but hear me out. Usually, I find burgers from chains fairly throw away affairs, you get it, eat it, it&#8217;s hot, it probably has some nice toppings, [...]]]></description>
			<content:encoded><![CDATA[<p>Believe it or not, but I find Applebees burgers to be the best burgers I have ever tasted! This may be heresy coming from a self confessed foodie, but hear me out. Usually, I find burgers from chains fairly throw away affairs, you get it, eat it, it&#8217;s hot, it probably has some nice toppings, and you&#8217;re done. However, I don&#8217;t know whether it is the new line of &#8220;Real Burgers&#8221; they started doing months ago or if they just started making them better, but their recent burgers, particularly the A1 Steakhouse burger is just fantastic.</p>
<p>It comes on a lightly toasted bun, on which they put a drop of tangy A1 sauce and a creamy mayonnaise type dressing and plenty of fried onion straws. Now, if they&#8217;ve done it properly the burger should have some pink to it but still be warm throughout and that is when you get a good juiciness to the burger. They&#8217;ve been a little bit inconsistent recently and not asked how I want the burger and sometimes I get it well done and other times I get it nice and pink-ish. Since they can&#8217;t decide on a default, just tell them you want it pink and warm throughout (medium as opposed to medium well).</p>
<p>When this thing arrives, you start by biting into the soft bun and then you plough through the onion straws which have a mildly crunchy fried texture and a slight sweetness from the onions. You then hit the soft mild (swiss?) cheese and the burger which is a patty of tender juicy beefiness with just the right crumbly texture to the burger and a juiciness that drips. In there somewhere is the tangyness of A1 which punctuates the other flavors now and again. These things are awesome and they are on the 2 for $20 menu (2 meals plus an appetizer for $20). I think they are grinding their meat fresh, and gently forming the patty so the meat doesn&#8217;t form into a tight beef puck which just gets tough. </p>
<p>Next time I plan on broadening my horizons and trying one of their other burgers (cowboy or cheese burger) to see if it is as good. The A1 burger doesn&#8217;t have bacon on it which normally should be an instant penalization, but regardless this burger is still so tasty. I used to have the cowboy burger (well done) but the toppings (onion rings, bacon and BBQ sauce) were tastier than the burger. I plan on trying it with the new improved burgers since perfect burger plus fantastic toppings could lead to an epic event!</p>
<p>(<b>Update</b> &#8211; 8th Feb 2010 &#8211; After taking my brother and Sister in law there, we found that a) They are thoroughly inconsistent, with the better burgers being the exception not the rule. b) Their service was crappy as they delivered appetizers, salad and the burgers in the space of 2 minutes after letting us wait for 10 minutes (Their problem, we planned on having a long meal and working our way through the cocktail menu). Also, they just got usurped by Michael Symon). </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/01/14/best-burger-ever/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with JSF 2.0 and CDI part 3 &#8211; Events</title>
		<link>http://www.andygibson.net/blog/index.php/2010/01/11/getting-started-with-jsf-2-0-and-cdi-part-3/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/01/11/getting-started-with-jsf-2-0-and-cdi-part-3/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 13:26:45 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[articles]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=728</guid>
		<description><![CDATA[Last time we looked more in depth at CDI and how we can define beans and inject them into other beans. This time we are going to look at how we can use events to decouple the handling of actions in the system.


As a refresher, in our last part, we had an application that obtained [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/">Last time</a> we looked more in depth at CDI and how we can define beans and inject them into other beans. This time we are going to look at how we can use events to decouple the handling of actions in the system.<br />
<span id="more-728"></span></p>
<p>
As a refresher, in our last part, we had an application that obtained a list of items, validated them and took a specific action when an invalid item was found. Lets say in the future we want to expand our system to handle all sorts of things happening when we find an invalid item. This could range from an email being sent, changes made to other data (i.e. an order canceled) or storing a list of rejections in a file or database table. To completely decouple the implementation we can use events. Events are raised by the event producer and subscribed to by event observers. Like most of CDI, event production and subscription is type safe and allows qualifiers to determine which events observers will observe.
</p>
<p>
Luckily we don&#8217;t have to change our application much to implement this, we just provide an implementation of the <code>ItemErrorHandler</code> that raises the event when it handles the item. We will inject an instance of the Item error handler called <code>EventErrorHandler</code> and create a <code>@Notify</code> qualifier to select it for injection.
</p>
<pre name="code" class="java">
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface Notify {}
</pre>
<pre name="code" class="java">
@Notify
public class EventItemHandler implements ItemErrorHandler {

    @Inject
    private Event&lt;Item&gt; itemEvent;

    public void handleItem(Item item) {
        System.out.println("Firing Event");
        itemEvent.fire(item);
    }
}
</pre>
<p>In this item handler, we inject an instance of an Event where the event payload will be an <code>Item</code>. The event payload is the state data passed from the event producer to the event observer which in this case passes the rejected Item. When the invalid item is handled, we fire the event and pass in the invalid item we received. This event based item handler is injected the same as any other item handler would be so we can swap it in and out whenever we need to and also can substitute it during testing.  We created a <code>@Notify</code> qualifier annotation to identify this error handler for injection and can use it in our item processor by adding it to the injection point.</p>
<pre name="code" class="java">
    @Inject
    @Notify
    private ItemErrorHandler itemErrorHandler;
</pre>
<p>If we deploy this now, we will see that when the item processor hits invalid items, the event based item error handler fires the event. Currently though we don&#8217;t have anything observing the event. We can fix this by creating an observer method which is the only thing needed to observe an event. We can still re-use our existing item processors by adding an event observer method to the implementations which just calls the error handler method. For example, to make our <code>FileErrorReporter</code> respond to the event, we add the following observer event.</p>
<pre name="code" class="java">
public class FileErrorReporter implements ItemErrorHandler,Serializable {

    public void eventFired(@Observes Item item) {
        handleItem(item);
    }
    ....
    ....
</pre>
<p>If you run the application now, you will see that the events are fired on the invalid objects, and the item information is being saved when this event is fired. You will also note that the lifecycle events are being observed. </p>
<div class="codeblock">
INFO: Firing Event<br />
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@1f84b46 [Value=34, Limit=7] to file<br />
INFO: Closing file error reporter<br />
INFO: Firing Event<br />
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@2656da [Value=89, Limit=32] to file<br />
INFO: Closing file error reporter
</div>
<p>Note that the file error reporter bean is created each time the event is raised which may or may not be what we want. In this case, we don&#8217;t want to create the bean new each time since we don&#8217;t want to open and close the file for each item. We still want to open the file at the start of the process, and then close it once the process it completed. In this case, we need to consider the scope of the <code>FileErrorReporter</code> bean which doesn&#8217;t have a scope defined. When no scope is defined, CDI defaults it to the default pseudo dependent scope. What this means in practice is that the bean is created and destroyed over a very short space of time, typically over a method call. In our case here, the bean is created and destroyed for the duration of the event being fired. To fix this, we need to lengthen the scope of the bean by manually adding a scope annotation. We will make this bean <code>@RequestScoped</code> so once the bean is created the first time the event is fired, it will remain created for the duration of the request. Also, for any injection points that this bean is qualified to be injected to, the same bean instance will be injected. Here is the log when we make our scope change to the bean. Note that the bean is still only created when the event is fired. </p>
<div class="codeblock">
INFO: Firing Event<br />
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@1380c08 [Value=34, Limit=7] to file<br />
INFO: Firing Event<br />
INFO: Saving eedemo.Item@1b44f96 [Value=89, Limit=32] to file<br />
INFO: Closing file error reporter
</div>
<p>Let&#8217;s take the events example a little further. Right now we are observing any event for an item but chances are, there may be different types of events in the system for the items. We want to be specific in which observers subscribe to which events. Luckily CDI provides for this in a similar manner to how we determine suitable beans for injection points by using typing and qualifiers. </p>
<p>First, lets create a problem for ourselves by firing events off for each item we validate by adding the following code to the item processor.</p>
<pre name="code" class="java">
    @Inject
    private Event<Item> processorEvent;

    public void execute() {
        List<Item> items = itemDao.fetchItems();
        for (Item item : items) {
            processorEvent.fire(item);
            if (!itemValidator.isValid(item)) {
                itemErrorHandler.handleItem(item);
            }
        }
    }
</pre>
<p>This will fire an event for each item we process, but we don&#8217;t want the invalid item handler to subscribe to each of those events. If we do, we will see output like the following : </p>
<div class="codeblock">
INFO: Creating eedemo.EventItemHandler_$$_javassist_748<br />
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file<br />
INFO: Creating eedemo.EventItemHandler<br />
INFO: Firing Event<br />
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file<br />
INFO: Saving eedemo.Item@1087300 [Value=4, Limit=37] to file<br />
INFO: Saving eedemo.Item@11674c9 [Value=24, Limit=19] to file<br />
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file<br />
INFO: Firing Event<br />
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file<br />
INFO: Closing file error reporter
</div>
<p>For each item, the file item handler observer is being called for each item because we aren&#8217;t distinguishing the kind of events fired when the item is processed and the kind of event fired when an invalid item is found. To differentiate between them we will create an <code>@Invalidate</code> qualifier to qualify the event for invalid items. This annotation will be placed on the event injection point and also on the observation point method. </p>
<pre name="code" class="java">
@Notify
@RequestScoped
public class EventItemHandler implements ItemErrorHandler {

    @Inject @Invalidated
    private Event<Item> itemEvent;

    public void handleItem(Item item) {
        System.out.println("Firing Event");
        itemEvent.fire(item);
    }
}
</pre>
<pre name="code" class="java">
@Save
@RequestScoped
public class FileErrorReporter implements ItemErrorHandler,Serializable {

    public void eventFired(@Observes @Invalidated Item item) {
        handleItem(item);
    }

    ....

}
</pre>
<p>If you run the code now, you will see that we no longer call the file save handler for each item, even though we are firing the event for each item.</p>
<div class="codeblock">
INFO: Firing Event<br />
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@1e3aa22 [Value=34, Limit=7] to file<br />
INFO: Firing Event<br />
INFO: Saving eedemo.Item@172940f [Value=89, Limit=32] to file<br />
INFO: Closing file error reporter
</div>
<p>You can add an event observer to the item processor just to see the events are still being raised and can be observed.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    ....

    public void observeItemEvent(@Observes Item item) {
        System.out.println("Item event observed for item "+item);
    }
}
</pre>
<p>This will print a message whenever an event is fired so you can see that there is a difference between the two event subscribers and also that the more general version of the observer sees all events related to the item.</p>
<p>Events are a great way to decouple parts of the system in a modular fashion as you can add pieces that will subscribe to events with the event producer unaware of the observer as opposed to the even producer having to call the observer manually when events are not used. For example, if someone updates an order status, you could add events to email the sales rep, or notify an account manager if a tech support issue is open for more than a week. These kinds of rules can be implemented without events, but events make it easier to decouple the business logic. Additionally, there is no compile or build time dependency and you can just add modules to your application and they will automatically start observing and producing events. Additionally, observers and producers know nothing about each other, nor do they require any configuration for them to do so.</p>
<h4>Scheduling the Processing</h4>
<p>One last tidbit before we move on to creating CDI driven JSF apps is that for now we are running our code from a button in a JSF page but typically this is something that would get fired off on a regular basis. With the power of the EJB 3.1 scheduler we can do just that in a new class with few lines of code. We&#8217;ll create a new stateless EJB into which  we&#8217;ll inject our <code>ItemProcessor</code> and add a method to call the <code>execute()</code> method which will be called at a scheduled time.</p>
<pre name="code" class="java">
@Stateless
public class ScheduledProcessor {

    @Inject
    private ItemProcessor itemProcessor;

    @Schedule(hour="07",minute = "00")
    public void execute() {
        System.out.println("executing scheduled job!");
        itemProcessor.execute();
    }
}
</pre>
<p>This makes use of the new EJB 3.1 <code>@Schedule</code> annotation and will schedule this method to be called every morning at 7am. You could make it on the hour every hour, or you could use the EJB timer service to implement your own timeout. We inject the same <code>ItemProcessor</code> implementation we have been using all along and call the <code>execute()</code> method. That is a pretty powerful transformation letting us re-use our existing code and easily incorporating EJB services with POJO managed beans into an EJB needing only a few lines of code.</p>
<p><small><b>Note</b> : If you actually implement this and run it, it won&#8217;t work because of a Weld 1.0 bug whereby the request scope isn&#8217;t active during calls to EJB timeouts (see <a href="https://jira.jboss.org/jira/browse/WELD-15">here</a> for details) so you&#8217;ll have to wait until Weld 1.01 which should be out fairly soon.</small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/01/11/getting-started-with-jsf-2-0-and-cdi-part-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Understanding Nested Conversations</title>
		<link>http://www.andygibson.net/blog/index.php/2010/01/10/understanding-nested-conversations/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/01/10/understanding-nested-conversations/#comments</comments>
		<pubDate>Mon, 11 Jan 2010 03:04:53 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[seam]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jee]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=778</guid>
		<description><![CDATA[I had a bit of epiphany on the subject of nested conversations the other day when I was thinking about them and thought I&#8217;d share. I think nested conversations have been a little misunderstood with people unsure of how to use them, myself included, but I think I have found the best way to think [...]]]></description>
			<content:encoded><![CDATA[<p>I had a bit of epiphany on the subject of nested conversations the other day when I was thinking about them and thought I&#8217;d share. I think nested conversations have been a little misunderstood with people unsure of how to use them, myself included, but I think I have found the best way to think of them. </p>
<p>In summary, nested conversations do for regular conversations what conversations do for session scope. With session scope, you cannot have mutliple instances of a named variable, you have to put each variable instance in its own conversation where it will be unique. However, if you want to have multiple instances of a named variable within the conversation, again, you cannot and you have the same problem you have with the session scope, that variables must be unique. Therefore  you have to have each variable in its own nested conversation under the main conversation the same way we had the top level conversation under the session scope.</p>
<p>In some weird web app which lets you pick a person and then put costumes on them, you might have a main page where you select the person, and then in separate browser windows you can pick different outfits for that person. You put the selected person value in a different conversation so the value of <code>#{selectedPerson}</code> is local to the conversation allowing multiple selected people in different browser windows. This overcomes the limitations of the session which allows only one value for <code>#{selectedPerson}</code></p>
<p> However, if you had that conversation open in multiple windows or tabs so you can compare different costumes on that person, there would only be one value of <code>#{selectedCostume}</code> for the conversation shared between all windows. As you select a costume in one window, it would affect all the other windows as they share the variable in that conversation. Using nested conversations would allow the conversation to have different values for the selected costume under the same parent conversation with the same selected person.</p>
<p>Taking it further you could select the person in the top level conversation, select the costume in the nested conversation, and then you could have multiple windows open with further nested conversation letting you pick different shoes to go with that costume. Also, if you change the person in the top level conversation, it will change the selected person for all windows using that conversation or any of its nested conversations.</p>
<p>I&#8217;m not sure there is a great need for nested conversations, I&#8217;ve never really used them or found the need and I don&#8217;t think users open that many browser windows or tabs to create different logic paths within a conversation. I think it is acceptable to limit the data isolation to a single conversation level.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/01/10/understanding-nested-conversations/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Christmas Hiatus Over</title>
		<link>http://www.andygibson.net/blog/index.php/2010/01/07/christmas-hiatus-over/</link>
		<comments>http://www.andygibson.net/blog/index.php/2010/01/07/christmas-hiatus-over/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 04:35:13 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[personal]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[food]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=762</guid>
		<description><![CDATA[Well, 2009 is done with and we are plunging headlong into 2010. Being European, I like to take a good week off around Christmas and New Year and with relatives here for Christmas I haven&#8217;t spent much time on work or blogging. So for those that have sent emails, apologies for the delay and I&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>Well, 2009 is done with and we are plunging headlong into 2010. Being European, I like to take a good week off around Christmas and New Year and with relatives here for Christmas I haven&#8217;t spent much time on work or blogging. So for those that have sent emails, apologies for the delay and I&#8217;ll get back to you this week/weekend. I have a few posts lined up including part 3 of the CDI articles covering Events, I&#8217;ll probably do one introducing conversations and then I&#8217;ll start writing on creating some real world apps with JSF and CDI. If anyone has anything they&#8217;d like to see in these articles, let me know.</p>
<p>Also, I have a couple of food posts almost completed as Christmas was full of good food and recipes that inspired me to blog about it (Must have been watching Julie &#038; Julia in the New Year that did it).</p>
<p>Happy New Year all!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2010/01/07/christmas-hiatus-over/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with CDI part 2 &#8211; Injection</title>
		<link>http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/</link>
		<comments>http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 13:45:20 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[articles]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=706</guid>
		<description><![CDATA[In  part 1, we looked at creating a JEE 6 application with Netbeans using JSF and CDI running on Glassfish. Now we&#8217;ll take a closer look at using CDI for managing dependencies in a Java EE 6 environment.

Last Time
Last time we looked at setting up the development environment and creating our EE6 application in [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/index.php/2009/12/16/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/"> part 1</a>, we looked at creating a JEE 6 application with Netbeans using JSF and CDI running on Glassfish. Now we&#8217;ll take a closer look at using CDI for managing dependencies in a Java EE 6 environment.<br />
<span id="more-706"></span></p>
<h4>Last Time</h4>
<p>Last time we looked at setting up the development environment and creating our EE6 application in Netbeans and deploying it to Glassfish v3. This time, we&#8217;ll skip straight to writing code which can be put into either a new Netbeans project using the previous tutorial, or you can use the existing project and just add the new code.</p>
<h4>The &#8216;I&#8217; in CDI</h4>
<p>CDI is an API for injecting contexts and dependencies  which is the part we&#8217;ll turn our attention to now. In Seam and Spring dependencies worked mostly by naming beans and binding them to their injection points by their name. So far we have only referenced a managed bean by name from the JSF page when we defined the name for the bean using the <code>@Named</code> annotation. The primary role of the <code>@Named</code> annotation is to define the bean for the purpose of resolving EL statements within the application, usually through the JSF EL resolvers. Injection <i>could</i> be performed by using names, but this was not how injection in CDI was meant to work since CDI gives us a much richer way to express injection points and the beans to be injected into them.</p>
<p>Let&#8217;s look at an example which is somewhat contrived. We have a dao that returns a list of objects that need validating, and for invalid ones, we take a certain action.  Here&#8217;s the definition for the item.</p>
<pre name="code" class="java">
package eedemo;

public class Item {

    private int value;
    private int limit;

    @Override
    public String toString() {
        return super.toString() + String.format(" [Value=%d, Limit=%d]", value,limit);
    }

    /*
    getters and setters omitted
    */
}
</pre>
<p>The <code>ItemDao</code> interface defines how we get the list of item objects. In this test application we anticipate using multiple implementations so we will code to interfaces. </p>
<pre name="code" class="java">
public interface ItemDao {

    List&lt;Item&gt; fetchItems();

}
</pre>
<p>The <code>ItemProcessor</code> is our main class that we will inject our beans into and execute the process from. For now, we will start with the Dao and look at how we will inject it into our processor bean.</p>
<pre name="code" class="java">
import java.util.List;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    private ItemDao itemDao;

    public void execute() {
      List&lt;Item&gt;  items = itemDao.fetchItems();
      for (Item item : items) {
          System.out.println("Found item "+item);
      }
    }
}
</pre>
<p>We&#8217;ll start with a simple Dao that just creates a list of items and returns a fixed list of items.</p>
<pre name="code" class="java">
public class DefaultItemDao implements ItemDao {

    public List&lt;Item&gt; fetchItems() {
        List&lt;Item&gt; results = new ArrayList&lt;Item&gt;();
        results.add(new Item(34, 7));
        results.add(new Item(4, 37));
        results.add(new Item(24, 19));
        results.add(new Item(89, 32));
        return results;
    }
}
</pre>
<p>In order to inject the <code>DefaultItemDao</code> into our <code>ItemProcessor</code> we add the <code>javax.inject.Inject</code> annotation to the <code>ItemDao</code> field to indicate that this field is an injection point.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    @Inject
    private ItemDao itemDao;

    ...
}
</pre>
<p>Finally, we need some way to call the <code>execute()</code< method on the <code>ItemProcessor</code>. We can run this in a SE environment, but for now we&#8217;ll keep it in a JSF page. We&#8217;ll add a new page with a button to call the execute method called <code>process.xhtml</code>.</p>
<pre name="code" class="xml">
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">
    <h:head>
        
    </h:head>
    <h:body>
        <h:form>
        <h:commandButton action="#{itemProcessor.execute}" value="Execute"/><br/>
        </h:form>
    </h:body>
</html>
</pre>
<p>If you open up the page at <a href="http://localhost:8080/ee6demo/faces/process.xhtml">http://localhost:8080/ee6demo/faces/process.xhtml</a> you will see just a button that when clicked lists the items from our default Dao implementation in the console.</p>
<div class="codeblock">
INFO: Found item eedemo.Item@23cbc6 [Value=34, Limit=7]<br />
INFO: Found item eedemo.Item@a40279 [Value=4, Limit=37]<br />
INFO: Found item eedemo.Item@19e6292 [Value=24, Limit=19]<br />
INFO: Found item eedemo.Item@1597bc4 [Value=89, Limit=32]
</div>
<p>We created a class which implements the <code>ItemDao</code> interface and when the application was deployed our managed beans in the module were processed by the CDI implementation (again because of the <code>beans.xml</code> file in the module. Our <code>Inject</code> annotation specifies that we want to inject a managed bean into that field and the only thing we know about the bean to inject is that it must implement <code>ItemDao</code> or some subtype of that interface. In this case, the <code>DefaultItemDao</code> class fits the bill perfectly.</p>
<p>Let&#8217;s say we add another Dao class to our application which also implements the <code>ItemDao</code> interface, now the choice isn&#8217;t so clear as to which bean we want to inject.</p>
<pre name="code" class="java">
public class AnotherItemDao implements ItemDao {

    public List&lt;Item&gt; fetchItems() {
        List&lt;Item&gt; results = new ArrayList&lt;Item&gt;();
        results.add(new Item(99, 9));
        return results;
    }

}
</pre>
<p>We now have two classes the implement this interface and predictably, Weld gives us an ambiguous dependency error meaning that it cannot determine what bean to use for that injection point. Most, if not all of the errors that can occur with regards to CDI injection in Weld are reported at deployment time, even down to whether beans are missing a Serializable implementation.</p>
<div class="codeblock">
Caused by: org.jboss.weld.DeploymentException: Injection point has ambiguous dependencies.<br />
Injection point: field eedemo.ItemProcessor.itemDao; Qualifiers: [@javax.enterprise.inject.Default()]; </p>
<p>Possible dependencies: [eedemo.AnotherItemDao, eedemo.DefaultItemDao]
</p></div>
<p>We could make our <code>itemDao</code> field in the item processor a type that matches one of the implementation types (<code>AnotherItemDao</code> or  <code>DefaultItemDao</code>) since it would then match one and only one class type. However, then we would lose the benefits of coding to an interface and find it harder to change implementations without changing the field type. A better solution is to instead look at CDI Qualifiers.</p>
<h4>Qualifiers</h4>
<p>A CDI qualifier is an annotation that can be applied at the class level to indicate the kind of bean the class is, and also at the field level (among other places) to indicate what kind of bean needs to be injected at that point.</p>
<p>When CDI inspects an injection point to find a suitable bean to inject it takes not only the class type into account, but also any qualifiers. Without knowing it, we have already used one qualifier which is the default qualifier called <code>@Any</code>. Let&#8217;s create a <code>@Demo</code> qualifier which we can apply to our <code>DefaultItemDao</code> implementation and also to the injection point.</p>
<pre name="code" class="java">
package eedemo.qualifier;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface Demo {

}
</pre>
<p>First, we&#8217;ll add this qualifier to our default dao implementation at the class level.</p>
<pre name="code" class="java">
@Demo
public class DefaultItemDao implements SomeDao {

    public List&lt;Item&gt; fetchItems() {
..
..
</pre>
<p>If you save and deploy this file now, you may notice that we don&#8217;t have any errors, and if you go to the web page and click the execute button, you can see that in the console, it displays the list of items from the <code>AnotherItemDao</code> dao (remember we annotated the <code>DefaultItemDao</code> implementation but not the injection point). By adding the <code>Demo</code> qualifier to the default dao implementation, we made the other implementation a more suitable match for the injection point as it matched on type and on qualifiers and the <code>DefaultItemDao</code> has a qualifier that is not on the injection point making it less suitable.</p>
<p>If we add the <code>Demo</code> annotation to the injection point and deploy it, when we click our button we use the default implementation again. This is because we are matching based on type and qualifiers and the <code>DefaultItemDao</code> is the only bean with both the correct type and the <code>Demo</code> annotation.</p>
<h4>Alternative Injection Methods</h4>
<p>There are multiple ways to define an injection point on the injected class. So far we have annotated the fields that will reference the injected object. You do not need to provide getters and setters for field injection. If we wish to create immutable managed beans with final fields, we can use injection in the constructor by annotating the constructor with the <code>Inject</code> annotation. We can then apply any annotations to constructor parameters to qualify beans for injection (of course, each parameter has a type that can assist in qualifying beans for injection). A bean may only have one constructor with injection points defined, but it may implement more than one constructor.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    private final ItemDao itemDao;

    @Inject
    public ItemProcessor(@Demo ItemDao itemDao) {
        this.itemDao = itemDao;
    }
}
</pre>
<p>We can also call an inialization method which can be passed the beans to be injected.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    private ItemDao itemDao;

    @Inject
    public void setItemDao(@Demo ItemDao itemDao) {
        this.itemDao = itemDao;
    }
}
</pre>
<p>While in the above case we used the setter method for initialization we can create any method and use it for initialization with as many beans as we want in the method call. We can also have multiple initialization methods in a bean. </p>
<pre name="code" class="java">
    @Inject
    public void initBeans(@Demo ItemDao itemDao,@SomeQualifier SomeType someBean) {
        this.itemDao = itemDao;
        this.bean = someBean;
    }
</pre>
<p>The same rules apply to bean matching regardless of how the injection point is defined, it will try and find the best match based on type and qualifiers and will fail on deployment if there are multiple matching beans or no matching beans for an injection point.</p>
<p>Let&#8217;s look at the other aspects of our application, we get a list of items, iterate through them and test each one and if it fails that test, we pass it on to an error handler. We&#8217;ll create an <code>ItemValidator</code> interface to determines whether an item is valid or not.</p>
<pre name="code" class="java">
public interface ItemValidator {
    boolean isValid(Item item);
}
</pre>
<p>We&#8217;ll expand our <code>ItemProcessor</code> class to incorporate the new feature.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    @Inject @Demo
    private ItemDao itemDao;

    @Inject
    private ItemValidator itemValidator;

    public void execute() {
      List&lt;Item&gt;  items = itemDao.fetchItems();
      for (Item item : items) {
          System.out.println("Item = "+item+" valid = "+itemValidator.isValid(item));
      }
    }
}
</pre>
<p>Our first implementation will be <code>DefaultItemValidator</code> which will simply test the limit against the value.</p>
<pre name="code" class="java">
public class DefaultItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() < item.getLimit();
    }
}
</pre>
<p>If we save our changes, go to our web page and click our button, in the console you will see that our items are being validated and the only valid item is where the value is less than the limit.</p>
<div class="codeblock">
INFO: Item = eedemo.Item@25dd89 [Value=34, Limit=7] valid = false<br />
INFO: Item = eedemo.Item@1f37ca2 [Value=4, Limit=37] valid = true<br />
INFO: Item = eedemo.Item@7b8d67 [Value=24, Limit=19] valid = false<br />
INFO: Item = eedemo.Item@18075da [Value=89, Limit=32] valid = false
</div>
<p>Now lets consider the scenario where we have a deployment to a different site that is more relaxed and considers an item invalid only if the value is more than twice the limit. We may want to have another bean that implements the validator interface for that logic.</p>
<pre name="code" class="java">
public class RelaxedItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() < (item.getLimit() * 2);
    }
}
</pre>
<p>Now we have an ambiguous dependency problem since we have two classes implementing the same interface. The only difference is based on deployment so for most deployments, we want to use the default, but for one deployment, we want to use the relaxed implementation. CDI offers the use of the <code>Alternative</code> annotation which lets you package multiple beans that match an injection point without ambiguity errors, and the bean to use is defined in the <code>beans.xml</code>. This means you can deploy both implementations in the same module with the only difference being the beans.xml definition which can change over different deployments. </p>
<pre name="code" class="java">

@Alternative
public class DefaultItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() < item.getLimit();
    }
}
</pre>
<p>and</p>
<pre name="code" class="java">
@Alternative
public class RelaxedItemValidator implements ItemValidator {

    public boolean isValid(Item item) {
        return item.getValue() < (item.getLimit() * 2);
    }
}
</pre>
<p>If we deploy our application now, we will get an unsatisfied dependency error since we defined the two matching beans as alternative but we didn't enable either of them in the <code>beans.xml</code> file.</p>
<pre name="code" class="java">
<beans
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <alternatives>
        <class>eedemo.RelaxedItemValidator</class>
    </alternatives>
</beans>
</pre>
<p>This tells CDI that for this deployment we want to use the <code>RelaxedItemValidator</code>. You can think of the alternative annotation as effectively disabling the bean making it unavailable for injection, but allowing the implementation to be packaged with the other beans. Adding it as an alternative in the <code>beans.xml</code> file effectively enables the bean making it available for injection. By moving this type of metadata to the <code>beans.xml</code> file, we can bundle different versions of the file with different deployments.</p>
<h4>Handling Invalid Items</h4>
<p>Continuing the example, invalid items are sent to the <code>ItemErrorHandler</code> as they are discovered.</p>
<pre name="code" class="java">
public interface ItemErrorHandler {
    void handleItem(Item item);
}
</pre>
<p>Let's start by implementing a fake handler that saves the item details to a file. We want to open the file before we start handling items, leave it open for the duration of the process as we add content to the file, and then close the file when we are done with our processing. We could manually add <code>initProcess()</code> and <code>finishProcess()</code> methods to the error reporter bean, but then we couldn't code to the interface since the caller would need to know about those class specific methods. We could add those same methods to the <code>ItemErrorReporter</code> interface but then we would have to unnecessarily implement those methods in every class that implements that interface. Instead, we can use some of the lifecycle annotations from the Managed Bean spec to call methods on the bean at certain points in the bean lifecycle. A <code>PostConstruct</code> annotated method is called when the bean has been constructed and any dependencies the bean has have been injected. Likewise, a <code>PreDestroy</code> annotated method is called just before the bean is disposed of by the container.</p>
<pre name="code" class="java">
public class FileErrorReporter implements ItemErrorHandler {

    @PostConstruct
    public void init() {
        System.out.println("Creating file error reporter");
    }

 @PreDestroy
    public void release() {
        System.out.println("Closing file error reporter");
    }

    public void handleItem(Item item) {
        System.out.println("Saving "+item+" to file");
    }
}
</pre>
<p>Our final change is to add the item error handling into our <code>ItemProcessor</code> bean.</p>
<pre name="code" class="java">
@Named("itemProcessor")
@RequestScoped
public class ItemProcessor {

    @Inject @Demo
    private ItemDao itemDao;

    @Inject
    private ItemValidator itemValidator;

    @Inject
    private ItemErrorHandler itemErrorHandler;

    public void execute() {
      List<Item>  items = itemDao.fetchItems();
      for (Item item : items) {
          if (!itemValidator.isValid(item)) {
              itemErrorHandler.handleItem(item);
          }
      }
    }
}
</pre>
<p>When we run this from our browser we see the following in the console ;</p>
<div class="codeblock">
INFO: Creating file error reporter<br />
INFO: Saving eedemo.Item@d8b01e [Value=34, Limit=7] to file<br />
INFO: Saving eedemo.Item@12a5e8 [Value=89, Limit=32] to file<br />
INFO: Closing file error reporter
</div>
<h4>Next Time</h4>
<p>Different application deployments might use different rules for handling invalid items. such as rejecting the item, to sending notifications to individuals or just flagging them or listing them in an output file. In addition, we may want to do a combination of these (reject an order, send email to the sales rep, and list it in a file).<br />
One great way to handle this kind of multi-faceted problem is using events which we'll look at next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Getting Started with JSF 2.0 and CDI in JEE 6 part 1</title>
		<link>http://www.andygibson.net/blog/index.php/2009/12/16/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/</link>
		<comments>http://www.andygibson.net/blog/index.php/2009/12/16/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 14:20:03 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[jee]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=647</guid>
		<description><![CDATA[Here's a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.

Getting Netbeans and JEE6
First download the latest version of Netbeans (at the time of writing 6.8 has just been released). Make sure the download version [...]]]></description>
			<content:encoded><![CDATA[<p>Here's a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.<br />
<span id="more-647"></span></p>
<h4>Getting Netbeans and JEE6</h4>
<p>First download the latest version of Netbeans (at the time of writing 6.8 has just been released). Make sure the download version you choose includes Glassfish V3 and java web and EE. Once downloaded, install it and get it up and running and we can start writing the application.</p>
<h4>Starting the Project</h4>
<p>Once Netbeans is up and running, start a new web project by clicking New Project and select the Java Web category and select a Web Application project and click next.</p>
<p>Give the new project a name (I called mine ee6demo) and a directory and click next. On the server settings, Glassfish v3 should already be selected so select next. In this tab, make sure Java Server Faces is selected and stick with the defaults in the lower panel that appears when you select it.</p>
<p>You can now click finish and Netbeans will create the project and open it up for you in the IDE. On the left you can see the project explorer and in the main tab you can see a file called index.html. Without doing anything, open the Run menu in the main menu and select "Run Main Project". After a moment of activity and console logging a web browser window should open up with the message "Hello From Facelets" which is exactly what we can see in the index.xhtml file. So far, we haven't done anything and we already have a working web application shell.</p>
<p>Just take a moment and look at the tabs on the left hand side, you should see Project,Files, and Services. Click on the services tab and expand the Servers node and you should see the Glassfish server we are using with a little green arrow on it indicating that the server is running. For now, we don't need this because we aren't actually going to deploy to the server again, no restarts and no manual deployments, so go back to the projects tab on the left.</p>
<h4>Adding some code</h4>
<p>In the projects tab, expand the "Source Packages" node and right click and select New->Java Class. Give the class the name <code>MessageServerBean</code> and a package name (I used <code>eedemo</code>). We annotate the class with the <code>javax.inject.Named</code> annotation and a single method to return a string.</p>
<pre name="code" class="java">
package eedemo;

import javax.inject.Named;

@Named
public class MessageServerBean {

    public String getMessage() {
        return "Hello World!";
    }
}
</pre>
<p>This a managed bean as defined by CDI which in Glassfish v3 is implemented using Weld from JBoss. One thing we need to do now is tell the server that this project is a module containing CDI beans. We add a file called <code>beans.xml</code> to the project in the WEB-INF folder. Right click on the WEB-INF folder in the project manager in the ee6Demo/Web Pages/folder and select New-&gt;XML Document. In the file name editor, just call it <code>beans</code>, <b>not</b> <code>beans.xml</code> as the IDE will add the xml extension for you and if you add the xml extension, the file will be called <code>beans.xml.xml</code> (I've often tripped myself up with that one!). Open the beans.xml file in the editor, and select all the text and delete it so it is an empty file.  You could alternatively just put <code>&lt;beans&gt;&lt;/beans&gt;</code>. (<b>Note</b> This file can be used to specify bean related information in xml so you aren't limited to annotations)</p>
<p>The last change is to edit the <code>index.xhtml</code> and replace the "Hello From Facelets" with our own text.</p>
<pre name="code" class="xml">
        Message is : #{messageServerBean.message}<br/>
        Message Server Bean is : #{messageServerBean}
</pre>
<p>Save it and go to your browser and refresh the page (<code><a href="http://localhost:8080/ee6demo/">http://localhost:8080/ee6demo/</a></code>). </p>
<pre class="codeblock">
Message is : Hello World!
Message Server Bean is : eedemo.MessageServerBean@xxxxxxx
</pre>
<p>You should now see the message from the bean displayed on the page. Now go back into your message bean and change the message to something else (I used <code>Hello From Weld!</code>), save the file and then refresh the browser. Your new message appears automatically since your application code has been hot deployed automatically by Netbeans . If you don't see your changes just give it a second and refresh again.</p>
<p>From the second line in our page you can see that the class name is <code>eedemo.MessageServerBean</code> and the bean is just a pojo. Even though this is JEE, there is no complex class hierarchy wrapped in layers of transactions, interceptors and all that 'Heavy' stuff you keep hearing about. </p>
<h4>What's going on?</h4>
<p>When the application is deployed, the presence of a <code>beans.xml</code> file signals that this module contains CDI managed beans so the classes on the path are scanned for CDI annotations. Our bean was annotated with the <code>@Named</code> annotation and so this class was registered with Weld (under that name) (<b>edit</b> in a CDI module, all beans are registered with Weld, the named annotation is just used to match beans to injection points). When our JSF page was rendered, JSF tried to resolve the value of <code>messageServerBean</code> in the page using the registered expression resolvers in JSF. One of these is the Weld EL Resolver which has the MessageServerBean class registered under the name <code>messageServerBean</code>. We could have specified a name with the annotation, but since we didn't it was registered under the default name of the class name with a lower case first name. The Weld resolver returns an instance of this bean in response to the request from JSF. Bean naming is only needed when using EL expressions and should not be used as the default mechanism for injection. CDI provides type safe injection by class type and stereotypes or qualifiers as we'll see later.</p>
<h4>Upgrading to an EJB</h4>
<p>As we are using a JEE stack, we can easily deploy our bean as an EJB with some small changes thanks to EJB 3.1. Just open up the <code>MessageServerBean</code> and add the <code>javax.ejb.Stateless</code> annotation at the class level. Again, just save the file and go to your browser and refresh (no manual deploying, just save the file), and you should see something like :</p>
<pre class="codeblock">
Message is : Hello From Weld!
Message Server Bean is : eedemo.__EJB31_Generated__MessageServerBean__Intf____Bean__@xxxxxxx
</pre>
<p>Amazingly, we turned our pojo bean into a fully featured EJB with just one annotation, we saved it, and refreshed our page and our changes appeared, we don't have to create any weird project configurations, local interfaces or arcane deployment descriptors.  </p>
<h4>Different EJB types</h4>
<p>You can also try using the <code>@Stateful</code> annotation (don't forget to implement the <code>java.io.Serializable</code> interface in the bean as it needs to be able to passivate (<b>edit</b> This isn't necessary for it to be an EJB, but it is necessary if you want it to be session or conversation scoped)). Alternatively, you could try the new <code>@Singleton</code> annotation for singleton instances. If you do, you may notice that there is a <code>javax.ejb.Singleton</code> and <code>javax.inject.Singleton</code>. Why two Singleton annotations? A single annotation in CDI lets you define a singleton instance outside of EJB in case you are using CDI in a non-EJB environment. An EJB singleton will have all the features of an EJB such as transaction management so you have the choice depending on your needs and whether the environment is EJB or not.</p>
<p>In this first part, we have created a new JSF 2.0 application, made it CDI enabled and added a managed bean which we then referenced from the web page. In part 2, we'll start looking at creating more complex beans and injecting them into and with other beans.</p>
<p>Click to view <a href="http://www.andygibson.net/blog/index.php/2009/12/22/getting-started-with-cdi-part-2-injection/">Part 2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/index.php/2009/12/16/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>
