<?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; CDI</title>
	<atom:link href="http://www.andygibson.net/blog/tag/cdi/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Thu, 02 Feb 2012 14:33:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language></language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 2</title>
		<link>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/</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>
]]></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>0</slash:comments>
		</item>
		<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 1</title>
		<link>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/</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>
]]></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>
		</item>
		<item>
		<title>Announcing CDISource</title>
		<link>http://www.andygibson.net/blog/article/announcing-cdisource/</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>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/announcing-cdisource/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Simple RESTful services in Glassfish Pt 2</title>
		<link>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/</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>
]]></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>
		</item>
		<item>
		<title>JBoss Java EE 6 spec dependency in Maven</title>
		<link>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 13:52:47 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Knappsack]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1733</guid>
		<description><![CDATA[Adam Bien wrote about the Troubled with the crippled Java EE 6 APIs in Maven and a solution for them. Another solution has presented itself now that JBoss has finalized the Java EE 6 spec pom and added it to their public repositories as of early January 2011. You can include the spec in your [...]]]></description>
			<content:encoded><![CDATA[<p>Adam Bien wrote about the <a href="http://www.adam-bien.com/roller/abien/entry/trouble_with_crippled_java_ee">Troubled with the crippled Java EE 6 APIs in Maven</a> and a solution for them. Another solution has presented itself now that JBoss has finalized the Java EE 6 spec pom and added it to their public repositories as of early January 2011.</p>
<p>You can include the spec in your own project by adding the following to your <code>pom.xml</code> :</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;type&gt;pom&lt;/type&gt;
&lt;/dependency&gt;
</pre>
<p>You may also need to add the JBoss repository to your <code>pom.xml</code> which is defined as :</p>
<pre class="brush: xml;">
&lt;repositories&gt;
	&lt;repository&gt;
		&lt;id&gt;repository.jboss.org&lt;/id&gt;
		&lt;name&gt;JBoss Repository&lt;/name&gt;
		&lt;url&gt;http://repository.jboss.org/nexus/content/groups/public-jboss/&lt;/url&gt;
	&lt;/repository&gt;
&lt;/repositories&gt;
</pre>
<p>I&#8217;ll be adding this pom to the Knappsack archetypes to resolve some of the issues people have been facing with the broken spec dependency.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Little Less Conversation&#8230;</title>
		<link>http://www.andygibson.net/blog/article/a-little-less-conversation/</link>
		<comments>http://www.andygibson.net/blog/article/a-little-less-conversation/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 13:11:07 +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[JEE]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1718</guid>
		<description><![CDATA[One thing that I wrote that I haven&#8217;t really gotten around to examining and verifying in closer detail and validating my position on is the production of the conversational entity manager in the Knappsack archetypes. This article looks at this and re-evaluates my thinking on the use of conversational contexts in CDI. Defaulting to Request [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that I wrote that I haven&#8217;t really gotten around to examining and verifying in closer detail and validating my position on is the production of the conversational entity manager in the Knappsack archetypes.  This article looks at this and re-evaluates my thinking on the use of conversational contexts in CDI.<br />
<span id="more-1718"></span><br />
<H1>Defaulting to Request Scoped</h1>
<p>It&#8217;s one of those things that you write and it works, but something feels wrong with it, and I haven&#8217;t had time to go back and look at it. The entity manager is scoped to the conversation so that it will work with as both conversational and request scoped. When an object is scoped to the conversation and there is no long running conversation then the conversation itself is limited to the request so your data, although conversation scoped becomes request scoped. This was a handy way to default data that was mostly request scoped to a request scope while giving it the ability to partake in active conversations.  In Seam, this was fairly standard practice since it allowed your model to live in a conversational entity manager without having to worry about detachment issues. However, CDI conversations are different from Seam conversations and their use needs to be a little more focused.</p>
<p>The problem is that CDI is supported in a number of environments within Java EE 6  while the conversation scope is not. To name a few, servlets and web services don&#8217;t have default support for conversations and Arquillian tests doesn&#8217;t handle conversations well. While we may be able to work around non-conversational servlets, web services and arquillian tests, the problem really goes deeper.</p>
<p>Logically we are thinking about using these beans as request scoped beans because there is no long running conversation. However, the conversational context still needs to be initialized and available to hold these beans. CDI doesn&#8217;t magically know to put the conversational beans in the request scope context when there&#8217;s no long running conversation, it always puts it in the conversational context.</p>
<p>So, the answer you say is to use request scoped beans and relegate a conversational scope to those cases where you really do need a conversational scope, and not use it everywhere you want request scoped but might need a conversation scoped bean. While this is true, our request scoped beans depend on business logic beans that in turn use the data layer beans that uses our entity manager to access the database. The problem is that the entity manager is conversation scoped so all our beans that depend on it are broken. </p>
<p>The end result is that using some of the tools and API&#8217;s with CDI has been rather frustrating since nearly every bean depends on the entity manager at the end of the day and without conversation support it typically breaks with an obscure error message.</p>
<p>The solution is to treat our entity manager like our beans, we only use conversations where absolutely necessary. The question you may be asking yourselves is how to deal with code that is both request and conversation scoped. For example, you load an entity at the start of a wizard into a conversation scoped bean using a conversation scoped entity manager because you want to keep this bean attached for the duration of the conversation. At the end of the conversation, you might want to use the standard request scoped entity Dao to save the entity. Will the request scoped Dao will use a different entity manager from the conversation scoped bean or not? The good news is that we can re-use the same entity manager sourced from the same place and offered up as a request scoped entity manager to get around this so they will use the same entity manager.</p>
<p>Additionally, the introduction of some of the new JSF 2.0 scopes helps out since we can use the flash or view scopes to pass objects from one page to the next or to maintain state between requests. The only problem here is that these scopes are in JSF and not compatible with CDI, or implemented in CDI by default. The Seam 3 faces module provides CDI compatible alternatives and I would put good money on those scopes making it into the next version of CDI.</p>
<h1>Lesson Learned</h1>
<p>One take away from this is to always make sure everything will play nice together before committing to a particular strategy or design. It would have been a shame to implement our data access layer and find out that we couldn&#8217;t use it in our web services or testing. </p>
<p>I&#8217;ll be trying to spend a little time working all this out and seeing what the best strategies are, but hopefully this will remove some of the barriers to demonstrating and adding third party integrations into the Knappsack archetypes. This will probably get changed for the next version of the Knappsack archetypes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/a-little-less-conversation/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Handling missing resources with CDI Events</title>
		<link>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/</link>
		<comments>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/#comments</comments>
		<pubDate>Tue, 11 Jan 2011 14:18:04 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Master]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1604</guid>
		<description><![CDATA[In part 1, we created a simple application that made use of string resource bundles in JSF and in part 2 we extended it by using CDI to inject the resource provider into beans so we can re-use our code for accessing locale specific string based resources. One benefit of using CDI to inject your [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/">part 1</a>, we created a simple application that made use of string resource bundles in JSF and in <a href="http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/">part 2</a>  we extended it by using CDI to inject the resource provider into beans so we can re-use our code for accessing locale specific string based resources.<br />
<span id="more-1604"></span><br />
One benefit of using CDI to inject your beans instead of just creating them manually is the ability to utilize the event mechanism within those beans. In this example, we are going to fire an event when we discover a resource is missing. </p>
<ol>
<li>Start by creating a <code>MissingResourceInfo</code> class that stores the info regarding the missing resource (key and locale). This will be passed along with the event so the observer has all the info when it receives the event.</p>
<pre class="brush: java;">
public class MissingResourceInfo {

	private final String key;
	private final String locale;

	public MissingResourceInfo(String key, Locale locale) {
		this(key, locale.getDisplayName());
	}

	public MissingResourceInfo(String key, String locale) {
		super();
		this.key = key;
		this.locale = locale;
	}

	public String getKey() {
		return key;
	}

	public String getLocale() {
		return locale;
	}
}
</pre>
</li>
<li>We fire an event when we discover a resource key is missing from the locale specific properties file being used. In the <code>MessageProvider</code> class from part 2, we inject the <code>Event</code> instance in to a field and modify the <code>getValue</code> method to fire off the event when a key is missing.
<pre class="brush: java;">
@RequestScoped
public class MessageProvider {

	@Inject
	private Event&lt;MissingResourceInfo&gt; event;
	....
	....
	public String getValue(String key) {
		String result = null;
		try {
			result = getBundle().getString(key);
		} catch (MissingResourceException e) {
			result = &quot;???&quot; + key + &quot;??? not found&quot;;
			event.fire(new MissingResourceInfo(key, getBundle().getLocale()));
		}
		return result;
	}
}
</pre>
</li>
<li>Finally, we want to add an observer for that event that handles it when it is fired. To do this, we will add a new class for this purpose.
<pre class="brush: java;">
public class MissingResourceObserver {

	public void observeMissingResources(@Observes MissingResourceInfo info) {
		String template = &quot;Oh noes! %s key is missing in locale %s&quot;;
		String msg = String.format(template, info.getKey(), info.getLocale());
		System.out.println(msg);
	}

}
</pre>
</li>
<li>Finally, to see it in action, we need to add bean getter to fetch a non-existing value from the bundle.
<pre class="brush: java;">
@Named
@RequestScoped
public class AnotherBean {

	public String getMissingResource() {
		return provider.getValue(&quot;ImNotHere&quot;);
	}
}
</pre>
</li>
<li>We can see this in action by adding to our JSF page a call to this property
<pre class="brush: xml;">
#{anotherBean.missingResource}
</pre>
<p>Results in the following being displayed in the console :</p>
<pre class="brush: plain;">
Oh noes! 'ImNotHere' key is missing from locale English (United States)
</pre>
</li>
</ol>
<p>Remember, you can have as many event observers as you want so you can have one that just logs it to the console or one that emails if missing text strings are urgent (i.e. production). You could have it write the missing values to the database so during development cycles, the missing strings can be exported and put into the properties files. This is especially useful if you have third parties handling the translation where you can send them a list of missing items to translate in one big batch.</p>
<h1>What about EL?</h1>
<p>This works great when we are accessing resource bundles from Java, but what about when we are using EL expressions to access the values. JSF channels those expressions straight to the resource bundle without the ability to intercept them. One way to fix this would be to write our own EL expression resolver and see if the root of the expression maps to a resource bundle and if so try to obtain the value from the bundle and fire the event if the item is not found. This would work, but it seems overkill since every EL expression  would end up going through the resolver.<br />
Remember that the syntax for accessing resource strings in EL is <code>#{bundlename.key}</code>, and Java <code>Map</code> classes can also be accessed using the same syntax. What we can do is create a named bean that (barely) implements the map interface and in the <code>get</code> method, it gets the value from the injected resource bundle. This means EL expressions will use our Map bean and we can delegate the call to the Message provider which will handle missing expressions.</p>
<ol>
<li>Start by creating a new bean that implements the <code>Map</code> interface. Most of the methods will throw exceptions that they are not implemented, we only really care about the method to get values.</p>
<pre class="brush: java;">
@Named(&quot;messages&quot;)
@RequestScoped
public class ResourceMap implements Map&lt;String, String&gt; {

	@Inject
	private MessageProvider provider;

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	@Override
	public boolean containsKey(Object key) {
		return provider.getBundle().containsKey((String) key);
	}

	@Override
	public boolean containsValue(Object value) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

	@Override
	public String get(Object key) {
		return provider.getValue((String) key);
	}

	@Override
	public String put(String key, String value) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

	@Override
	public String remove(Object key) {
		throw new RuntimeException(&quot;Not implemented&quot;);
	}

       ....
       ....
       ....
}
</pre>
<p>If the interface method isn&#8217;t listed, assume it throws a &#8220;not implemented&#8221; exception. We inject the <code>MessageProvider</code> instance so we can re-use our message provider bean to fetch messages and fire the events. </li>
<li>
We gave the bean the name <code>messages</code>  so if we go to our web page and add the following to our page :</p>
<pre class="brush: xml;">
First name from map = #{messages.firstName}&lt;br/&gt;
Missing name from map = #{messages.missingValue}&lt;br/&gt;
</pre>
<p>When we run our application and refresh the page, we get the value displayed for <code>messages.firstName</code>, and a missing value for <code>messages.missingValue</code>. In our server log we get </p>
<pre class="brush: plain;">
Oh noes! missingValue key is missing in locale English (United States)
</pre>
<p>Since we re-used the <code>MessageProvider</code> bean, it fires the event when it cannot find a key value so even though we called it from the JSF page, it ended up being routed through to our message provider and the event being fired.
</li>
</ol>
<p>How you use this is up to you, but since the syntax is the same whether you use the Map or the JSF resource variable, you can switch between the two depending on whether it is a development or production environment. You may also use different event handlers depending on the deployment environment. Alternatively, you may be worried about performance in production, or the fact that you lose autocompletion if you use the map in development.<br />
To switch implementations, just give either the JSF resource variable, in <code>faces-config</code> or the <code>MessageProvider</code> bean the name used for your resource string component. You can switch components without having to change either your code or your JSF pages.</p>
<p><a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourceEventDemo.zip'>Download the Maven source code</a> for this project and run it locally by typing unzipping it and running <code>mvn clean jetty:run</code> in the command line, and going to <a href="http://localhost:8080/resourcedemo/">http://localhost:8080/resourcedemo/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Injecting String Resource Services with CDI</title>
		<link>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/</link>
		<comments>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 15:02:26 +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[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[JSF]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1601</guid>
		<description><![CDATA[In this post we looked at adding String resource bundles to our JSF applications to move our string constants into external resources that we can define for different locales. Now I want to extend that example to show how you can expand on that by using injection to access those resources. We finished off with [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.andygibson.net/blog/article/resource-bundles-in-jsf-2-0-applications/">this post</a> we looked at adding String resource bundles to our JSF applications to move our string constants into external resources that we can define for different locales. Now I want to extend that example to show how you can expand on that by using injection to access those resources.<br />
<span id="more-1601"></span><br />
We finished off with a <code>MessageProvider</code> class that was responsible for fetching the resource bundle and had methods for fetching values from that bundle. We created this class manually and accessed the string resources from it. The problem here is that we need to keep on recreating the provider in each piece of code that needs it.</p>
<h1>Doing things the CDI way</h1>
<p>You could construct an instance of the <code>MessageProvider</code> each time you need it, but instead, we should look at how we can change our existing code to make it more CDI like. We can make the method that fetches the bundle a producer method and then inject the resource bundle where needed. If we give it a long enough scope, we can re-use it in the same request. </p>
<p>First we&#8217;ll write a new Qualifier for the bundle so we can uniquely identify this bundle in a type safe manner. We may want to produce and inject multiple resources that will all be of the same type (<code>ResourceBundle</code>) so using a qualifier is a probably a good idea.</p>
<pre class="brush: java;">
@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface MessageBundle {

}
</pre>
<p>We&#8217;ll add a <code>@Produces</code> annotation to the <code>getBundle()</code> method.</p>
<pre class="brush: java;">
public class MessageProvider {

     @Produces @MessageBundle
     public ResourceBundle getBundle() {
		if (bundle == null) {
			FacesContext context = FacesContext.getCurrentInstance();
			bundle = context.getApplication().getResourceBundle(context, &quot;msgs&quot;);
		}
		return bundle;
	}
	...
        ...
        ...
}
</pre>
<p>Now we just need to inject this into our bean and use the injected bundle instead of constructing our own instance of the <code>MessageProvider</code> class.</p>
<pre class="brush: java;">
@Named
@RequestScoped
public class SomeBean {

	@Inject @MessageBundle
	private ResourceBundle bundle;

	public String getMessage() {
		String msg = null;
		String key = &quot;someMessage&quot;;
		try {
			msg = bundle.getString(key);
		} catch (MissingResourceException e) {
			msg = &quot;??&quot;+key+&quot;?? is missing!&quot;;
		}
		return MessageFormat.format(msg, &quot;SomeValue&quot;);
	}
}
</pre>
<p>While this is more CDI-ish, it does have the problem that it consists of more code since we re-produce the exception handling code each time. So we probably need to use something that consists of more than just the bundle, say maybe the whole <code>MessageProvider</code> class with the methods to fetch key values. The beauty here is that we we don&#8217;t need to do anything to achieve this except give the <code>MessageProvider</code> class a scope : </p>
<pre class="brush: java;">
@RequestScoped
public class MessageProvider {
    ....
    ....
}
</pre>
<p>No we just add an injection point for the <code>MessageProvider</code> class in our bean. We&#8217;ll create a new bean for this called <code>AnotherBean</code> :</p>
<pre class="brush: java;">
@Named
@RequestScoped
public class AnotherBean {

	@Inject
	private MessageProvider provider;

	public String getFirstNameCaption() {
		return provider.getValue(&quot;firstName&quot;);
	}
}
</pre>
<p>In our JSF page we add a reference to the property to display the value :</p>
<pre class="brush: xml;">
First Name Caption = #{anotherBean.firstNameCaption}
</pre>
<p>This results in the following text being displayed :</p>
<pre class="brush: xml;">
First Name Caption = First Name
</pre>
<p>You might notice that our old bean is still using the resource bundle from the producer method, and everything is still working. This is because beans can be injectable and still contain producer methods. You will also find that across the request, the injected instance of the bundle is always the same as the one in <code>provider.getBundle()</code>. This is because every time the bundle is produced, the <code>MessageProvider</code> is constructed and put into request scope and the bundle value is returned. This bundle value is retained in the <code>MessageProvider</code> instance. No matter how many times we inject the bundle, the same one is used, even though we didn&#8217;t give it a request scope. This is actually a useful thing because the resource bundle cannot be proxied by CDI so it cannot be put into request scope itself, but it can be put into request scope if it is contained in another bean (in this case, the <code>MessageProvider</code>).</p>
<p>This shows not only how flexible CDI is in making objects available to your applications, but how easy it is to tweak how those objects are made available, all without changing the underlying code.</p>
<p>Next time we&#8217;ll look at using event handling to notify us of missing resources.</p>
<p>You can <a href='http://www.andygibson.net/blog/wp-content/uploads/2010/10/resourceInjectionDemo.zip'>download the Maven source code</a> for this project and run it locally by unzipping it and running <code>mvn clean jetty:run</code> in the command line and going to <a href="http://localhost:8080/resourcedemo/">http://localhost:8080/resourcedemo/</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/injecting-string-resource-services-with-cdi/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>CDI @Alternative Info</title>
		<link>http://www.andygibson.net/blog/quickbyte/cdi-alternative-info/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/cdi-alternative-info/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 03:02:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1591</guid>
		<description><![CDATA[The @Alternative CDI annotation allows you to have multiple matching dependencies for a given injection point. This means you can define beans that provide implementations for the same interface without worrying about ambigious dependency errors. When you mark a class with the @Alternative annotation, it is effectively disabled and cannot be considered for injection. The [...]]]></description>
			<content:encoded><![CDATA[<p>The @Alternative CDI annotation allows you to have multiple matching dependencies for a given injection point. This means you can define beans that provide implementations for the same interface without worrying about ambigious dependency errors. When you mark a class with the @Alternative annotation, it is effectively disabled and cannot be considered for injection. The only exception is for the class that is defined in the <code>beans.xml</code> configuration file. </p>
<pre class="brush: xml;">
&lt;alternatives&gt;
	&lt;class&gt;org.company.project.bean.SomeBean&lt;/class&gt;
&lt;/alternatives&gt;
</pre>
<p>Once this bean is identified, it is then used in any injection point that matches for this bean. No other beans for similar injection points can be declared as the &#8216;active&#8217; alternative.</p>
<p>Alternative is really an odd name for it, but all it does is disable the bean while adding it to the <code>beans.xml</code> file enables it and makes it available to CDI.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/cdi-alternative-info/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JBoss 6.0.0 M5 Has Been Released</title>
		<link>http://www.andygibson.net/blog/news/jboss-6-0-0-m5-has-been-released/</link>
		<comments>http://www.andygibson.net/blog/news/jboss-6-0-0-m5-has-been-released/#comments</comments>
		<pubDate>Sun, 26 Sep 2010 15:03:28 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JBoss]]></category>
		<category><![CDATA[Seam]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1561</guid>
		<description><![CDATA[It looks like JBoss 6.0 milestone 5 has just been released. Not that anyone would know it since they haven&#8217;t announced it anywhere, I just saw Aslak Knutsen tweet it. Dan Allen also posted slides from his JavaOne presentation on Weld and the future of Seam.]]></description>
			<content:encoded><![CDATA[<p>It looks like JBoss 6.0 milestone 5 has just <a href="http://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.M5/">been released</a>. Not that anyone would know it since they haven&#8217;t announced it anywhere, I just saw Aslak Knutsen tweet it. Dan Allen also <a href="http://www.slideshare.net/mojavelinux/jsr299-cdi-weld-the-future-of-seam-javaone-2010">posted slides</a> from his JavaOne presentation on Weld and the future of Seam.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/news/jboss-6-0-0-m5-has-been-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

