<?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 &#187; Articles</title>
	<atom:link href="http://www.andygibson.net/blog/tag/articles/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Fri, 30 Jul 2010 02:42:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using Composition in Object Modeling</title>
		<link>http://www.andygibson.net/blog/article/using-composition-in-object-modeling/</link>
		<comments>http://www.andygibson.net/blog/article/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[Articles]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Journeyman]]></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 class="brush: java;">
public class Person {

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

  private String userName;
  private String password;

}
</pre>
<pre class="brush: java;">
public class Customer extends Person {

  private int creditLimit;

}
</pre>
<pre class="brush: 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>
<h1>Role your own</h1>
<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>
<h1>Compose Yourself</h1>
<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 class="brush: java;">
public class User {

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

  private Long id;
  private Person person;
  private int creditLimit;
}
</pre>
<pre class="brush: 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 class="brush: 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 class="brush: 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 class="brush: 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 class="brush: java;">
  String msg = &quot;Hi There &quot;+customer.getName();
</pre>
<p>is much cleaner than</p>
<pre class="brush: java;">
  String msg = &quot;Hi There &quot;;

  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 class="brush: java;">
select c from Customer c where c.creditLimit &gt; 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>
<h1>Unique People, non-unique references</h1>
<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>
<h1>Modeling with JPA</h1>
<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 class="brush: java;">
public class PersonCustomer extends AbstractCustomer {

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

}

public class CompanyCustomer extends AbstractCustomer {

  @ManyToOne
  @JoinColumn(name=&quot;REF_ID&quot;)
  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>
<h1>A technique with many uses</h1>
<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 class="brush: 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 class="brush: 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/article/using-composition-in-object-modeling/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Getting Started with JSF 2.0 and CDI part 3 &#8211; Events</title>
		<link>http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/</link>
		<comments>http://www.andygibson.net/blog/tutorial/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[Tutorials]]></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.

Read Part 1
Read Part 2
Read Part 3
As a refresher, in our last part, [...]]]></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><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1/">Part 1</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-cdi-part-2-injection/">Part 2</a><br />
Read <a href="http://www.andygibson.net/blog/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/">Part 3</a></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 class="brush: java;">
@Retention(RetentionPolicy.RUNTIME)
@Target({FIELD,METHOD,PARAMETER,TYPE})
@Qualifier
public @interface Notify {}
</pre>
<pre class="brush: java;">
@Notify
public class EventItemHandler implements ItemErrorHandler {

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

    public void handleItem(Item item) {
        System.out.println(&quot;Firing Event&quot;);
        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 class="brush: 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 class="brush: 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>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1f84b46 [Value=34, Limit=7] to file
INFO: Closing file error reporter
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@2656da [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<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>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1380c08 [Value=34, Limit=7] to file
INFO: Firing Event
INFO: Saving eedemo.Item@1b44f96 [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<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 class="brush: java;">
    @Inject
    private Event&amp;lt;Item&amp;gt; processorEvent;

    public void execute() {
        List&amp;lt;Item&amp;gt; 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>
<pre class="brush: plain;">
INFO: Creating eedemo.EventItemHandler_$$_javassist_748
INFO: Creating file error reporter
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file
INFO: Creating eedemo.EventItemHandler
INFO: Firing Event
INFO: Saving eedemo.Item@6d0baf [Value=34, Limit=7] to file
INFO: Saving eedemo.Item@1087300 [Value=4, Limit=37] to file
INFO: Saving eedemo.Item@11674c9 [Value=24, Limit=19] to file
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file
INFO: Firing Event
INFO: Saving eedemo.Item@de163a [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<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 class="brush: java;">
@Notify
@RequestScoped
public class EventItemHandler implements ItemErrorHandler {

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

    public void handleItem(Item item) {
        System.out.println(&quot;Firing Event&quot;);
        itemEvent.fire(item);
    }
}
</pre>
<pre class="brush: 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>
<pre class="brush: plain;">
INFO: Firing Event
INFO: Creating file error reporter
INFO: Saving eedemo.Item@1e3aa22 [Value=34, Limit=7] to file
INFO: Firing Event
INFO: Saving eedemo.Item@172940f [Value=89, Limit=32] to file
INFO: Closing file error reporter
</pre>
<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 class="brush: java;">
@Named(&quot;itemProcessor&quot;)
@RequestScoped
public class ItemProcessor {

    ....

    public void observeItemEvent(@Observes Item item) {
        System.out.println(&quot;Item event observed for item &quot;+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 class="brush: java;">
@Stateless
public class ScheduledProcessor {

    @Inject
    private ItemProcessor itemProcessor;

    @Schedule(hour=&quot;07&quot;,minute = &quot;00&quot;)
    public void execute() {
        System.out.println(&quot;executing scheduled job!&quot;);
        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/tutorial/getting-started-with-jsf-2-0-and-cdi-part-3/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Notes On Choosing A Web Framework</title>
		<link>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/</link>
		<comments>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 13:24:47 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Wicket]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=549</guid>
		<description><![CDATA[I&#8217;m looking at starting a new project and once again find myself choosing between frameworks. Having spent some time evaluating different ones I wrote up some notes to share and get some feedback that might alter my thoughts or opinions. Here&#8217;s the criteria I&#8217;m using to choose a framework in no particular order.

IDE Support &#8211; [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m looking at starting a new project and once again find myself choosing between frameworks. Having spent some time evaluating different ones I wrote up some notes to share and get some feedback that might alter my thoughts or opinions. Here&#8217;s the criteria I&#8217;m using to choose a framework in no particular order.<br />
<span id="more-549"></span></p>
<p><strong>IDE Support</strong> &#8211; I would like to get as much IDE support as possible for auto completion, code validation and general helpfulness.</p>
<p><strong>Resume Building</strong> &#8211; How much demand is there for the skills? I&#8217;m looking to bolster my skills that have wide adoption in the industry. As this is an important factor, it also means I probably won&#8217;t be choosing a framework that I am already very familiar with. I&#8217;ll be using job trends and opinion to determine the industry support for the frameworks. I know job sites aren&#8217;t the best measure, especially since many ads are stuffed with buzzwords so they appear in searches even if there is no JSF, JAXB or JAX-WS involved. However, the fact that they are included at all indicates some kind of market penetration of the technology.</p>
<p><strong>Ajax Support</strong> &#8211; How well does it support Ajax natively out of the box as opposed to requiring third party libraries and are there de-facto standard libraries for that framework if they are needed.</p>
<p><strong>Templating / Layout</strong> &#8211; How are pages built and organized to enable reusable HTML without using include statements everywhere or some other mechanism which will require every page to be edited if the layout is changed. I think facelets is the best page layout library out there as it pulls the template into the page and then pushes the content from the page into the template making separate files optional. Tiles requires separate definition files and does a similar thing outside of the page being rendered. Sitemesh is non invasive and works by decorating existing pages as they are sent to the client. In terms of writing actual pages, the choices are Jsp, Velocity and Freemarker, of which JSP and Velocity are the two most in demand.</p>
<p><strong>Completeness</strong> &#8211; How much is in the framework out of the box without requiring additional libraries for core functionality. Obviously, you are going to need libraries for things like data access, but the framework should be able to put text in a page without requiring third party libraries. One other aspect of this is how easy it is to get up and running without having to get different pieces configured and talking to each other. Some frameworks discussed here like Spring MVC and JSF are not meant to be complete frameworks but a framework onto which to build other frameworks (like Servlets). In these cases, the frameworks are expanded by third party libraries so completeness is not so much a factor here. Third party libraries integrated as part of the stack is acceptable (i.e. Sitemesh in Grails and Richfaces in Seam).</p>
<p><strong>Custom Paginated Tables with Sortable Columns</strong> &#8211; This is my barrier for determining how powerful and easy a framework is to use. Simple CRUD is trivial to write, it&#8217;s like hello world for the web so I usually go for a more robust litmus test by writing some pagination code. Action frameworks require you to chug all the parameters backwards and forwards and handle your own binding and determining whether a page was selected or next/previous was clicked while Component frameworks handle most of that for you. For the same reason, clickable columns can be a real pain. For bonus points, how easy is it to implement multiple paginated / sortable tables? </p>
<p><strong>Statefulness</strong> &#8211; Can we integrate some kind of stateful mechanism in there (i.e Spring Web Flow) cleanly? There are a few scenarios where I will need a stateful workflow in the application.</p>
<p><strong>Third Party Support and integration</strong> &#8211; One annoying aspect of java web development is all the pieces and parts that need to be strung together and then you have to get them to play nicely. This is really about the path of least surprise, and not having to deal with issues because I add libraries that don&#8217;t have special mechanisms for working with each other.. I.e Spring MVC embraces Tiles, but how much of a hassle is it to incorporate Velocity with Tiles? This issue is also somewhat redundant for those frameworks that include built-in solutions for most needs. </p>
<p>The application is going to be moderate in size, but hopefully growing as time goes on. For that reason, I&#8217;m looking for something flexible enough to grow and refactor later on. Initially, I&#8217;m also looking for something lightweight and will be looking to deploy it on Tomcat primarily due to ease of hosting. </p>
<h1>Action or Component Based</h1>
<p>I find Action frameworks are great for catalogs and simple CRUD pages but when you start getting to more complex web applications pages, things get much tricker. Take for example a search page with 10 search parameters, suddenly you find yourself having to attach 10 parameters to the next/previous/first/last result links or using javascript funkiness to modify form contents to change the form state and post the form. Add column ordering and things get pretty messy quickly. In my mind, For a web application, any search pages (or other pages that require pagination or other common interface elements) should be trivial to write within minutes. Obviously, if you are Google and your main business is that one search page, you can afford to spend a little more time on it and be as choosy as you like on how to implement it. However, it never fails to amaze how much code people will write to create a single page demonstrating how to do some simple function in a non-reusable way. User interface elements like pagination and column ordering should be totally reusable. </p>
<h1>The Contenders</h1>
<p>Here are the contenders in no specific order</p>
<ul>
<li>Seam with JSF</li>
<li>Wicket</li>
<li>JSF</li>
<li>Grails</li>
<li>Spring MVC with JSP</li>
<li>Spring MVC with JSF</li>
</ul>
<p>First lets look at the job trends for these different frameworks :</p>
<div style="width:540px">
<a href="http://www.indeed.com/jobtrends?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" title="spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends"><br />
<img width="540" height="300" src="http://www.indeed.com/trendgraph/jobgraph.png?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" border="0" alt="spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends graph"><br />
</a></p>
<table width="100%" cellpadding="6" cellspacing="0" border="0" style="font-size:80%">
<tr>
<td><a href="http://www.indeed.com/jobtrends?q=spring+java%2C+ejb+java%2C+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java">spring java, ejb java, jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends</a></td>
<td align="right"><a href="http://www.indeed.com/q-spring-java-jobs.html">spring java jobs</a> &#8211; <a href="http://www.indeed.com/q-ejb-java-jobs.html">ejb java jobs</a> &#8211; <a href="http://www.indeed.com/q-jsf-java-jobs.html">jsf java jobs</a> &#8211; <a href="http://www.indeed.com/jobs?q=%22spring+mvc%22+java">&#034;spring mvc&#034; java jobs</a> &#8211; <a href="http://www.indeed.com/q-wicket-java-jobs.html">wicket java jobs</a> &#8211; <a href="http://www.indeed.com/q-seam-java-jobs.html">seam java jobs</a> &#8211; <a href="http://www.indeed.com/q-grails-java-jobs.html">grails java jobs</a></td>
</tr>
</table>
</div>
<p>We can see a sort of multi-tier system in place for different frameworks. Spring and EJB both rank up there as first tier technologies. I&#8217;ve already had quite a bit of experience with both of these but Spring is at an advantage with regards to being lightweight and running in tomcat without having to worry about setting up an embedded EJB container. Writing something with EJB 6 might be a possibility, but I think it more likely I&#8217;ll try and use Spring.</p>
<p>Now lets consider the view frameworks :</p>
<div style="width:540px">
<a href="http://www.indeed.com/jobtrends?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" title="jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends"><br />
<img width="540" height="300" src="http://www.indeed.com/trendgraph/jobgraph.png?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java" border="0" alt="jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends graph"><br />
</a></p>
<table width="100%" cellpadding="6" cellspacing="0" border="0" style="font-size:80%">
<tr>
<td><a href="http://www.indeed.com/jobtrends?q=+jsf+java%2C+%22spring+mvc%22+java%2C+wicket+java%2C+seam+java%2C+grails+java">jsf java, &#034;spring mvc&#034; java, wicket java, seam java, grails java Job Trends</a></td>
<td align="right"><a href="http://www.indeed.com/q-jsf-java-jobs.html">jsf java jobs</a> &#8211; <a href="http://www.indeed.com/jobs?q=%22spring+mvc%22+java">&#034;spring mvc&#034; java jobs</a> &#8211; <a href="http://www.indeed.com/q-wicket-java-jobs.html">wicket java jobs</a> &#8211; <a href="http://www.indeed.com/q-seam-java-jobs.html">seam java jobs</a> &#8211; <a href="http://www.indeed.com/q-grails-java-jobs.html">grails java jobs</a></td>
</tr>
</table>
</div>
<h1>Seam / JSF</h1>
<p>I&#8217;ve had a lot of experience with these two so it&#8217;s easy to comment on. Great IDE support (probably the best), great out of the box support, but it can feel foreign to use on Tomcat where it doesn&#8217;t offer such a rich a developer experience. Great Ajax support, but not so great for the resume since I already have a lot of experience with Seam and there are very few Seam jobs out there.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Seam</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Excellent &#8211; JBoss Tools</td>
<td><strong>Demand</strong></td>
<td>Poor</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent &#8211; Richfaces</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Excellent &#8211; reusable component based pagination</td>
<td><strong>Completeness</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Statefullness</strong></td>
<td>Excellent &#8211; Conversational scope</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Ok &#8211; Seam likes things to run a certain way</td>
</tr>
</table>
<h1>JSF</h1>
<p>Despite using Seam a lot, writing a straight JSF application is still quite different and poses a number of challenges. It might be a interesting using just JSF but I have most of that ground covered with my existing JSF work. JSF is in-demand though and this might be an opportunity to use it with other frameworks such as a Spring/Hibernate/JSF combination. It has great Ajax support with multiple frameworks available, but no decent IDE support even though JBoss Tools works well on plain JSF apps without Seam. It may also get frustrating since I&#8217;ll be having constant reminders of how easy things are when you use Seam. Facelets is a great templating framework, if not the best, and I&#8217;d probably go to JSF 2.0 so I can use annotated beans. For statefulness, I could add in Orchestra and pagination should be simple with JSF although I think Seam (or JBoss-El) added ways to call methods (with parameters) on beans passed in to facelets which made it really easy. I haven&#8217;t been able to duplicate that with in JSF or Spring Faces which could be a problem. One annoyance of JSF is the inability to suppress validation when you post the form back but don&#8217;t want to save it which you may want to do as part of a web flow where you want to save the contents, go to another page, come back and finish your data entry. The only solution is to manually perform validation when the form is finally saved and not use JSF validators which is a limitation and I don&#8217;t thing this was fixed in JSF 2.0.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>JSF</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Ok with JBoss Tools</td>
<td><strong>Demand</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Great with 3rd Party tools or JSF 2.0</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Good</td>
<td><strong>Completeness</strong></td>
<td>Ground framework</td>
</tr>
<tr>
<td><strong>Statefulness</strong></td>
<td>None without 3rd party libs like Apache Orchestra</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Excellent for JSF libs</td>
</tr>
</table>
<h1>Wicket</h1>
<p>Wicket is a great component based framework with good ajax support, a fine grained stateful architecture and because of it&#8217;s emphasis on the java language, good IDE support. Some people don&#8217;t like the heavy use of java code to build web pages, but it&#8217;s a personal thing and I do enjoy it. However, the only thing holding it back for me is the poor industry adoption with very few Wicket jobs. </p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Wicket</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Great since it is mostly java based</td>
<td><strong>Demand</strong></td>
<td>Poor &#8211; unfortunately</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent &#8211; it comes with Ajaxified components</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Offers page inheritance and panels</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Excellent &#8211; reusable component based pagination</td>
<td><strong>Completeness</strong></td>
<td>Good</td>
</tr>
<tr>
<td><strong>Statefullness</strong></td>
<td>Excellent &#8211; Fine grained statefulness</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Great &#8211; although you won&#8217;t need or be able to use many web libraries (i.e. tiles, velocity etc) here.</td>
</tr>
</table>
<h1>Grails</h1>
<p>I tried to get back into Grails and again, I hit a number of snags. It&#8217;s a great framework, but I find it can be problematic. The IDE support was basic and I often had to clean the eclipse project then the grails project so it wouldn&#8217;t choke on old classes lying around. Netbeans also has Grails support, but was prone to hanging when you want to restart the server. It also lacked the refactoring / renaming features present in eclipse.  I also found problems in the framework itself such as not being able to model embedded classes that contained a reference to another entity. Other times, inexplicably, when I called <code>person.save()</code> nothing would happen, no error, no messages, nothing. I don&#8217;t doubt it was my fault and something I did, but it is off putting and frustrating in a framework that won&#8217;t tell you when you have a syntax error.</p>
<p>Grails and Wicket seem like polar opposites in some ways. Wicket is all about type safety and strict java code checked by the IDE. Grails on the other hand doesn&#8217;t often know when you make a mistake because its a dynamic language.  Developers shouldn&#8217;t have to write tests just to make sure you didn&#8217;t make any typo&#8217;s in your classes, people have spent a number of years and millions of dollars evolving IDEs to solve that very problem.</p>
<p>The dynamic language is all very nice, and Grails is a framework but when I&#8217;m building furniture, I don&#8217;t start out with aflat pack plywood cabinet and slowly replace each piece with half inch mahogany with hand cut dovetail joints in the name of being rapid and agile (umm, Agile Wordworking, there&#8217;s an idea). I can see the point, and for the most part, Grails is unobtrusive but I think for me,  on this project, I&#8217;d rather start out with a workbench and some planks of mahogany and craft it from scratch. </p>
<p>Ajax support is excellent and it also has many plugins which are easy to install and use. Writing taglibs is a breeze and very intuitive. Even pagination was fairly simple and I especially liked the paginator tag that takes a map of parameter values to include on all the previous/next/page links. Again, things are scarce on the job front for Grails, but being such a unique and productive tool I think there is a great future for Grails which lowers the importance of current trends. </p>
<p>Grails also supports Spring Web Flow but I&#8217;m not sure it allows the use of flow scoped persistence contexts. Sitemesh is used for templating and offers a lot of features out of the box. Overall it&#8217;s very impressive and definitely still a contender.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Grails</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Poor</td>
<td><strong>Demand</strong></td>
<td>Small but growing</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Sitemesh and easy taglibs</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Great</td>
<td><strong>Completeness</strong></td>
<td>Great &#8211; plugins make things easier</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Spring Web Flow </td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Plugins make it really easy</td>
</tr>
</table>
<h1>Spring MVC with JSP</h1>
<p>This is probably the one I was most eager to tackle as I think this one probably has the most potential. Spring and JSP have been largely adopted within the industry, but are they any good? I think Spring MVC is excellent, especially with the new Spring 2.5 Controller annotations and Web Flow integration. As usual with Spring, it provides a lot of flexibility and it sits on the Core Spring Framework. For templating, I can use Sitemesh, Tiles, and it includes support for velocity and free marker. It appears that using both Tiles and Velocity together isn&#8217;t straightforward resulting in this third party <a href="http://anydoby.com/velocity/">plugin</a> to solve the problem.</p>
<p>Spring MVC doesn&#8217;t have any ajax support, <a href="http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html">Chapter 13 &#8211; Web MVC Framework</a> of the Spring reference documentaton doesn&#8217;t even mention the word Ajax. Spring Web Flow has Ajax support but it requires the use of Tiles (or some other compatible templating library) for specifying page fragments to update. This is also requires that pages be designed in such a way that the Ajax updatable pieces are clearly defined in the page definition which is outside of the page being designed. With Richfaces you can create a fragment in the page just by using an output panel tag and giving it a name. Another problem with Spring Web Flow is the inability to use an Open Session In View alongside the Flow Managed Persistence context which means having to work around Lazy Initialization Issues in other ways. On the plus side though, you can make validation optional in Spring Web Flow if you are using the Spring Validators and not JSF.</p>
<table style="width : 100%;font-size : 90%">
<tr>
<th colspan=4>Spring MVC with JSP </th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Good &#8211; Spring IDE</td>
<td><strong>Demand</strong></td>
<td>Excellent</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Poor</td>
<td><strong>Templating</strong></td>
<td>3rd Party</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Roll Your Own</td>
<td><strong>Completeness</strong></td>
<td>Spring MVC offers a solid ground on which to build</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Spring Web Flow</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Good</td>
</tr>
</table>
<h1>Spring MVC with JSF / Spring Faces</h1>
<p>If I couldn&#8217;t find a way to reconcile the problems with Spring MVC and JSP, this would be my backup as it solves a number of problems with using Spring MVC and JSP. It fixes the Ajax and templating issues since I can use a JSF based Ajax framework (IceFaces or Richfaces) and Facelets for superior templating. The only problems here is a resource issue for JSF and the fact that I have already worked with JSF extensively. However, I have found Spring Faces to be a great library to use with some nice extensions. While there are only a few jobs explicitly mentioning Spring Faces, there are many jobs involving Spring and JSF. While spring web flow de-couples your view from the back end, it can be a little too decoupled. For example, within a flow, to call a method from a command button and refresh some data requires you to call the method and return an action string that would trigger the refresh of the data in the web flow. In Seam, you can get away with just calling the method and then refreshing the data. Spring Web Flow, forces you to decouple that which makes for a lot more work when you have multiple links that can trigger a refresh of the data. It also doesn&#8217;t fix the open session in view / flow managed persistence context clash. Writing JSF pages outside of a web flow means having to work directly with Spring beans as Jsf backing beans as opposed to dealing with Spring Beans through the web flow. This isn&#8217;t a big deal though, it just means you have two separate styles of writing code.  Even though Spring Web Flow lets you suppress validations for flow transitions, It doesn&#8217;t have any effect when you are using JSF for the view, only when you are using Spring validations.</p>
<table style="width: 100%; font-size: 90%">
<tr>
<th colspan=4>Spring MVC with JSF / Spring Faces</th>
</tr>
<tr>
<td><strong>IDE Support</strong></td>
<td>Good &#8211; JBoss Tools for JSF and Spring IDE</td>
<td><strong>Demand</strong></td>
<td>Great &#8211; Spring and JSF Combination</td>
</tr>
<tr>
<td><strong>Ajax Support</strong></td>
<td>Excellent</td>
<td><strong>Templating</strong></td>
<td>Excellent &#8211; Facelets</td>
</tr>
<tr>
<td><strong>Pagination</strong></td>
<td>Good</td>
<td><strong>Completeness</strong></td>
<td>Good</td>
</tr>
<tr>
<td><strong>statefulness</strong></td>
<td>Soring Web Flow</td>
<td><strong>3rd Party Library Integration</strong></td>
<td>Good</td>
</tr>
</table>
<h1>Summary</h1>
<p>Ultimately, it boils down to Grails or Spring MVC with JSP and probably Tiles and if I can&#8217;t find a solution there, Spring MVC with JSF. I f career/employment was not a factor, I would pick Wicket with Spring in a second, however, as I&#8217;m looking to bolster my resume and make sure my bona fides are in order for the more popular technologies.</p>
<p>All in all, it&#8217;s a difficult choice, but I&#8217;d love to get some more thoughts on the matter. I&#8217;m sure there are plenty of opinions on frameworks out there in The java community <img src='http://www.andygibson.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /><br />
<script type="text/javascript">var dzone_url = 'http://www.andygibson.net/blog/index.php/2009/09/25/notes-on-choosing-a-web-framework/';</script><br />
<script type="text/javascript">var dzone_title = 'Notes On Choosing A Web Framework';</script><br />
<script type="text/javascript">var dzone_blurb = 'Yet another write up of my ongoing evaluation of different web frameworks for a new Java project';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/notes-on-choosing-a-web-framework/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Glass Button Tutorial &#8211; In Java</title>
		<link>http://www.andygibson.net/blog/tutorial/glass-button-tutorial-in-java/</link>
		<comments>http://www.andygibson.net/blog/tutorial/glass-button-tutorial-in-java/#comments</comments>
		<pubDate>Thu, 03 Sep 2009 00:01:55 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JTexgen]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=446</guid>
		<description><![CDATA[
Create glass effect buttons using nothing but Java code and JTexGen, a procedural texture library for Java. First create a new project in your favorite IDE and add the JTextGen jar file, or create a new maven project and add the JTexgen dependency if you installed it from the source distribution into your local repository.

Our [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/blog/wp-content/uploads/2009/08/mainButton.png" class="leftImg" /><br />
Create glass effect buttons using nothing but Java code and <a href="http://www.andygibson.net/blog/index.php/2009/08/02/jtexgen-procedural-texture-library-released/">JTexGen</a>, a procedural texture library for Java. First create a new project in your favorite IDE and add the JTextGen jar file, or create a new maven project and add the JTexgen dependency if you installed it from the source distribution into your local repository.<br />
<span id="more-446"></span><br />
Our glass button will be round-ish, and will have a margin at the edge where we will render the shadow. We&#8217;ll start by writing our main method and creating the glass button class and rendering it. First create a new class called <code>GlassButton.java</code> and make it extend <code>AbstractTexture</code>. We&#8217;ll add a constructor that takes the base color of the button and returns it in the <code>getColor</code> method.</p>
<pre class="brush: java;">
public class GlassButton extends AbstractTexture {

	private final RGBAColor color;

	public GlassButton(RGBAColor color) {
		this.color = new RGBAColor(color);
	}

	public void getColor(double u, double v, RGBAColor value) {
		value.setColor(color);
	}
}
</pre>
<p>Next we&#8217;ll create our main class and add some code to create and render our texture.</p>
<pre class="brush: java;">
public class Main {

	public static void main(String[] args) {
		RGBAColor color = RGBAColor.red();
		Texture texture = new Background(new GlassButton(color),RGBAColor.white());
		TextureViewer.show(texture);
	}
}
</pre>
<p>Ok, a fairly simple start, we create our texture with a red color over a white background and pass it to the viewer. If you save and run this, you should get a window with a start button, which will render the red texture when clicked. Let&#8217;s add a method to our texture to calculate where on the button the textures <code>u,v</code> co-ordinates are. We do this by calculating the distance from the center of the texture the U,V co-ordinates are. The value returned will range from 0..1 inside the circle and outside the circle, it will return 1+ and grow larger the further it gets from the center. This lets us determine what should appear for any given point on the texture. Since we want a border around the edge of the button, we will have to scale the <code>u,v</code> values so when the result ramps up to 1 before getting to the edge of the texture. Add the following method to the <code>GlassButton</code> class.</p>
<pre class="brush: java;">
protected double calculateCircleRange(double u,double v) {
	//displace point
	u = u - 0.5;
	v = v - 0.5;
	//calculate distance
	double distance = Math.sqrt((u*u)+(v*v));
	//double it since the range will only be from 0 to 0.5
	return distance * 2;
}
</pre>
<p>We can verify this works by changing our get value method to return this value in the alpha channel.</p>
<pre class="brush: java;">
public void getColor(double u, double v, RGBAColor value) {
	double range = calculateCircleRange(u, v) * 1.2;
	value.setColor(color);
	value.setAlpha(1-range);
}
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/coefAlpha.png" class="leftImg" /><br />
We inverted the signal (<code>1-range</code>) so the color would be stronger at the center and weaker at the edge. Since the range goes beyond 1, then the value is truncated to the range 0..1 which is why the pattern repeats at the edge of the circle. </p>
<p>What we need to do is calculate the color based on the return value of this function. Values greater than 1 will result in rendering the shadow with a strength inversely proportional to the distance from the edge. For 0 to 1 values, we will render the button color and overlay the highlight onto it. We will also add an inner shadow in the range 0.7 to 1 with a strength based on the distance from the edge. The button color will consists of a base color which slowly transforms into a darker version of that base color the further down the button we go. The highlight is added as a lighter version of the base color with the alpha channel decreasing the further down the button we go. This has the effect of fading out the highlight the further down we go. Let&#8217;s flesh out a simple version to indicate where each piece is going. </p>
<pre class="brush: java;">
public void getColor(double u, double v, RGBAColor value) {
	double range = calculateCircleRange(u, v) * 1.2;

	if (range &gt; 1) {
		//render shadow
		value.setColor(RGBAColor.black());
		return;
	}		

	value.setColor(color);

	if (range &gt; 0.7) {
		value.setColor(RGBAColor.yellow());
	}
}
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/buttonLayout.png" class="leftImg" /><br />
This gives us a fairly predictable result, you can see where the button ends and the shadow starts and you can see which parts the inner shadow affects. We multiply the range value by 1.2 so we can shrink the circle down a bit to give us our margin around the edge for the shadow to sit in.</p>
<p>Time to add some actual colors to our template starting with the shadow. Our shadow is essentially the color black with the alpha ranging from 0.9 to 0 based on how far the point is from the edge of the button. We make the shadow fall off exponentially so the shadow becomes much lighter faster. Bear in mind that the range value for the shadow area is 1+ so we need to adjust the value into the 0..1 range.</p>
<pre class="brush: java;">
public void getColor(double u, double v, RGBAColor value) {
	double range = calculateCircleRange(u, v) * 1.2;

	if (range &gt; 1) {
		//render shadow
		value.setColor(RGBAColor.black());
		double shadow = Math.pow(2-range-0.1, 8);
		value.setAlpha( shadow);
		return;
	}		

	value.setColor(color);

	if (range &gt; 0.8) {
		value.setColor(RGBAColor.yellow());
	}
}
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/shadowButton.png" class="leftImg" /><br />
We specified a white background in our main class and the shadow has a varying alpha value so the white background show through. We can also change the background to see how it looks on different colors.</p>
<p>Now would be a good time to set up the different colors we&#8217;ll be using in our button. We have our base color passed in to the constructor, and from that, we can calculate the darker button color and the lighter highlight color. Let&#8217;s add those in to the constructor first.</p>
<pre class="brush: java;">
public class GlassButton extends AbstractTexture {

	private final RGBAColor color;
	private final RGBAColor darkerColor;
	private final RGBAColor highlightColor;

	public GlassButton(RGBAColor color) {
		this.color = new RGBAColor(color);

		//make a copy and darken it
		this.darkerColor = new RGBAColor(color);
		this.darkerColor.merge(RGBAColor.black(),0.5);

		//make a copy and lighten it
		this.highlightColor = new RGBAColor(color);
		this.highlightColor.merge(RGBAColor.white(),0.8);
	}
</pre>
<p>With our colors in place, we can start adding them to the final button image. We&#8217;ll start with the main button color which ranges from the base color to dark color as the v value increases and we evaluate pixels further down the image. This can be done with one line of code since we take the base color and merge the darker color based on the v value after we assign the base color to the value.</p>
<pre class="brush: java;">
value.setColor(color);
value.merge(darkerColor,(v-0.1)*1.2);
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/coloredButton.png" class="leftImg" /><br />
We shift and scale the v value to try and make the color transformation apply across the whole face of the button which is scaled down. This gives as a gentle transformation across the face of the button. </p>
<p>The button has an inner shadow which gives us the impression that the edges of the button are bending away from us. The code for this looks at the circle range value and if greater than 0.8 adds the inner shadow based on the distance from the edge. To calculate this, we subtract the 0.8 and scale it to get a value in the range of 0 to 0.4 which is perfect since we don&#8217;t want a strong shadow.</p>
<pre class="brush: java;">
		//add the inner shadow
		if (range &gt; 0.8) {
			double shadow = (range-0.8)*2;
			value.merge(RGBAColor.black(),shadow);
		}
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/innerShadowButton.png" class="leftImg" /><br />
The last piece we need to add is the highlight which is rendered in the shape of an smaller circle that is offset upwards slightly. This means we can reuse our <code>calculateCircleRange</code> method to determine which points are in the smaller circle. Once we have determined whether we are in the highlight circle or not we will merge the highlight color based on the <code>v</code> value so the highlight fades out as we move down the button. </p>
<p>Here is the complete <code>getColor</code> method with the code to add the highlight at the end.</p>
<pre class="brush: java;">
public void getColor(double u, double v, RGBAColor value) {
	double range = calculateCircleRange(u, v) * 1.2;

	if (range &gt; 1) {
		// render shadow
		value.setColor(RGBAColor.black());
		double shadow = Math.pow(2 - range - 0.1, 8);
		value.setAlpha(shadow);
		return;
	}

	// set the base color
	value.setColor(color);

	// add the darker color transform
	value.merge(darkerColor, (v - 0.1) * 1.2);

	// add the inner shadow
	if (range &gt; 0.8) {
		double shadow = (range - 0.8) * 2;
		value.merge(RGBAColor.black(), shadow);
	}

	// finally add the highlight
	double highlightRadius = calculateCircleRange(u, v + 0.05) * 1.5;
	if (highlightRadius &lt; 1) {
		double highlight = v * 2;
		value.merge(highlightColor, Gradient.clip(1 - highlight));
	}
}
</pre>
<p><img src="/blog/wp-content/uploads/2009/08/final.png" class="leftImg" /><br />
This is our final button image which is a round red glass button. However, because this is a procedural texture, we can scale the image in both the u and v directions without loss of quality and we can also create oval buttons. Below you can see a number of different variations. </p>
<p>I&#8217;ve also added an enhancement with regards to the inner shadow. Rather than making it a fixed black color, I have used a <code>ColorGradient</code> so the inner shadow transforms from dark to light from the top to the bottom of the button.  We did this by adding this private member </p>
<pre class="brush: java;">
private final ColorGradient shadowColor = ColorGradient.buildBlackAndWhite();
</pre>
<p>and in our inner shadow code, we use this gradient color instead of the fixed black color :</p>
<pre class="brush: java;">
	// add the inner shadow
	if (range &gt; 0.8) {
		double shadow = (range - 0.8) * 2.5;
		value.merge(shadowColor.interpolate((v+0.3)), shadow);
	}
</pre>
<p>Also, for the last image, instead of using a solid color, I used a <code>ColorGradient</code> from the highlight color to the base color and then the darker color to give it that radial gradient. I plan on writing a generalized version of this texture for inclusion in the next release that will let you set parameters and even pass <code>Texture</code> objects for the main color and the inner shadow.</p>
<p><img src="/blog/wp-content/uploads/2009/08/logoButton.png" class="leftImg" /><img src="/blog/wp-content/uploads/2009/08/oval1.png" class="leftImg" /><img src="/blog/wp-content/uploads/2009/08/lightShadow.png" class="leftImg" /><img src="/blog/wp-content/uploads/2009/08/onMarble.png" class="leftImg" /><img src="/blog/wp-content/uploads/2009/08/purpleRadial.png" class="leftImg" /><br />
<br/></p>
<div style="clear:both">
<script type="text/javascript">var dzone_url = 'http://www.andygibson.net/blog/index.php/2009/09/02/glass-button-tutorial-in-java/';</script><br />
<script type="text/javascript">var dzone_title = 'Glass Button Tutorial In Java';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/glass-button-tutorial-in-java/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Seam vs Spring Web Flow part 3</title>
		<link>http://www.andygibson.net/blog/article/seam-vs-spring-web-flow-part-3/</link>
		<comments>http://www.andygibson.net/blog/article/seam-vs-spring-web-flow-part-3/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 14:34:36 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=156</guid>
		<description><![CDATA[This is the third of a four part series comparing Seam vs Spring Web Flow (SWF),and looks at the Seam implementation of the sample application.
(Updated 1/19/2009 : Changed links to point to the whole set of articles)
HTML
Single Page HTML
PDF
]]></description>
			<content:encoded><![CDATA[<p>This is the third of a four part series comparing Seam vs Spring Web Flow (SWF),and looks at the Seam implementation of the sample application.</p>
<p>(Updated 1/19/2009 : Changed links to point to the whole set of articles)<br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html/index.html">HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html_single/">Single Page HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/pdf/SeamSpringComparison.pdf">PDF</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/seam-vs-spring-web-flow-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Seam versus Spring Web Flow part 2</title>
		<link>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-2/</link>
		<comments>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-2/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 14:14:54 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=152</guid>
		<description><![CDATA[This is the second of a four part series comparing Seam and Spring Web Flow (SWF),and looks at the Spring implementation of the sample application that we discussed in part 1. In a day or so I will have the piece that looks at writing the application using Seam.
(Updated 1/19/2009 : Changed links to point [...]]]></description>
			<content:encoded><![CDATA[<p>This is the second of a four part series comparing Seam and Spring Web Flow (SWF),and looks at the Spring implementation of the sample application that we discussed in part 1. In a day or so I will have the piece that looks at writing the application using Seam.</p>
<p>(Updated 1/19/2009 : Changed links to point to the whole set of articles)<br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html/index.html">HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html_single/">Single Page HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/pdf/SeamSpringComparison.pdf">PDF</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Seam versus Spring Web Flow part 1</title>
		<link>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-1/</link>
		<comments>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-1/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 06:02:15 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=141</guid>
		<description><![CDATA[This is the first of a four part series comparing Seam and Spring Web Flow (SWF) from different aspects, primarily with respect to building web based CRUD applications. It includes writing a simple but fairly complete application using both frameworks and then comparing the differences between the Seam and the SWF implementation.
This first part starts [...]]]></description>
			<content:encoded><![CDATA[<p>This is the first of a four part series comparing Seam and Spring Web Flow (SWF) from different aspects, primarily with respect to building web based CRUD applications. It includes writing a simple but fairly complete application using both frameworks and then comparing the differences between the Seam and the SWF implementation.</p>
<p>This first part starts by taking a look at the two frameworks, where they come from and briefly, how they are used.</p>
<p>(Updated 1/19/2009 : Changed links to point to the whole set of articles)<br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html/index.html">HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/html_single/">Single Page HTML</a><br />
<a href="http://www.andygibson.net/articles/seam_spring_comparison/pdf/SeamSpringComparison.pdf">PDF</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/seam-versus-spring-web-flow-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
