<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Andy Gibson</title>
	
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &amp; Technical Writings</description>
	<lastBuildDate>Sat, 11 Feb 2012 17:36:57 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language />
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/andygibson/uhrp" /><feedburner:info uri="andygibson/uhrp" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Fading in Primefaces Components</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/eeuNOW7Ak0I/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/fading-in-primefaces-components/#comments</comments>
		<pubDate>Sat, 11 Feb 2012 17:36:57 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1884</guid>
		<description><![CDATA[I was trying to fade in a Primefaces panel component that was initially hidden and found it to be somewhat of a struggle. After a bit of googling, the only thing I found out was that I wasn&#8217;t the first to come across the problem. Here&#8217;s the basic JSF code to use an effect on [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to fade in a Primefaces panel component that was initially hidden and found it to be somewhat of a struggle. After a bit of googling, the only thing I found out was that I wasn&#8217;t the first to come across the problem. Here&#8217;s the basic JSF code to use an effect on a panel in response to the button click.</p>
<pre class="brush: java;">
&lt;p:button id=&quot;showme&quot; value=&quot;Show Me&quot; onclick=&quot;return false&quot;&gt;
	&lt;p:effect type=&quot;fade&quot; event=&quot;click&quot; for=&quot;myPanel&quot;/&gt;
&lt;/p:button&gt;

&lt;h:panelGroup layout=&quot;block&quot; id=&quot;myPanel&quot; style=&quot;display:none&quot;&gt;Show Me&lt;/h:panelGroup&gt;
</pre>
<p>This code does nothing because by default the fade effect fades out the component. Looking at the <a href="http://docs.jquery.com/UI/Effects/Fade#options">options</a> for the fade gives us no clues either since it claims there are no parameters. The solution is to provide a <code>mode</code> parameter that can be either <code>show</code> or <code>hide</code> which is used for most of the effects. In our case, we want to <code>show</code> the component.</p>
<pre class="brush: java;">
&lt;p:button id=&quot;showme&quot; value=&quot;Show Me&quot; onclick=&quot;return false&quot;&gt;
	&lt;p:effect type=&quot;fade&quot; event=&quot;click&quot; for=&quot;myPanel&quot;&gt;
		&lt;f:param name=&quot;mode&quot; value=&quot;'show'&quot;/&gt;
	&lt;/p:effect&gt;
&lt;/p:button&gt;

&lt;h:panelGroup layout=&quot;block&quot; id=&quot;myPanel&quot; style=&quot;display:none&quot;&gt;Show Me&lt;/h:panelGroup&gt;
</pre>
<p>This will show the panel that was initially hidden when you click the button. The only nagging problem is that the button retains its hover style until you click elsewhere in the page.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/eeuNOW7Ak0I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/fading-in-primefaces-components/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/quickbyte/fading-in-primefaces-components/</feedburner:origLink></item>
		<item>
		<title>Comparing JSF Beans, CDI Beans and EJBs</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/qaw3R6LxtQw/</link>
		<comments>http://www.andygibson.net/blog/article/comparing-jsf-beans-cdi-beans-and-ejbs/#comments</comments>
		<pubDate>Tue, 07 Feb 2012 13:15:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1879</guid>
		<description><![CDATA[There&#8217;s still a lot of confusion over the difference types of managed beans provided in Java EE 6 with EJBs, CDI beans and JSF managed beans all being available. This article aims to clear up some of the differences between the them and define when to use them. A number of people assume that there [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s still a lot of confusion over the difference types of managed beans provided in Java EE 6 with EJBs, CDI beans and JSF managed beans all being available. This article aims to clear up some of the differences between the them and define when to use them.<span id="more-1879"></span></p>
<p>A number of people assume that there is some meaning to all these different types of beans that they just don&#8217;t understand. However, the problem is down to the different APIs overlapping which is unfortunate. </p>
<h1>JSF Managed Beans, CDI Beans and EJBs</h1>
<p>JSF was initially developed with its own managed bean and dependency injection mechanism which was enhanced for JSF 2.0 to include annotation based beans. When CDI was released with Java EE 6, it was regarded as the managed bean framework for that platform and of course, EJBs outdated them all having been around for well over a decade. </p>
<p>The problem of course is knowing which one to use and when, but they all involve the same process. Typically a class has to be identified as a managed bean, and where necessary, will need a scope,qualifiers and a name if it is to be used in JSF. What follows is a brief description of the different types of managed beans and how and when to use them.</p>
<p>Let&#8217;s start with the simplest, JSF Managed beans. </p>
<h2>JSF Managed Beans</h2>
<p>In short, don&#8217;t use them if you are developing for Java EE 6 and using CDI. They provide a simple mechanism for dependency injection and defining backing beans for web pages, but they are far less powerful than CDI beans. </p>
<p>They can be defined using the <a href="http://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/managed-bean-api/javax/faces/bean/ManagedBean.html">@javax.faces.bean.ManagedBean</a> annotation which takes an optional <code>name</code> parameter. This name can be used to reference the bean from JSF pages.</p>
<p>Scope can be applied to the bean using one of the different scopes defined in the <a href="http://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/managed-bean-api/javax/faces/bean/package-summary.html">javax.faces.bean</a> package which include the request, session, applicaion, view and custom scopes. </p>
<pre class="brush: java;">@ManagedBean(name=&quot;someBean&quot;)
@RequestScoped
public class SomeBean {
    ....
    ....
}
</pre>
<p>JSF beans cannot be mixed with other kinds of beans without some kind of manual coding.</p>
<h2>CDI Beans</h2>
<p>CDI is the bean management and dependency injection framework that was released as part of Java EE 6 and it includes a complete, comprehensive managed bean facility. CDI beans are far more advanced and flexible than simple JSF managed beans. They can make use of interceptors, conversation scope, Events, type safe injection, decorators, stereotypes and producer methods. </p>
<p>To deploy CDI beans, you must place a file called <code>beans.xml</code> in a META-INF folder on the classpath. Once you do this, then every bean in the package becomes a CDI bean. There are a lot of features in CDI, too many to cover here, but as a quick reference for JSF-like features, you can define the scope of the CDI bean using one of the scopes defined in the <a href="http://docs.oracle.com/javaee/6/api/javax/enterprise/context/package-summary.html">javax.enterprise.context</a> package (namely, request, conversation, session and application scopes). If you want to use the CDI bean from a JSF page, you can give it a name using the <a href="http://docs.oracle.com/javaee/6/api/javax/inject/Named.html">javax.inject.Named</a> annotation. To inject a bean into another bean, you annotate the field with <a href="http://docs.oracle.com/javaee/6/api/javax/inject/Inject.html">javax.inject.Inject</a> annotation.</p>
<pre class="brush: java;">@Named(&quot;someBean&quot;)
@RequestScoped
public class SomeBean {

    @Inject
    private SomeService someService;
}
</pre>
<p>Automatic injection like that defined above can be controlled through the use of <a href="http://docs.oracle.com/javaee/6/api/javax/inject/Qualifier.html">Qualifiers</a> that can help match the specific class that you want injected. If you have multiple payment types, you might add a qualifier for whether it is asynchronous or not. While you can use the <code>@Named</code> annotation as a qualifier, you shouldn&#8217;t as it is provided for exposing the beans in EL.</p>
<p>CDI handles the injection of beans with mismatched scopes through the use of proxies. Because of this you can inject a request scoped bean into a session scoped bean and the reference will still be valid on each request because for each request, the proxy re-connects to a live instance of the request scoped bean.</p>
<p>CDI also has support for interceptors, events, the new conversation scope and many other features which makes it a much better choice over JSF managed beans.</p>
<h2>EJB</h2>
<p>EJBs predate CDI beans and are in someways similar to CDI beans and in other ways very different. Primarily, the differences between CDI beans and EJBs is that EJBs are :</p>
<ul>
<li>Transactional </li>
<li>Remote or local </li>
<li>Able to passivate stateful beans freeing up resources</li>
<li>Able to make use of timers</li>
<li>Can be asynchronous</li>
</ul>
<p>The two types of EJBs are called stateless and stateful. Stateless EJBs can be thought of as thread safe single-use beans that don&#8217;t maintain any state between two web requests. Stateful EJBs do hold state and can be created and sit around for as long as they are needed until they are disposed of. </p>
<p>Defining an EJB is simple, you just add either a <a href="http://docs.oracle.com/javaee/6/api/javax/ejb/Stateless.html">javax.ejb.Stateless</a> or <a href="http://docs.oracle.com/javaee/6/api/javax/ejb/Stateful.html">javax.ejb.Stateful</a> annotation to the class.</p>
<pre class="brush: java;">@Stateless
public class BookingService {

  public String makeReservation(Item Item,Customer customer) {
    ...
    ...
  }
}
</pre>
<p>Stateless beans must have a dependent scope while a stateful session bean can have any scope. By default they are transactional, but you can use the transaction attribute annotation.</p>
<p>While EJBs and CDI beans are very different in terms of feaures, writing the code to integrate them is very similar since CDI beans can be injected into EJBs and EJBs can be injected into CDI beans. There is no need to make any distinction when injecting one into the other. Again, the different scopes are handled by CDI through the use of proxying. One exception to this is that CDI does not support the injection of remote EJBs but that can be implemented by writing a simple producer method for it.</p>
<p>The <a href="http://docs.oracle.com/javaee/6/api/javax/inject/Named.html">javax.inject.Named</a> annotation as well as any <a href="http://docs.oracle.com/javaee/6/api/javax/inject/Qualifier.html">Qualifiers</a> can be used on an EJB to match it to an injection point.</p>
<h1>When to use which bean</h1>
<p>How do you know when to use which bean? Simple.</p>
<p>Never use JSF managed beans unless you are working in a servlet container and don&#8217;t want to try and get CDI working in Tomcat (although I have a <a href="http://www.andygibson.net/blog/projects/knappsack/">Maven archetype</a> for that so there&#8217;s no excuse).</p>
<p>In general, you should use CDI beans unless you need the advanced functionality available in the EJBs such as transactional functions. You can write your own <a href="http://smokeandice.blogspot.com/2009/12/cdi-and-declarative-transactions.html">interceptor to make CDI beans transactional</a>, but for now, its simpler to use an EJB until CDI gets transactional CDI beans which is just around the corner. If you are stuck in a servlet container and are using CDI, then either hand written transactions or your own transaction interceptor is the only option without EJBs.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/qaw3R6LxtQw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/comparing-jsf-beans-cdi-beans-and-ejbs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/article/comparing-jsf-beans-cdi-beans-and-ejbs/</feedburner:origLink></item>
		<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 2</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/-subA8g94Ho/</link>
		<comments>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 12:28:33 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1841</guid>
		<description><![CDATA[In this second article on implementing Spring MVC in Java EE 6 we&#8217;ll take the metadata we extracted in part one and use it to invoke request mapped controller methods in response to web requests and then direct the user to a web page based on the result of the method. In this article we&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>In this second article on implementing Spring MVC in Java EE 6 we&#8217;ll take the metadata we extracted in <a href="http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/">part one</a> and use it to invoke request mapped controller methods in response to web requests and then direct the user to a web page based on the result of the method. <span id="more-1841"></span></p>
<p>In this article we&#8217;ll be implementing the following functions, the code for which is available for <a href='http://www.andygibson.net/blog/wp-content/uploads/2012/01/mvcdi_part2.zip'>download</a> :</p>
<ul>
<li>Write a servlet that will dispatch the requests to our MVC handler class.</li>
<li>In the MVC Handler, we&#8217;ll take a web request and invoke the appropriate controller method</li>
<li>Take the result from the request mapped method and resolve it to a view which the user is forwarded to</li>
</ul>
<h1>Implementing the Servlet</h1>
<p>Our servlet code takes incoming requests and delegates them to the injected <code>MvcHandler</code> instance.</p>
<pre class="brush: java;">@WebServlet(urlPatterns = &quot;/demo/*&quot;)
public class DelegatingServlet extends HttpServlet {

    @Inject
    private MvcHandler mvcHandler;

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doHandleRequest(req, resp, RequestMethod.GET);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doHandleRequest(req, resp, RequestMethod.POST);
    }

    private void doHandleRequest(HttpServletRequest request, HttpServletResponse response,
        RequestMethod requestMethod) {

        mvcHandler.handleRequest(request.getPathInfo(),requestMethod,request,
            response,getServletContext());
    }
}
</pre>
<p>Our servlet uses the <code>@WebServlet</code> annotation to register the servlet for the <code>/demo/*</code> url path. It injects the instance of our <code>MvcHandler</code> class and uses it to handle the <code>GET</code> and <code>POST</code> requests. When we call the MVC handler, we have to pass in multiple objects that will be used by the handler. Looking ahead, we can see this is going to grow since we have controller methods, model values, outcomes and view names to pass around so we&#8217;ll create a new object called a <code>RequestContext</code> that will keep a hold of all these things and we can pass all those items around as a single object. </p>
<p>It makes our method calls look nicer with fewer parameters and we don&#8217;t have to keep adding parameters to methods for each new piece of information needed. Working with a single context means we can break the handler down to a specific set of steps with the product of each method (i.e. fetch model values) being held in the context and used in the next method. It also means we can convert it to an interface and/or abstract some of the information available to provide different implementations (i.e portal version). For now, we just need a basic version with a servlet context, request, response objects. We&#8217;ll also need to store the controller, the controller method and the outcome from that method.</p>
<pre class="brush: java;">public class RequestContext {

    private final ServletContext servletContext;
    private final HttpServletRequest request;
    private final HttpServletResponse response;
    private final RequestMethod requestMethod;
    private Object controller;
    private ControllerMethod method;
    private Object outcome;

    public RequestContext(ServletContext servletContext,
            HttpServletRequest request, HttpServletResponse response,
            RequestMethod requestMethod) {
        this.servletContext = servletContext;
        this.request = request;
        this.response = response;
        this.requestMethod = requestMethod;
    }

    //getters and setters omitted
}
</pre>
<h1>Implementing the MVC Handler</h1>
<p>Going back to our MVC Handler, the code in this class pulls everything together and orchestrates things as it receives calls from the servlet.</p>
<pre class="brush: java;">public class MvcHandler {

    @Inject
    private ControllerInfo controllerInfo;

    @Inject
    private ControllerMethodMatcher matcher;

    @Inject
    private BeanManager beanManager;    

	public void handleRequest(RequestContext context) {

		//find the controller method that best matches the request
		context.setMethod(matcher.findMatching(controllerInfo, context));

		if (context.getMethod() != null) {
			Object controller = locateController(context.getMethod().getControllerClass());
			context.setController(controller);
			// start executing the controller method
			executeControllerMethod(context);
			handleResponse(context);
		} else {
			throw new RuntimeException(&quot;Unable to find method for &quot;
					+ context.getRequestMethod() + &quot; request with url &quot;
					+ context.getPath());
		}
	}

    private void handleResponse(RequestContext context) {
        if (context.getOutcome() instanceof String) {
            String outcome = (String) context.getOutcome();
            String view = &quot;/&quot;+outcome+&quot;.jsp&quot;;
            context.forwardTo(view);
        }
    }

    private Object locateController(Class&amp;lt;?&amp;gt; controllerClass) {
          //returns a bean of type controllerClass from CDI
    }

    private void executeControllerMethod(RequestContext context) {
       //executes the controller method on the controller
    }
}
</pre>
<p>We inject our instance of <code>ControllerInfo</code> which holds all the controller methods and the <code>handleRequest()</code> method is called from the servlet when receives a web request. In order to service the request it takes the following steps :</p>
<ul>
<li>Find a matching controller method for this request. </li>
<li>Locate the controller </li>
<li>Execute the controller method on that controller instance saving the outcome returned from the method. </li>
<li>Handle the correct response back to the user. </li>
</ul>
<p>For now, we are just assuming the controller method returns a string that indicates the view name which we forward to. I added a method to handle forwarding on the request context object.</p>
<h2>Matching Methods</h2>
<p>The <code>ControllerMethodMatcher</code> is an interface that can be used to locate a controller method in the list of controller methods that matches the incoming request info held in the request context</p>
<pre class="brush: java;">public interface ControllerMethodMatcher {
    ControllerMethod findMatching(ControllerInfo info,RequestContext context);
}
</pre>
<p>Our default implementation of this is really simple for now. We iterate through our list of controller methods and check that the request type matches the request method of the incoming request. If it does, then as long as the url path starts with the controller level prefix and ends with the method level suffix, then it is a match. Because we already sorted the controller methods in order of the larger expressions first, we know that the first match we come across is the best for now.</p>
<pre class="brush: java;">public class DefaultControllerMatcher implements ControllerMethodMatcher {

    public ControllerMethod findMatching(ControllerInfo info,RequestContext context) {
        for (ControllerMethod method : info.getControllerMethods()) {
            if (matches(method, context)) {
                return method;
            }
        }
        return null;
    }

    protected boolean matches(ControllerMethod methodToTest, RequestContext context) {
        String path = context.getPath();
        boolean result = methodToTest.matchesRequestMethod(context.getRequestMethod())
            &amp;&amp; (methodToTest.getPrefix() == null || path.startsWith(methodToTest.getPrefix()))
            &amp;&amp; (methodToTest.getSuffix() == null || path.endsWith(methodToTest.getSuffix()));
        return result;
    }
}
</pre>
<p>We can override this class, and re-implement the <code>matches</code> method later on and since we pass in the <code>RequestContext</code> we will have all sorts of information available to us to determine the best match. </p>
<h2>Executing the Controller Method</h2>
<p>We can just use reflection to execute the controller method instance for now. We assume that there are no params for now, that will come later.</p>
<pre class="brush: java;">
private void executeControllerMethod(RequestContext context) {
	Method javaMethod = context.getMethod().getMethod();
	Object outcome = null;
	try {
		outcome = javaMethod.invoke(context.getController());
	} catch (Exception e) {
		e.printStackTrace();
	}
	context.setOutcome(outcome);
}
</pre>
<h2>Seeing it in action</h2>
<p>Finally we can put it all together so we can see it in action in a web application. For now our MVC code is in our web project to make integrating it easier. We can later extract the MVC code to a stand-alone module to use as a library in other projects.  We&#8217;ve already set up a controller and our servlet, now we just need to create a couple of pages based on the string returned from the mapped methods. If we run the application now and go to a url such as <a href="http://localhost:8080/mvcdi/demo/person/list">http://localhost:8080/mvcdi/demo/person/list</a> we will get an error message because <code>listPeople.jsp</code> doesn&#8217;t exist. We&#8217;ll create the following simple jsp pages so we can display something in the browser. Each page just consists of the boilerplate structure and some text that indicates which page we are on.</p>
<pre class="brush: xml;">
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;View Person&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    View Person
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We do this for the following pages in the root of the web directory.</p>
<ul>
<li><code>viewPerson.jsp</code></li>
<li><code>listPeople.jsp</code></li>
<li><code>updatedPerson.jsp</code></li>
<li><code>editPerson.jsp</code> (see below for additional changes)</li>
</ul>
<p>The one different page is the <code>editPerson.jsp</code> page where we want to put a form containing only a button so we can issue a <code>POST</code> request which maps to the method on the controller that handles the <code>POST</code> request from the <code>editPerson.jsp</code> page and navigates to the <code>updatedPerson.jsp</code> page in response.</p>
<pre class="brush: java;">
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Editing Person&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        Editing Person
        &lt;form method=&quot;post&quot;&gt;
            Some Form Here&lt;br/&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Update&quot; /&gt;
        &lt;/form&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If we go to <a href="http://localhost:8080/mvcdi/demo/person/edit">http://localhost:8080/mvcdi/demo/person/edit</a> and click the submit button, we get sent to the page that tells us we just updated someone because that is the page returned from the controller method for the <code>edit</code> path with a <code>POST</code> request method.</p>
<p>You can download (<a href='http://www.andygibson.net/blog/wp-content/uploads/2012/01/mvcdi_part2.zip'>mvcdi_part2.zip</a>) the code for this as a maven project that can run on any Java EE 6 container and has been tested on  both JBoss AS 7 and Glassfish 3.1.1.</p>
<p>This wraps up the second installment of this series on implementing Spring MVC in Java EE 6 and CDI and covers the bulk of the request mapping so we can direct our web requests to controller methods and ultimately to specific pages. Next time we&#8217;ll look at providing model data to the pages.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/-subA8g94Ho" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/</feedburner:origLink></item>
		<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 1</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/OOu10w3PCDk/</link>
		<comments>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 12:30:36 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1829</guid>
		<description><![CDATA[One of the opinions I&#8217;ve had over the last couple of years is that Spring makes things look really easy, and CDI is a great dependency injection framework. Throw in this article suggesting you can build your own Java EE 7 and it sounds like a challenge, so for fun, I thought I might have [...]]]></description>
			<content:encoded><![CDATA[<p>One of the opinions I&#8217;ve had over the last couple of years is that Spring makes things look really easy, and CDI is a great dependency injection framework. Throw in this article suggesting you can <a href="http://java.dzone.com/articles/cdi-extensions-you-can-build">build your own Java EE 7</a> and it sounds like a challenge, so for fun, I thought I might have a go at implementing a subset of Spring MVC on top of CDI with Java EE 6.<span id="more-1829"></span></p>
<p>Interestingly, there&#8217;s nothing like Spring MVC for Java EE which is a shame because it is a really good framework. So in this series of articles, I&#8217;ll be covering different aspects of implementing Spring MVC on CDI with the caveat that this won&#8217;t be an exact compatible replica. I&#8217;ll be implementing just enough of each feature to demonstrate that it can be done, but I&#8217;ll leave enough room so that with more work, it can be a more accurate implementation. It goes without saying that these articles assume you are familiar with Spring MVC 3 using annotations and at least a little bit familiar with CDI. I&#8217;ll also mention that the code listed in the articles only contains the code relevant to the implementation for demonstration purposes. I&#8217;ve removed a lot of the null checks and other defensive programming code to make things more readable but they are still present in the final code.</p>
<p>In this first part, we will start by laying all the dull ground work as we capture the metadata from the MVC annotations in the following steps : </p>
<ul>
<li>Define our MVC annotations</li>
<li>Define a class to hold our request mapped methods</li>
<li>Write some code to extract the request mapped methods from a given class and store the metadata</li>
</ul>
<h1>The MVC annotations</h1>
<p>To get started we implement the controller and request mapping annotations which are based on the Spring MVC versions. <code>@Controller</code> marks our classes as MVC controllers that implement MVC methods. Each method that can be mapped to a URL is mapped with the <code>@RequestMapping</code> annotation.</p>
<pre class="brush: java;">@Target({ ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}
</pre>
<p>The request mapping annotation has two attributes (for now), the default <code>value</code> which contains an array of paths that are mapped to this controller or method. For now, we will implement simple path matching, the url must start with the controller path and end with the path defined on the method. We can change to a more complex wildcard/Ant path matching implementation if we want to later. The other attribute on the request mapping is an array of <code>RequestMethod</code> types that indicates the type of requests we want to map to this controller and method. For now, we&#8217;ll just deal with <code>POST</code>, <code>GET</code> and <code>DELETE</code> request types :</p>
<pre class="brush: java;">
public enum RequestMethod {
    POST,GET,DELETE
}
</pre>
<p>Now we can define our request mapping annotation :</p>
<pre class="brush: java;">
@Target({ ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {

    String[] value() default {};
    RequestMethod[] method() default {};
}
</pre>
<p>Armed with our new annotations, we can go ahead and create our first controller :</p>
<pre class="brush: java;">
@Controller
@RequestMapping(&amp;quot;/person/&amp;quot;)
public class PersonController {

    @RequestMapping(&amp;quot;list&amp;quot;)
    public String doListPeople() {
        return &amp;quot;listPeople&amp;quot;;
    }

    @RequestMapping(&amp;quot;view&amp;quot;)
    public String doViewPerson() {
        return &amp;quot;viewPerson&amp;quot;;
    }

    @RequestMapping(value=&amp;quot;edit&amp;quot;,method=RequestMethod.GET)
    public String doGetEditPerson() {
        return &amp;quot;editPerson&amp;quot;;
    }

    @RequestMapping(value=&amp;quot;edit&amp;quot;,method=RequestMethod.POST)
    public String doPostUpdatePerson() {
        return &amp;quot;updatePerson&amp;quot;;
    }
}
</pre>
<p>For now, our controller methods return a String which can be used to determine the final view to render.</p>
<h1>The MVC CDI Handler</h1>
<p>Originally, I considered writing this as a <a href="http://docs.jboss.org/weld/reference/1.0.1-Final/en-US/html/extend.html">CDI extension</a> but felt that it wasn&#8217;t a good match and instead chose to create a managed <code>MvcHandler</code> bean that will be invoked by the servlet and will lazily initialize its own configuration post construction. This led to a more modular design since I could make the <code>MvcHandler</code> the center of the implementation and it let me write it in a purely managed environment saving me from having to deal with some of the limits extension have compared to managed beans.</p>
<p>Technically, when a web request comes in, we could get a list of controllers and iterate through them to find a matching controller and then search for a method on that controller that matches our request. However, I&#8217;m extracting and storing all that metadata on startup since it is more efficient and will allow for more expansion later on. When we start examining different types of metadata, it will get ridiculous doing it all at run time. Also, it lets us optimize a bit since we could have several matches, but some will be better matches than others so we will always need to compare all the controller methods each time a request comes in. Pre-reading it lets us also presort the controller methods into best-fit-first.</p>
<h1>Extracting Controller Metadata</h1>
<p>We&#8217;ll create a class called <code>ControllerInfo</code> that holds the metadata for the controllers. It does this by taking the controller class and iterating through its methods and seeing if they have the request mapping annotation on them. If they do, those methods are added to a list of <code>ControllerMethod</code> objects. This object holds info about a specific mapped method on a controller : </p>
<pre class="brush: java;">
public class ControllerMethod {
    private final String prefix;
    private final String suffix;
    private final RequestMethod[] requestMethod;
    private final Method method;

  //getters and setters
}
</pre>
<p>The prefix is determined from the request mapping path on the controller class, and the suffix is determined from the request mapping on the method. The request method value indicates which kinds of request methods this method can be mapped to (<code>GET</code> or <code>POST</code> requests). The <code>Method</code> object is a java reflection <code>Method</code> instance that we can use to not only define the class method that is mapped, but also reference the declaring class for when we need to locate the controller bean. Since the path value can be an array of strings if a particular method has multiple paths in the value then there will be mulitple <code>ControllerMethod</code> entries, one for each path as the suffix. However, we don&#8217;t split up multiple request method values instead opting to store them as they are as an array.</p>
<pre class="brush: java;">
@Controller
@RequestMapping(&amp;quot;/somePath/&amp;quot;)
public class MyController {

   @RequestMapping(value={&amp;quot;page1.do&amp;quot;,&amp;quot;page2.do&amp;quot;},method={GET,POST})
  public void someMethod() {
     ...
  }
}
</pre>
<p>The above class results in two entries : </p>
<table border=1 width="100%">
<tr>
<th>Prefix</th>
<th>Suffix</th>
<th>Request Methods</th>
<th>Method</th>
</tr>
<tr>
<td><code>/somePath/</code></td>
<td><code>page1.do</code></td>
<td><code>GET,POST</code></td>
<td>MyController.someMethod()</td>
</tr>
<tr>
<td><code>/somePath/</code></td>
<td><code>page2.do</code></td>
<td><code>GET,POST</code></td>
<td>MyController.someMethod()</td>
</tr>
</table>
<p>The reason for this is it lets us optimize the path matching based on the best match first by sorting based on the length of the suffix path. Again, we can improve this ordering later on by using a better path matcher.</p>
<p>Now we&#8217;ve a place to store the controller method information, we can implement the <code>ControllerInfo</code> class which contains the list of Controller method instances:</p>
<pre class="brush: java;">
@ApplicationScoped
public class ControllerInfo {

    private final List&amp;lt;ControllerMethod&amp;gt; controllerMethods = new ArrayList&amp;lt;ControllerMethod&amp;gt;();

    private static final String[] DEFAULT_MAPPING_PATHS = new String[] { &amp;quot;&amp;quot; };

    public static final AnnotationLiteral&amp;amp;lt;Controller&amp;amp;gt; CONTROLLER_LITERAL = new AnnotationLiteral&amp;amp;lt;Controller&amp;amp;gt;() {
        private static final long serialVersionUID = -3226395594698453241L;
    };

    @Inject
    private BeanManager beanManager;

    @PostConstruct
    public void initialize() {
        Set&amp;amp;lt;Bean&amp;amp;lt;?&amp;amp;gt;&amp;amp;gt; controllers = beanManager.getBeans(Object.class,CONTROLLER_LITERAL);
        for (Bean&amp;amp;lt;?&amp;amp;gt; bean : controllers) {
            add(bean.getBeanClass());
        }
        sortControllerMethods();
    }

    private void add(Class&amp;amp;lt;?&amp;amp;gt; clazz) {
    }
}
</pre>
<p>The initialize method is invoked when this bean is first created. As we&#8217;ll see later, this bean is injected into the <code>MvcHandler</code> so this method is only called when needed. It uses the CDI API to locate all beans with a controller qualifier annotation and calls the <code>add(Class&lt;?&gt; clazz)</code> method for each controller class. Finally it makes a call to sort our list of <code>ControllerMethod</code> instances.</p>
<p>In the <code>add</code> method, for the given controller class, we iterate through its methods and see if we can add them as a request mapped method.</p>
<pre class="brush: java;">
private void add(Class&amp;amp;lt;?&amp;amp;gt; clazz) {
    if (clazz.isAnnotationPresent(Controller.class)) {

        Method[] methods = clazz.getMethods();
        String[] controllerPaths = null;

        RequestMapping rm = clazz.getAnnotation(RequestMapping.class);

        if (rm != null) {
            controllerPaths = rm.value();
        }

        // if no paths are specified, then default to one blank path so we always add it
        if (controllerPaths == null || controllerPaths.length == 0) {
            controllerPaths = DEFAULT_MAPPING_PATHS;
        }

        // add methods for each mapped path at the controller level
        for (String prefix : controllerPaths) {
            for (Method m : methods) {
                addMethod(prefix, m);
            }
        }
    }
}

private void addMethod(String prefix, Method javaMethod) {

    RequestMapping mapping = javaMethod.getAnnotation(RequestMapping.class);
    if (mapping != null) {

        String[] paths = mapping.value();

        // if these are blank, fill with defaults
        if (paths == null || paths.length == 0) {
            paths = DEFAULT_MAPPING_PATHS;
        }

        for (String path : paths) {
            controllerMethods.add(new ControllerMethod(javaMethod, prefix,path, mapping.method()));
        }

    }
}
</pre>
<p>The <code>addMethod</code> function will check for a request mapping annotation on the method, extract the metadata and store it in the list.</p>
<p>This about wraps up the first installment which covers the extraction of request mapped methods and storing them for use later on. Next time we&#8217;ll start coding our servlet and core MVC handler that will let us make web requests and invoke the mapped methods on our controller before displaying the appropriate web page.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/OOu10w3PCDk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/</feedburner:origLink></item>
		<item>
		<title>More Time Saved By Unit Tests</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/upx4lv6BmeM/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 07:10:59 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[DataValve]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1815</guid>
		<description><![CDATA[So I&#8217;ve been meaning to make a fix in one of my projects for a while, and I haven&#8217;t touched the code in over a year, so of course I have to go back and really get back up to speed with the code. The change was for the Datavalve project and it was to [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been meaning to make a fix in one of my projects for a while, and I haven&#8217;t touched the code in over a year, so of course I have to go back and really get back up to speed with the code. The change was for the Datavalve project and it was to include support for passing in collections and using <code>in</code> SQL Statements, so now you can use something like :</p>
<pre class="brush: java;">
provider.addRestriction(&quot;item.statusCode in (:param)&quot;, stateCodeList);
</pre>
<p>This will cause the list of codes to be expanded into an <code>in</code> SQL statement including checking to exclude null items, and as usual, the restriction is not included if the code list is null or contains only null items.</p>
<p>So I have two problems, the first is getting back up to speed on my code, figuring out where the make the change, and making it. The second is making sure my code changes don&#8217;t break anything thats currently working. </p>
<p>For the first problem, I decide to create the unit tests first so I can verify that the change does as expected. Obviously, the tests fail initially, but by looking at the code executed by the tests, I can start to pick out places where I need to start looking to add the new code. After all, tests measure the correctness of the state after the code has been executed. What better place to start looking than seeing what code the test executes. After finding the method that I need to change, I make my code changes and run my tests. All my original tests pass with flying colors, but my new test fails. I take a peek and sure enough I left off the last line of code to add the built object to a list. I put it in, and I have all my tests up and running. </p>
<p>All in all, I&#8217;ve made a large change to some sizable (12K+ LOC) code that I haven&#8217;t seen in over a year, verified that the change works and that it hasn&#8217;t impacted any other code. Not bad for an hour.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/upx4lv6BmeM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/</feedburner:origLink></item>
		<item>
		<title>I’m Back</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/cIqeyLKhYcY/</link>
		<comments>http://www.andygibson.net/blog/personal/im-back/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 03:33:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1808</guid>
		<description><![CDATA[So I&#8217;ve been on a bit of break from blogging, I&#8217;ve had lots of things going on, I&#8217;ve moved house twice, and changed jobs a couple of times. I&#8217;ve not even really been checking my email that much (as evidenced by the fact that I didn&#8217;t see my hosting invoices and the subsequent temporary suspension [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been on a bit of break from blogging, I&#8217;ve had lots of things going on, I&#8217;ve moved house twice, and changed jobs a couple of times. I&#8217;ve not even really been checking my email that much (as evidenced by the fact that I didn&#8217;t see my hosting invoices and the subsequent temporary suspension of my blogging web site). I&#8217;ve been spending time with the family over summer and taking a bit of a break from the extra-curricular IT work. I&#8217;ve also been doing some thinking on which direction I want to go in my career. Because of all this,  If you&#8217;ve emailed, or sent a LinkedIn request that I&#8217;ve done nothing with, that&#8217;s why.  However, things have been hotting up in my absence so there&#8217;s certainly a lot of topics to delve into.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/cIqeyLKhYcY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/personal/im-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/personal/im-back/</feedburner:origLink></item>
		<item>
		<title>JSTL 1.2 Missing From Maven Repositories</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/ow4QZplnxMg/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 12:45:04 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1802</guid>
		<description><![CDATA[It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a number of issues around the web. Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one javax.servlet.jstl [...]]]></description>
			<content:encoded><![CDATA[<p>It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a <a href="http://www.google.com/search?q=jstl%201.2%20missing">number of issues</a> around the web.</p>
<p>Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one <code>javax.servlet.jstl</code> dependency you will use the following :</p>
<pre class="brush: xml;">
&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;org.glassfish.web&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-impl&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p>If you are running code in a container that already contains JSTL you will just use the <code>jstl-api</code> dependency with a <code>scope</code> of <code>provided</code>. This way your code has access to the API that will be provided by the container.</p>
<p>For those of you using the Knappsack archetypes or using the JBoss Java EE 6 API pom, or no doubt some other dependencies that use <code>javax.servlet.jstl</code>, you will have problems because the Java EE 6 pom relies on the <code>javax.servlet.jstl</code> dependency. The answer here is to exclude it from the Java EE 6 dependency and add it separately using the api dependencies described above.</p>
<pre class="brush: xml;">
&lt;dependency&gt;
    &lt;groupId&gt;org.jboss.spec&lt;/groupId&gt;
    &lt;artifactId&gt;jboss-javaee-6.0&lt;/artifactId&gt;
    &lt;version&gt;1.0.0.Final&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
    &lt;type&gt;pom&lt;/type&gt;
    &lt;exclusions&gt;
        &lt;exclusion&gt;
            &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
            &lt;artifactId&gt;jstl&lt;/artifactId&gt;
        &lt;/exclusion&gt;
    &lt;/exclusions&gt;

&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>I&#8217;m surprised that they would eliminate the pom like that, but it may have been due to licensing issues for the reference implementation which I believe has been an issue for some of the standard Java EE APIs and the reason that there is no real definitive deployment of the APIs and we have to mix and match API dependencies from different sources unless you are using the <a href="http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/">JBoss Java EE 6 dependency</a> to solve the problem.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/ow4QZplnxMg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/</feedburner:origLink></item>
		<item>
		<title>Update</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/AlVDTAWIKus/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/1799/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 01:46:53 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1799</guid>
		<description><![CDATA[I haven&#8217;t been writing for a while since I&#8217;ve been busy working on several things right now. First off, after a few months of job hunting, I&#8217;ve changed jobs, I&#8217;m now doing some Java contract work down in Pittsburgh. After 11 years at my old job, it was time to move on. The great thing [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t been writing for a while since I&#8217;ve been busy working on several things right now.</p>
<p>First off, after a few months of job hunting, I&#8217;ve changed jobs, I&#8217;m now doing some Java contract work down in Pittsburgh. After 11 years at my old job, it was time to move on. The great thing about contract work is the opportunity to work on a lot of different projects in a lot of different places. After being stuck in Cleveland for 11 years, we are ready for some changes.</p>
<p>I also want to try and get into doing some more Java EE 6 and CDI training. A lot of people are unsure of how it is all meant to work together and are missing out on the real beauty and simplicity of working with these frameworks.</p>
<p>Rick, Rob and I have been doing some more work with CDISource and anticipate a release of our source in the next few weeks. Once thats out, I want to start playing with some of the Seam 3 stuff especially with regards to CDI. We announced CDISource and then all of a sudden we all got busy with different things, and we have some code we want to release for which we have a number of articles to write.</p>
<p>Between moving, unpacking, starting a new gig, which always fries the brain for a few weeks, and having my Mum over from Manchester,England, I haven&#8217;t really been having time to write or work on projects. </p>
<p>I have a new release of the Knappsack almost ready to go which includes Spring based archetypes and also a Java EE 6 EAR archetype as well as a couple of new posts.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/AlVDTAWIKus" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/1799/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/quickbyte/1799/</feedburner:origLink></item>
		<item>
		<title>Announcing CDISource</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/qX816ScYiEE/</link>
		<comments>http://www.andygibson.net/blog/article/announcing-cdisource/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 13:38:01 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[CDISource]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1787</guid>
		<description><![CDATA[In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is [...]]]></description>
			<content:encoded><![CDATA[<p>In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is for intertwining various historical and literary references in his posts. The result of this is the <a href="https://sites.google.com/site/cdipojo/get-started">CDISource</a> project which aims to advocate and facilitate the use of the JSR 299 &#8211; Java Contexts and Dependency Injection framework across the Java landscape.</p>
<p>If you&#8217;ve seen my posts or my site before, you&#8217;ll no doubt be aware that I have written at great length about Java EE 6, JSF, CDI , EJB and so on. What I haven&#8217;t written about is the many frustrations I&#8217;ve come up against in dealing with these frameworks on their own and especially when combined, or how their usefulness is often constrained to the application server container. </p>
<p>Java EE in some ways is an archipelago of frameworks that lacks the cohesiveness and all in one wide screen vision that software developers need. Java EE is about the enterprise, in reality its about the web, or even more specifically about Java EE containers. There&#8217;s a whole slew of uses for a good type safe and flexible dependency injection and AOP framework and such as CDI outside of Java EE containers but there is very little information and code to make it actually work.  </p>
<p>Our goal is to make CDI useful and usable on its own without Java EE 6, and to give developers the tools and information to do so. To let them write vendor neutral and portable code, and apply agile and best practices. Developers know how to write good software and don&#8217;t want to sacrifice that for the sake of using a framework to make things easier. To that end we aim to provide code and information that will help facilitate those practices. </p>
<p>There will be some learning for ourselves along the way and we will have to change some of our previously held concepts. I know over the last few weeks having been  getting CDI working and useful outside of the web container it has really altered my perspective on how I think about the dependencies and structure in CDI applications. My perspective has changed even more than when I wrote <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>. </p>
<p>As much as I hate to say it, we did come up with a mission statement, although we found it fairly easy and enjoyable to clearly defined the goals and attitudes of the project. </p>
<p>Our mission is to :</p>
<ul>
<li>Promote and facilitate the use of the Java Context and Dependency Injection (CDI) framework in relation to as many aspects of application development as possible.</li>
<li>Enable developers to take advantage of CDI independently of Java EE.</li>
<li>Provide lightweight, lean and agile access to the underlying CDI container as a core principle in our efforts.</li>
<li>Make testing easy without requiring a complex set of tools or complex deployment scenarios.</li>
<li>Enhance both Java EE development as well as the use of CDI in non Java EE application where possible.</li>
<li>Promote and enable the use of CDI in a vendor neutral environment and maximize the portability of application code across CDI implementations.</li>
<li>Not reject the ideas of Java EE but expand the usability of CDI outside the borders of Java EE application servers with frameworks that are not a part of the specification.</li>
<li>Not reject other CDI efforts but to provide another venue to promote those efforts. This is an addition. This is another voice in support of CDI.</li>
</ul>
<p>We are pretty excited that so far we have been able to live up to the intent of our mission statement with everything we&#8217;ve done so far. Over the next few days and weeks you will see articles and tutorials come out of Rick, Rob and I as we write about the CDISource project and we start to showcase some of the code we have written and start giving you an idea of where we are heading.  </p>
<p>Right now we have vendor neutral support for starting up CDI outside of the web container and also for testing CDI beans with minimal configuration and intrusion on your test cases. We also have a few other pieces that are nearly ready, as well as dozens of ideas to get started on.</p>
<p>You can start by looking at Ricks brand new <a href="http://java.dzone.com/articles/cdi-di-p1">introduction of CDI</a> over on JavaLobby.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/qX816ScYiEE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/announcing-cdisource/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/article/announcing-cdisource/</feedburner:origLink></item>
		<item>
		<title>Simple RESTful services in Glassfish Pt 2</title>
		<link>http://feedproxy.google.com/~r/andygibson/uhrp/~3/gCH0vCPVb_E/</link>
		<comments>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 12:39:13 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1765</guid>
		<description><![CDATA[In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page. In part 1, we looked at creating simple web services and now [...]]]></description>
			<content:encoded><![CDATA[<p>In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page.<br />
<span id="more-1765"></span><br />
In part 1, we looked at creating simple web services and now we&#8217;re going to look at making something more practical and interesting. We&#8217;ll start from where we left off with the source code as it was at the end of the part 1 which you can download from here (<a href="http://www.andygibson.net/blog/wp-content/uploads/2011/02/restwebdemo_pt1.zip">restwebdemo_pt1</a>) if you want to follow along. If not, the final source can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>).</p>
<ol>
<li>First off, we&#8217;re going to change the entity manager that is available for injection to be request scoped. To do this, open up <code>DataRepositoryProducer.java</code> and change the <code>@ConversationScoped</code> annotation on the <code>getEntityManager()</code> method to be <code>@RequestScoped</code>.  The reason for this is documented here in <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>.</li>
<li>Next we are going to create a simple dao for Course objects, and the only reason to do this is to demonstrate the integration of CDI and the ability to layer your code. Create a new class called <code>CourseDao</code> with the following code.
<pre class="brush: java;">
package org.fluttercode.restwebdemo.bean;

@Stateless
@LocalBean
public class CourseDao {

	@Inject @DataRepository
	private EntityManager entityManager;

	public void save(Course course) {
		entityManager.persist(course);
	}

	public Course update(Course course) {
		return entityManager.merge(course);
	}

	public Course find(Long id) {
		return entityManager.find(Course.class, id);
	}
}
</pre>
<p>This just injects an entityManager and uses it to locate, save and update Course objects.
</li>
<li>Now create a new <code>CourseService</code> bean that will handle the web services. To start with we want to make it a stateless EJB and inject the course Dao. We are going start by re-implementing the method to return the course name for the given id.
<pre class="brush: java;">
	@Path(&quot;courseName/{id}&quot;)
	@GET
	public String getCourseName(@PathParam(&quot;id&quot;) Long id) {
		Course course = courseDao.find(id);
		if (course == null) {
			return &quot;Course not found&quot;;
		} else {
			return course.getTitle();
		}
	}
</pre>
</ol>
<p>To see this method in action, deploy the application and go to <a href="http://localhost:8080/restwebdemo/rest/course/courseName/126">http://localhost:8080/restwebdemo/rest/course/courseName/126</a>. Now we know everything is working and hooked up together, we can look at adding some new functionality. </p>
<p>Let&#8217;s start by returning a course with a given id from the service. This is fairly simple given what we already know. The only thing to determine now is what format to return the object as and to convert it to that type. Luckily, Java EE already provides JAXB which can take an object graph and convert it to XML for us as long as we annotate the classes with the annotations to let the JAXB implementation know how to convert it. The same annotations can be used by the body writer that handles JSON.</p>
<p>First we&#8217;ll annotate the <code>Course</code> class and make a couple of changes that we need to. Next we&#8217;ll create methods to return a <code>Cource</code> object from the service in XML or JSON format.</p>
<ol>
<li>Open the <code>Course</code> class and add the following annotations to the class. </p>
<pre class="brush: java;">
@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Course extends BaseEntity {
   ...
   ...
}
</pre>
<p>This tells the JAXB processor that this class can be serialized and to access the values using fields in the class. This also means that any other annotations we want to add to control the serialization needs to be applied to the fields.
</li>
<p>This is a simple example, so we don&#8217;t want to serialize the <code>teacher</code> or <code>enrolled</code> properties which we can do by marking them with the <code>@XmlTransient</code> attributes. Also, remove the <code>@NotNull</code> annotation from the <code>teacher</code> attribute as we will need it blank later. The following code shows the fields with both the JAXB and JPA annotations. JAXB (like JPA) uses default conventions for fields that don&#8217;t have annotations : </p>
<pre class="brush: java;">
	@Column(length = 32, nullable = false)
	@Size(max = 32)
	@NotEmpty(message = &quot;title is required&quot;)
	private String title;

	@Column(length = 8, nullable = false)
	@Size(max = 8  )
	@NotEmpty(message = &quot;code is required&quot;)
	private String code;

	@ManyToOne(fetch = FetchType.LAZY)
	@XmlTransient
	private Teacher teacher;

	@ManyToMany(mappedBy = &quot;enrolled&quot;)
	@XmlTransient
	private List&lt;Student&gt; students = new ArrayList&lt;Student&gt;();
</pre>
<p>We are just using a simple JAXB model for the sake of the example which is why we aren&#8217;t including the <code>Teacher</code> and <code>Student</code> classes.
</li>
<li>Now in our <code>CourseService</code> class we will create methods to return the course entity and we will create one for JSON and one for XML.
<pre class="brush: java;">
	@Path(&quot;find/{id}/xml&quot;)
	@GET
	@Produces(MediaType.APPLICATION_XML)
	public Course getCourseAsXml(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}

	@Path(&quot;find/{id}/json&quot;)
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Course getCourseAsJson(@PathParam(&quot;id&quot;) Long id) {
		return courseDao.find(id);
	}
</pre>
</li>
<p><small>(note : At this point, I had to switch to using Hibernate as the JPA provider since JAXB didn&#8217;t like the interface EclipseLink used for proxying the properties. You can do this using the Glassfish update tool).</small><br />
If you redeploy the application and browse to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/json">http://localhost:8080/restwebdemo/rest/course/find/1/json</a> you should be prompted to save a file, or it will display the text, but the content should be something like : </p>
<pre class="brush: plain;">
{&quot;createdOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;id&quot;:&quot;1&quot;,
  &quot;modifiedOn&quot;:&quot;2010-08-27T16:36:57.015-04:00&quot;,
  &quot;title&quot;:&quot;Computing for Beginners&quot;,
   &quot;code&quot;:&quot;CS101&quot;}
</pre>
<p>or if you go to <a href="http://localhost:8080/restwebdemo/rest/course/find/1/xml">http://localhost:8080/restwebdemo/rest/course/find/1/xml</a> you will get an XML version :</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;course&gt;
	&lt;createdOn&gt;2010-08-27T16:36:57.015-04:00&lt;/createdOn&gt;
	&lt;id&gt;1&lt;/id&gt;
	&lt;modifiedOn&gt;2010-08-27T16:36:57.015-04:00&lt;/modifiedOn&gt;
	&lt;title&gt;Computing for Beginners&lt;/title&gt;
	&lt;code&gt;CS101&lt;/code&gt;
&lt;/course&gt;
</pre>
<p>Now we can grab objects from our web service, we should look at creating objects from the service. We add a new method that takes the title and code values, creates a new <code>Course</code> with those values and saves it using the <code>courseDao</code>.</p>
<pre class="brush: java;">
	@Path(&quot;create&quot;)
	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	public Course createCourse(@FormParam(&quot;title&quot;) String title,@FormParam(&quot;code&quot;) String code) {
		Course course = new Course();
		course.setTitle(title);
		course.setCode(code);
		courseDao.save(course);
		return course;
	}
</pre>
<p>Here I&#8217;ve used the <code>FormParam</code> annotations to plug form values into the method call. You&#8217;ll notice that using REST conventions, the method to create a course uses the PUT type of request. Now let&#8217;s create a page to enter a title and code and create the course. Notice that our method returns the created course so we can return the course back to the user. This is probably not ideal, but suits for the purposes of demonstration. Now lets create a new HTML page to allow for data entry and calling the web service to create the Course.</p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;script type=&quot;text/javascript&quot;
	src=&quot;http://localhost:8080/restwebdemo/jquery-1.4.min.js&quot;&gt;
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;message&quot;
	style=&quot;display: none; background: #d0d0f0; padding: 12px&quot;&gt;Message Div&lt;/div&gt;
&lt;form action=&quot;rest/course/create&quot; method=&quot;POST&quot;&gt;

    &lt;fieldset&gt;
    	&lt;legend&gt;Create Course&lt;/legend&gt;
    	&lt;p&gt;
	        Title&lt;br /&gt;
    	    &lt;input id=&quot;title&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;p&gt;
        	Code&lt;br /&gt;
        	&lt;input id=&quot;code&quot; /&gt;&lt;br /&gt;
    	&lt;/p&gt;
    	&lt;input type=&quot;submit&quot; id=&quot;submit&quot; /&gt;
	&lt;/fieldset&gt;
&lt;/form&gt;
&lt;/body&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

//jquery pieces
$(document).ready(function() {

    //change the submit button behaviouus.
    $('#submit').click(function () {
		var title = $(&quot;input#title&quot;).val();
		var code = $(&quot;input#code&quot;).val();

		params = &quot;title=&quot;+title+&quot;&amp;code=&quot;+code;
		//alert(&quot;posting form : &quot;+data);
        $.ajax({
               type: &quot;PUT&quot;,
               url: &quot;rest/course/create&quot;,
               data: params,
               success: function(result) {
        		   showMessage(&quot;Created Course &quot;+result.title+&quot; with id &quot;+result.id+&quot; on &quot;+result.createdOn);
               }
        });
		return false;
    });
});

function showMessage(msg) {
	  $('#message').html(msg);
	  $('#message').fadeIn('fast');
	   $('#message').delay(3000).fadeOut('slow');
}
&lt;/script&gt;
&lt;/html&gt;
</pre>
<p>This looks a lot code, but not really. We import jquery to help us post our form, and we create our form with the two fields. We use JQuery to add an event handler so when you click submit, it packages up the form, calls our web service with a PUT type of request and grabs the returned object as a JSON object, and displays a message using the values from the new instance obtained from the server. To verify that your course has been created, go to the <a href="http://localhost:8080/restwebdemo/home.jsf">front page</a> and you should see it listed.</p>
<p>That about wraps it up for this post, the source code can be downloaded from (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>), just unzip it, use <code>mvn clean package</code> and deploy the war to glassfish and use the URLs mentioned in the article.</p>
<img src="http://feeds.feedburner.com/~r/andygibson/uhrp/~4/gCH0vCPVb_E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/</feedburner:origLink></item>
	</channel>
</rss>

