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

<channel>
	<title>Andy Gibson &#187; Articles</title>
	<atom:link href="http://www.andygibson.net/blog/category/article/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Tue, 07 Feb 2012 14:19:07 +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>Comparing JSF Beans, CDI Beans and EJBs</title>
		<link>http://www.andygibson.net/blog/article/comparing-jsf-beans-cdi-beans-and-ejbs/</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>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/comparing-jsf-beans-cdi-beans-and-ejbs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>Double the speed of (some of) your JSF pages (and dodge bugs too)</title>
		<link>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/</link>
		<comments>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/#comments</comments>
		<pubDate>Thu, 17 Mar 2011 12:49:39 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></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=1771</guid>
		<description><![CDATA[There was a thread on the JSF LinkedIn group about JSF performance and a number of people complained about the fact that as part of the restore view phase, JSF reconstructs the component tree including binding data to data tables causing unnecessary fetches of data from the database. This article looks at one way of [...]]]></description>
			<content:encoded><![CDATA[<p>There was a thread on the JSF LinkedIn group about JSF performance and a number of people complained about the fact that as part of the restore view phase, JSF reconstructs the component tree including binding data to data tables causing unnecessary fetches of data from the database. This article looks at one way of avoiding the additional work to fetch the data.<br />
<span id="more-1771"></span><br />
When you first do a postback, the restore view phase rebuilds the tree, including fetching the data to bind it to the data table. Why you ask, well a good question. Typically this wouldn&#8217;t be an issue since we want the server state to match the client view state. However, as the developer, we know that for some cases these results are useless since we don&#8217;t anticipate using them for anything so fetching them is really a waste of time. </p>
<p>Let&#8217;s take a look at this problem in action. You can use the maven archetype to generate the project and code along or download the source from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/fastapp.zip'>fastapp.zip</a>).</p>
<ol>
<li>Create a new maven application using the jee6-servlet-basic knappsack archetype. This gives you an empty Java EE 6 application that can be run using Jetty or Tomcat from the command line.</li>
<li>Add a new class that will be our backing bean that returns a list of paginated numbers but takes a long time (2 seconds) to do it.
<pre class="brush: java;">
@Named
@RequestScoped
public class DataBean {

	//indicates the page we are on
	private int pageNumber = 0;	

	//lazy loaded reference to the results
	private List&lt;Integer&gt; data;

	//returns the list of data by lazy loading it
	public List&lt;Integer&gt; getData() {
		if (data == null) {
			data = generateData();
		}
		return data;
	}

	//generates the list of data, think of this as an expensive DB operation
	private List&lt;Integer&gt; generateData()  {
		System.out.println(&quot;Generating Data starting from &quot;+pageNumber);

		//Sleep for 2 seconds while I access the database and do stuff
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		//now we actually generate the data
		List&lt;Integer&gt; results = new ArrayList&lt;Integer&gt;();
		for (int i = 0;i &lt; 10;i++) {
			results.add(pageNumber+i);
		}
		return results;

	}

	//method to move to the next page in the list
	public void nextPage() {
		pageNumber = pageNumber+10;
		//invalidate the lazy loaded data
		data = null;
	}

	//method to move to the previous page in the list
	public void previousPage() {
		pageNumber = pageNumber-10;
		//invalidate the lazy loaded data
		data = null;
	}

	//getter/setter for page number
	public int getPageNumber() {
		return pageNumber;
	}
	public void setPageNumber(int pageNumber) {
		this.pageNumber = pageNumber;
	}
}
</pre>
<p>We lazy load the results so for each request, we start with nothing and then load the results when the restore view phase looks for them. In the render response phase, the same results are used unless the next/previous page methods are called and the data value is set to null and invalidated. In this case when the data is requested in the render response phase, we see it is null and so it will be loaded fresh for the new page number.
</li>
<li>Now we modify the existing home.xhtml page to show a table and add two buttons to move to the previous and next pages.
<pre class="brush: xml;">
&lt;ui:define name=&quot;content&quot;&gt;

	&lt;h:dataTable value=&quot;#{dataBean.data}&quot; var=&quot;v_value&quot;&gt;
		&lt;h:column&gt;
			&lt;f:facet name=&quot;header&quot;&gt;Value&lt;/f:facet&gt;
			#{v_value}
		&lt;/h:column&gt;
	&lt;/h:dataTable&gt;
	&lt;h:form&gt;
		&lt;h:commandButton action=&quot;#{dataBean.previousPage}&quot; value=&quot;Previous&quot; /&gt;
		Page #{dataBean.pageNumber}
		&lt;h:commandButton action=&quot;#{dataBean.nextPage}&quot; value=&quot;Next&quot; /&gt;
		&lt;h:inputHidden value=&quot;#{dataBean.pageNumber}&quot; /&gt;
	&lt;/h:form&gt;
&lt;/ui:define&gt;
</pre>
<p>Fairly straightforward, we just show the list of numbers and have buttons for navigating. We store the page number in a hidden field and post it back to our backing bean so we have a stateless setup. I also added a phase listener that I&#8217;ve used before to log the timing of the JSF requests that is documented in this post (<a href="http://www.andygibson.net/blog/tutorial/timing-jsf-requests-using-a-phase-listener/">Timing JSF Requests using a Phase Listener</a>). Since this was for Seam originally I modified it by removing the logger code and just pushing the log text to <code>System.out</code>. You can turn it on and off by removing it from the <code>faces-config.xml</code> file in the <code>lifecycle</code> section.
</li>
<li>In a command console enter <code>mvn clean jetty:run</code> to start the server and go to the home page at <a href="http://localhost:8080/fastapp/home.jsf">http://localhost:8080/fastapp/home.jsf</a>.
</li>
</ol>
<p>When you first go to the page, you trigger a GET request which will cause the data to be loaded one time and displayed. In our output log we see :</p>
<pre class="brush: plain;">
Generating Data starting from 0
</pre>
<p>Fantastic. At this point, we know the page took 2 seconds to render. If we click the next or previous buttons, we cause a postback which will restore the view (including rebuilding the data) and then change the page number which will invalidate the data before again rebuilding the data for the new page. We see this in the log as  :</p>
<pre class="brush: plain;">
Generating Data starting from 0
Generating Data starting from 10
</pre>
<p>If you are using the phase listener to time it, you will see the two requests as :</p>
<pre class="brush: plain;">
//first request initiated
Executed Phase RESTORE_VIEW 1
Generating Data starting from 0
Execution Time = 2228ms
Executed Phase RENDER_RESPONSE 6

//click next page to trigger the postback and response
Generating Data starting from 0
Executed Phase RESTORE_VIEW 1
Executed Phase APPLY_REQUEST_VALUES 2
Executed Phase PROCESS_VALIDATIONS 3
Executed Phase UPDATE_MODEL_VALUES 4
Executed Phase INVOKE_APPLICATION 5
Generating Data starting from 10
Execution Time = 4116ms
Executed Phase RENDER_RESPONSE 6
</pre>
<p>You can see the first request took 2 seconds while the second request took over 4 seconds. The problem here is that the data is being fetched twice, once for the restore view and again for the rendering of the response with the new data as you can see in the phase listener log entries.</p>
<h1>Solution</h1>
<p>The solution to the problem is to skip fetching the data the first time altogether. It isn&#8217;t needed, it isn&#8217;t even used and it isn&#8217;t even the correct data (don&#8217;t worry, I&#8217;ll explain that later). In the <code>FacesContext</code> object there is a method called <code>getRenderResponse()</code> which returns true if the render response method has been called and we are in the rendering phase. Until we are rendering the page, we don&#8217;t really need our data so we only load it if this method returns true.</p>
<pre class="brush: java;">
	//generates the list of data, think of this as an expensive DB operation
	private List&lt;Integer&gt; generateData()  {
		if (!FacesContext.getCurrentInstance().getRenderResponse()) {
			return null;
		}
		System.out.println(&quot;Generating Data starting from &quot;+pageNumber);
		...
		...
		...
	}
</pre>
<p>It&#8217;s that simple, now redeploy the application load the page and click next, this time, we only get one data fetch per page request even on postbacks because we don&#8217;t bother loading the data until we really need it in the render response and if you look at the timing, our pages are loading twice as fast since we only fetch half the data.</p>
<pre class="brush: plain;">
//initial request
Executed Phase RESTORE_VIEW 1
Generating Data starting from 0
Execution Time = 2278ms
Executed Phase RENDER_RESPONSE 6

//click the next button to trigger a postback - look, no data loaded until the response is rendered
Executed Phase RESTORE_VIEW 1
Executed Phase APPLY_REQUEST_VALUES 2
Executed Phase PROCESS_VALIDATIONS 3
Executed Phase UPDATE_MODEL_VALUES 4
Executed Phase INVOKE_APPLICATION 5
Generating Data starting from 10
Execution Time = 2302ms
Executed Phase RENDER_RESPONSE 6
</pre>
<p>So there you go, you can increase the speed of your JSF pages by only loading data when you really need it, I guess kind of lazy lazy loading data.</p>
<h1>What about that bug we are dodging?</h1>
<p>Ah yes, that thing, not sure if it can be called a bug but to see the problem, remove the code to check for the render response so we do the double data request on postbacks. Now load up the application and click the next button twice, and you should see the following log :</p>
<pre class="brush: plain;">
//initial GET request, we only load the data once
Generating Data starting from 0

//Click next, trigger a postback with two data fetches
Generating Data starting from 0
Generating Data starting from 10

//Click next again, trigger a postback with two more fetches.
Generating Data starting from 0 --err, this isn't right it should be 10
Generating Data starting from 20
</pre>
<p>When we do the second postback, the first set of data fetched is starting from position 0. We are loading our data using the default <code>pageNumber</code> value of 0. So not only are we loading data we don&#8217;t need, we are loading the wrong data. This could have consequences if say you are in a search page and the postback triggers an unconstrained search which may take longer than one with search parameters set.</p>
<p>The reason for this is that the restore view process takes place before the request values are applied so the <code>pageNumber</code> is set to the default value of zero which makes the fetching of the data even more useless. I&#8217;m not sure it can be called a bug since the value hasn&#8217;t been set at the restore view phase The question is whether it is correct for the restore view phase to fetch data based on values that haven&#8217;t yet been initialized and if so, what&#8217;s the point?</p>
<h2>A Feature?</h2>
<p>You know, thinking about it, this might really be a feature, not a bug. It&#8217;s feasible to utilize the state of the <code>pageNumber</code> value to determine whether we can return the results if we change its type to <code>Integer</code>. We know that we don&#8217;t need to fetch the data if the page number is <code>null</code> because we haven&#8217;t hit the read request values stage so we must still be in the restore view stage and therefore don&#8217;t need any data.<br />
The only problem comes with the initial setting of the value when you first enter the page, what sets it from null to zero initially. You&#8217;d have to fudge around with the getters and settings, plus it would be hard to display that initial page of results since it would always be empty.</p>
<p>The source code for this project is available from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/fastapp.zip'>fastapp.zip</a>). To run, simply unzip, and in the console, type <code>mvn clean jetty:run</code> or <code>mvn clean tomcat:run</code> and go to <a href="http://localhost:8080/fastapp/home.jsf">http://localhost:8080/fastapp/home.jsf</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/double-the-speed-of-some-of-your-jsf-pages-and-dodge-bugs-too/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Generate Test Data with DataFactory</title>
		<link>http://www.andygibson.net/blog/article/generate-test-data-with-datafactory/</link>
		<comments>http://www.andygibson.net/blog/article/generate-test-data-with-datafactory/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 13:18:51 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[DataFactory]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1751</guid>
		<description><![CDATA[DataFactory is a project I just released which allows you to easily generate test data. It was primarily written for populating database for dev or test environments by providing values for names, addresses, email addresses, phone numbers, text, and dates. To add DataFactory to your maven project, just add it as a dependency in your [...]]]></description>
			<content:encoded><![CDATA[<p>DataFactory is a project I just released which allows you to easily generate test data. It was primarily written for populating database for dev or test environments by providing values for names, addresses, email addresses, phone numbers, text, and dates.<br />
<span id="more-1751"></span><br />
To add DataFactory to your maven project, just add it as a dependency in your <code>pom.xml</code> file.</p>
<pre class="brush: xml;">
&lt;dependency&gt;
	&lt;groupId&gt;org.fluttercode.datafactory&lt;/groupId&gt;
	&lt;artifactId&gt;datafactory&lt;/artifactId&gt;
	&lt;version&gt;0.8&lt;/version&gt;
	&lt;type&gt;jar&lt;/type&gt;
&lt;/dependency&gt;
</pre>
<h1>Generating Test Data</h1>
<p>Now you can create instances of the <code>DataFactory</code> class and create data :</p>
<pre class="brush: java;">
public class Main {

	public static void main(String[] args) {
		DataFactory df = new DataFactory();
		for (int i = 0; i &lt; 100; i++) {
			String name = df.getFirstName() + &quot; &quot;+ df.getLastName();
			System.out.println(name);
		}
	}
}
</pre>
<p>The produced output is :</p>
<pre class="brush: plain;">
Lindsey Craft
Erica Larsen
Ryan Levine
Erika Smith
Brooklyn Sloan
Karen Mayer
Eddie O'neill
Nancy Stevens
</pre>
<p>The <code>DataFactory</code> class can generate different types of values, from addresses to random text to random dates, to dates within a fixed time period.  Addresses and business names can be created using the following code : </p>
<pre class="brush: java;">
DataFactory df = new DataFactory();
for (int i = 0; i &lt; 100; i++) {
	String address = df.getAddress()+&quot;,&quot;+df.getCity()+&quot;,&quot;+df.getNumberText(5);
	String business = df.getBusinessName();
	System.out.println(business + &quot; located at &quot; + address);
}
</pre>
<p>to produce :</p>
<pre class="brush: plain;">
Uvalda Signs located at 1383 Beam Way,Lyons,19316
Alma Accounting located at 1386 Countiss St,Nashville,14967
Fort Stewart Engineering located at 1753 Bethesda Rd,Springfield,26306
Sugar Hill Textiles located at 1141 Loudon Circle,Cordele,83937
Albany Engineering located at 1185 Grieves Avenue,Sugar Hill,36753
Poulan Insurance located at 816 Cohen Blvd,Lake City,74839
Crescent Services located at 1085 Cloveridge Boulevard,Bemiss,08769
</pre>
<h1>Dates</h1>
<p>There are a number of features to create dates, the first being creating a random date which is usually in a given sensible date range. </p>
<pre class="brush: java;">
DataFactory df = new DataFactory();
Date minDate = df.getDate(2000, 1, 1);
Date maxDate = new Date();
for (int i = 0; i &lt; 10; i++) {
	Date start = df.getDateBetween(minDate, maxDate);
	System.out.println(&quot;Date = &quot;+start);
}
</pre>
<p>This produces a list of random dates between 1/1/2000 and the current date. Typically, a random date might be constrained by some other date, for example you can&#8217;t have an end date that occurs before the start date. In this case, you would plug the start date in as the minimum date value :</p>
<pre class="brush: java;">
DataFactory df = new DataFactory();
Date minDate = df.getDate(2000, 1, 1);
Date maxDate = new Date();

for (int i = 0; i &lt; 10; i++) {
	Date start = df.getDateBetween(minDate, maxDate);
	Date end = df.getDateBetween(start, maxDate);
	System.out.println(&quot;Date range = &quot; + dateToString(start) + &quot; to &quot; + dateToString(end));
}
</pre>
<p>The result is a list of dates where the second date is always later than the first : </p>
<pre class="brush: java;">
Date range = 04/29/2005 to 07/16/2006
Date range = 08/07/2009 to 01/19/2010
Date range = 09/22/2000 to 12/15/2003
Date range = 07/31/2004 to 03/24/2009
Date range = 06/27/2003 to 01/10/2007
Date range = 07/10/2003 to 04/02/2008
Date range = 01/04/2003 to 01/12/2005
</pre>
<p>In many cases, you might want your end date to be only within a few days of the start date. For example, helpdesk support tickets or hotel stays don&#8217;t last for years. To do this, you can specify the number of days from the base date you want to generate a result. In this case, we make the end date within 10 days of the begin date : </p>
<pre class="brush: java;">
for (int i = 0; i &lt; 10; i++) {
	Date start = df.getDateBetween(minDate, maxDate);
	Date end = df.getDate(start, 0, 10); //set end to within 10 days of the start
	System.out.println(&quot;Date range = &quot; + dateToString(start) + &quot; to &quot; + dateToString(end));
}
</pre>
<p>And the result : </p>
<pre class="brush: plain;">
Date range = 04/29/2005 to 04/30/2005
Date range = 12/29/2003 to 12/30/2003
Date range = 06/25/2003 to 07/03/2003
Date range = 10/19/2009 to 10/19/2009
</pre>
<p>You can also specify a negative minimum days value that could return a date prior to the base date or a positive minimum date value to get a later date. Here&#8217;s a more complex example that uses different date rules to come up with some complex test data.</p>
<pre class="brush: java;">
for (int i = 0; i &lt; 10; i++) {
	 //generate an order date
	Date orderDate = df.getDateBetween(minDate, maxDate);

	//estimate delivery 4-10 days after ordering
	Date estimatedDeliveryDate = df.getDate(orderDate, 4, 10);

	//deliver between 2 days prior and 3 days after delivery estimate
	Date actualDeliveryDate = df.getDate(estimatedDeliveryDate, -2, 3); 

	String msg =  &quot;Ordered on &quot;+dateToString(orderDate) +
		&quot; deliver by = &quot;+dateToString(estimatedDeliveryDate)+
		&quot; delivered on &quot; + dateToString(actualDeliveryDate);					

	if (estimatedDeliveryDate.before(actualDeliveryDate)) {
		msg = msg + &quot; - LATE&quot;;
	}
	if (estimatedDeliveryDate.after(actualDeliveryDate)) {
		msg = msg + &quot; - EARLY&quot;;
	}
	System.out.println(msg);
}
</pre>
<p>Here we calculate an order date, and create a delivery date that is at least 4 days out but no more than 10, and then we created an actual delivery date that is between 2 days prior and 3 days after the expected delivery date.<br />
Notice how we cherry picked the dates, the estimated delivery date is at least 4 days out from the order date, and the actual delivery date will only be at most 2 days prior to the estimated date. This means the actual delivery date is always at least 2 days out from the order date and we won&#8217;t get a delivery date value that is before the item was ordered. This code produces the following values : </p>
<pre class="brush: plain;">
Ordered on 04/29/2005 deliver by = 05/06/2005 delivered on 05/06/2005
Ordered on 08/07/2009 deliver by = 08/13/2009 delivered on 08/13/2009
Ordered on 09/22/2000 deliver by = 09/27/2000 delivered on 09/25/2000 - EARLY
Ordered on 07/31/2004 deliver by = 08/07/2004 delivered on 08/09/2004 - LATE
Ordered on 06/27/2003 deliver by = 07/04/2003 delivered on 07/04/2003
Ordered on 07/10/2003 deliver by = 07/19/2003 delivered on 07/18/2003 - EARLY
Ordered on 01/04/2003 deliver by = 01/08/2003 delivered on 01/08/2003
</pre>
<h1>Custom Random Values</h1>
<p>If there is a set of values that is very specific to your application that you might want to generate data from, you can use methods on the <code>DataFactory</code> class to return values with the option for it to be randomly be a default value.</p>
<pre class="brush: java;">
	public static void main(String[] args) {
		DataFactory df = new DataFactory();

		//favorite animal
		String[] values = {&quot;Cat&quot;,&quot;Dog&quot;,&quot;Goat&quot;,&quot;Horse&quot;,&quot;Sheep&quot;};
		for (int i = 0; i &lt; 100; i++) {
			System.out.println(df.getItem(values,80,&quot;None&quot;));
		}
	}
</pre>
<p>This example uses the array of animals and returns a value with a 20% chance of  being the default value of &#8220;None&#8221; to produce the following : </p>
<pre class="brush: plain;">
Sheep
None
Dog
Horse
</pre>
<h1>Textual Data</h1>
<p>Random text data comes in two forms, absolutely random data and text data made up of words. You can generate either using the following methods : </p>
<pre class="brush: java;">
DataFactory df = new DataFactory();
System.out.println(df.getRandomText(20, 25));
System.out.println(df.getRandomChars(20));
System.out.println(df.getRandomWord(4, 10))
</pre>
<p>which produces </p>
<pre class="brush: java;">
badly numbers good hot I
ywyypgqorighfawpftjq
demanded
</pre>
<p>All three of these methods can be passed a single length which returns a fixed length string, or a min/max length which produces a random string with a length somewhere between the min/max. For the single word method, if there are no words in the dictionary of suitable length, then a word is generated using random characters. </p>
<h1>Changing the test data values produced</h1>
<p>The data used to generate the values come from classes that can be replaced with other versions. For example, the name values can be changed by providing the <code>DataFactory</code> instance with an object that implements the <code>NameDataValues</code> interface. Here is a simple class that does that to return Scandinavian first names and delegates to the the default implementation to return all the other values.</p>
<pre class="brush: java;">
public class ScandinavianNames  implements NameDataValues {

	//first name values to use
	String[] firstNames = {&quot;Anders&quot;,&quot;Freydís&quot;,&quot;Gerlach&quot;,&quot;Sigdis&quot;};

	//delegate to the default implementation for the other values
	NameDataValues defaults = new DefaultNameDataValues();

	public String[] getFirstNames() {
		//return our custom list of names
		return firstNames;
	}

	//for the other values, just use the defaults
	public String[] getLastNames() {
		return defaults.getLastNames();
	}

	public String[] getPrefixes() {
		return defaults.getPrefixes();
	}

	public String[] getSuffixes() {
		return defaults.getSuffixes();
	}

}
</pre>
<p>Obviously, to use all your own names you would add and return values for last name and the suffix/prefix values. To use this new implementation, just create an instance of the data provider and pass it to the instance of the data factory. </p>
<pre class="brush: java;">
public static void main(String[] args) {
	DataFactory df = new DataFactory();
	df.setNameDataValues(new ScandinavianNames());
	for (int i = 0; i &lt; 10; i++) {
		System.out.println(df.getName());
	}
}
</pre>
<p>Our results are </p>
<pre class="brush: plain;">
Sigdis Craft
Gerlach Larsen
Sigdis Levine
Sigdis Smith
Freydís Sloan
Gerlach Mayer
</pre>
<p>You can always start working with the default implementation and use a more locale specific implementation if you need it later.</p>
<p>The different pieces that can be replaced are as follows : </p>
<ul>
<li><code>NameDataValues</code> &#8211; Generates names and suffix/prefixes</li>
<li><code>ContentDataValues.java</code> &#8211; Generates words, business types, email domain names and top level domain values</li>
<li><code>AddressDataValues</code> &#8211; Generates city names, street names and address suffixes</li>
</ul>
<p>Note that if you intend on replacing the component that generates words, you should have a good collection of words of various lengths from 2 up to say 8 or more characters. </p>
<p>Hopefully this will give you a head start in generating data in development and test environments for new projects. Now I have DataFactory in the Central Maven Repository I plan on using this in the Knappsack archetypes rather than hard coding the data which was in fact generated from an earlier DataFactory implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/generate-test-data-with-datafactory/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Shrinkwrap DSLs Makes Building Config Files Easy</title>
		<link>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/</link>
		<comments>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/#comments</comments>
		<pubDate>Mon, 07 Feb 2011 13:22:08 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Arquillian]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Shrinkwrap]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1720</guid>
		<description><![CDATA[If you&#8217;ve used Shrinkwrap you might have noticed that creating configuration files can be a bit of a burden requiring you to manually build XML configuration files yourself as strings. This article shows how the DSLs being added to Shrinkwrap will make configuring your deployments far easier. I&#8217;m not sure on the current status of [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve used <a href="http://community.jboss.org/wiki/ShrinkWrap">Shrinkwrap</a> you might have noticed that creating configuration files can be a bit of a burden requiring you to manually build XML configuration files yourself as strings. This article shows how the DSLs being added to Shrinkwrap will make configuring your deployments far easier.<br />
<span id="more-1720"></span><br />
I&#8217;m not sure on the current status of the DSL project, but you can find it on GitHub on the <a href="https://github.com/shrinkwrap/descriptors">shrinkwrap / descriptors</a> page. These are still in development, but as they are fairly stand-alone, they work well enough to use. To get started, download the maven project from the GitHub page, build and install it.</p>
<p>The descriptors project contains classes implementing DSLs for creating configuration files that can be exported to text. These files can then be added to the Shrinkwrap archive. Here&#8217;s a basic example that adds a <code>beans.xml</code> for CDI support.</p>
<pre class="brush: java;">
// first create the descriptor
BeansDescriptor bd = Descriptors.create(BeansDescriptor.class);

// add alternatives classes
bd.alternativeClasses(EmailEventHandler.class, LogEventHandler.class)
.decorator(BillingProcessorDecorator.class);// add decorator classes

System.out.println(bd.exportAsString());
</pre>
<p>Produces a result of </p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;beans xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans1_0.xsd&quot;&gt;
    &lt;decorators&gt;
        &lt;class&gt;org.demo.beans.BillingProcessorDecorator&lt;/class&gt;
    &lt;/decorators&gt;
    &lt;alternatives&gt;
        &lt;class&gt;org.demo.EventHandlers.EmailEventHandler&lt;/class&gt;
        &lt;class&gt;org.demo.EventHandlers.LogEventHandler&lt;/class&gt;
    &lt;/alternatives&gt;
&lt;/beans&gt;
</pre>
<p>First you must get an instance of the descriptor which is the basis for the dsl, and then you can define the properties for the descriptor using the methods defined on it, chaining the calls as needed.</p>
<p>Another example uses the <code>PersistenceDescriptor</code> and can be used to create <code>persistence.xml</code> files :</p>
<pre class="brush: java;">
PersistenceDescriptor pd = Descriptors.create(PersistenceDescriptor.class);

pd.persistenceUnit(&quot;myUnit&quot;)
		.classes(Person.class, User.class)
		.description(&quot;Default Persistence Unit&quot;)
		.formatSql()
		.schemaGenerationMode(SchemaGenerationModeType.CREATE_DROP)
		.jtaDataSource(&quot;java:/DefaultDS&quot;)
		.property(&quot;hibernate.cache.provider_class&quot;,&quot;org.hibernate.cache.HashtableCacheProvider&quot;)
		.version(&quot;2.0&quot;);

		System.out.println(pd.exportAsString());
</pre>
<p>Produces : </p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;persistence xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; version=&quot;2.0&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd&quot;&gt;
    &lt;persistence-unit name=&quot;myUnit&quot;&gt;
        &lt;description&gt;Default Persistence Unit&lt;/description&gt;
        &lt;jta-data-source&gt;java:/DefaultDS&lt;/jta-data-source&gt;
        &lt;class&gt;org.demo.model.Person&lt;/class&gt;
        &lt;class&gt;org.demo.model.User&lt;/class&gt;
        &lt;properties&gt;
            &lt;property name=&quot;hibernate.format_sql&quot; value=&quot;true&quot;/&gt;
            &lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;create-drop&quot;/&gt;
            &lt;property name=&quot;eclipselink.ddl-generation&quot; value=&quot;drop-and-create-tables&quot;/&gt;
            &lt;property name=&quot;hibernate.cache.provider_class&quot; value=&quot;org.hibernate.cache.HashtableCacheProvider&quot;/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;
</pre>
<p>The project also supports importing configuration files to the associated description type since the descriptors are modeled using JAXB XML bindings. At the moment the following descriptor types are supported : </p>
<ul>
<li><b>web.xml</b> &#8211; Web deployment descriptor file</li>
<li><b>persistence.xml</b> &#8211; JPA Persistence config file</li>
<li><b>faces-config.xml</b> &#8211; Configuration file for Java Server Faces</li>
<li><b>beans.xml</b> &#8211; Triggers the use of CDI and can contain configuration info</li>
</ul>
<p>While the goal is to use these to help generate Shrinkwrap archives, particularly for Arquillian testing, there&#8217;s nothing wrong with using them to automatically generate configuration files, especially for new projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/shrinkwrap-dsls-makes-building-config-files-easy/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Delphi still fighting the war lost years ago</title>
		<link>http://www.andygibson.net/blog/article/delphi-still-fighting-the-battle-lost-years-ago/</link>
		<comments>http://www.andygibson.net/blog/article/delphi-still-fighting-the-battle-lost-years-ago/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 04:04:28 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Delphi]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1736</guid>
		<description><![CDATA[Embarcadero announced the release of the Delphi XE Starter edition for building native windows applications. I spent many years as a Delphi developer before I made the switch to Java while the Delphi programming language and tools were top notch at the time. However, with the years of abuse at the hands of Borland and [...]]]></description>
			<content:encoded><![CDATA[<p>Embarcadero announced the release of the <a href="http://www.embarcadero.com/products/delphi/starter">Delphi XE Starter</a> edition for building native windows applications. I spent many years as a Delphi developer before I made the switch to Java while the Delphi programming language and tools were top notch at the time. However, with the years of abuse at the hands of Borland and then Codegear, it fell way behind. Java IDEs in general are far superior with a lot of attention paid to the actual code aspects of the IDEs while Delphi was very GUI centric and provided superior visual editors. Of course, Delphi is very rigid in how you build applications while Java provides a lot more flexibility to the point of having too much flexibility (the story of Java&#8217;s life).<br />
<span id="more-1736"></span><br />
I bought my last version of Delphi a few years ago, I think it was Delphi 10/2006, it cost several hundred dollars and it was a real stinker. I swore I would never buy another version with my hard earned cash. Even at the office we reverted back to Delphi 6 (from 2001 so it was 5 years old) because it was just horrible.<br />
I think at that point, with the release of .net and Visual Studio which was then starting to be given away free, the writing was on the wall. Stuck between the free competitor IDEs , Codegear and then Embracadero were still trying to push a high priced IDE that nobody really wanted in the first place since, albeit rather unjustly, Delphi adoption has never been high.</p>
<p>So now we have a new version, priced at just $199, where you can choose to use a limited version of a dead language (and probably with licensing restrictions). I always find it interesting to see which features they leave out of the basic version, let&#8217;s take a look at the <a href="http://www.embarcadero.com/products/delphi/delphi-feature-matrix.pdf">Feature Matrix</a> :</p>
<ul>
<li>No Code formatting</li>
<li>No Class Explorer</li>
<li>No autocompletion for DTD based documents</li>
<li>No To-Do Lists</li>
<li>No refactorings</li>
<li>No diagramming of any kind</li>
<li>No unit testing</li>
<li>NO DATABASE SUPPORT (except for Interbase)</li>
<li>No logging</li>
<li>No Reports</li>
<li>No network components</li>
</ul>
<p>Eh, I could go on but I won&#8217;t, to anyone familiar with something like Eclipse most of these items are the basic elements of any IDE that you wouldn&#8217;t want to do without. The point is, for $199 today, you can have an IDE from 15-20 years ago. For an extra $600 you can have the professional version which gets you all the basics, but not much more. To create multi-tier datasnap applications, you are looking at spending thousands on an enterprise or architect license. Compare this to the range and scope of the Java APIs that you can get and use for free, whether it be data access, network components, web frameworks or a variety of web servers. </p>
<p>When I moved from Delphi to Java, or even .net, it was like coming out from under a rock and seeing the surface of the Earth for the first time. I have no desire to pay $199 to go back under there. </p>
<h1>The Delphi Market</h1>
<p>Of course, there is a market for Delphi, there are plenty of places that use it internally for applications, and it really is one of the best ways currently to produce native applications for Windows which after all is still a rather huge market. These people see enough value in upgrading that there is still a market in there, although given the turbulent ownerships of Delphi, probably not a very good one. Meanwhile, Borland was bought by Micro Focus in May 2009.</p>
<p>I tend to object to the calls for something to be made free and open source simply because someone likes it. It simply ignores the masses of time and money that went into making it. However, in this case, I think if Embracadero would like to see any kind of growth, it should look at slashing the prices. Granted, they may be quite happy with the small market of dedicated customers and if they are able to strike a fiscal balance with that, all the best to them. </p>
<p>While cutting prices might make it more attractive, it still might not generate demand (which is probably why they won&#8217;t do this). By some standards, the web is now the platform of choice and native apps are in less demand. For corporate customers, there is probably far more demand for web applications for which there are better tools than Delphi. Since code re-usability was never a strong point of Delphi, the ability to leverage existing code is probably minimal, especially given the stateless nature of the web and the stateful nature of a client/server Delphi application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/delphi-still-fighting-the-battle-lost-years-ago/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple RESTful web services with Glassfish</title>
		<link>http://www.andygibson.net/blog/article/simple-restful-web-services-with-glassfish/</link>
		<comments>http://www.andygibson.net/blog/article/simple-restful-web-services-with-glassfish/#comments</comments>
		<pubDate>Thu, 03 Feb 2011 13:44:52 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1723</guid>
		<description><![CDATA[Here&#8217;s a quick guide to creating a RESTful web service with Glassfish using JAX-RS. First create a new maven project called restwebdemo using the jee6-sandbox-archetype so we have a model and some data to work with. To get this working with Glassfish, open the persistence.xml file and change the jta-data-source name to jdbc/__default. Also, make [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a quick guide to creating a RESTful web service with Glassfish using JAX-RS.<br />
<span id="more-1723"></span><br />
First create a new maven project called <code>restwebdemo</code> using the jee6-sandbox-archetype so we have a model and some data to work with. To get this working with Glassfish, open the <code>persistence.xml</code> file and change the <code>jta-data-source</code> name to <code>jdbc/__default</code>. Also, make sure that the javaDB is up and running by going to <code>$glassfish_dir/bin</code> and typing <code>asadmin start-database</code>. Verify that the application is working correctly by going to <a href="http://localhost:8080/restwebdemo/">http://localhost:8080/restwebdemo/</a> and you should get a list of courses.</p>
<p>Before we start getting to the interesting stuff, we have one more boring piece of configuration to perform specific to web services. We need to add the jersey servlet container to our <code>web.xml</code> file:</p>
<pre class="brush: xml;">
&lt;servlet&gt;
	&lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
	&lt;servlet-class&gt;com.sun.jersey.spi.container.servlet.ServletContainer&lt;/servlet-class&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
	&lt;url-pattern&gt;/rest/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p>This also tells Jersey to handle urls starting with <code>/rest</code> and pass it along to our web service methods.</p>
<p>Now we can dive right in an create a new server bean that will respond to requests for web services. For now we&#8217;ll just return a simple message from a POJO.</p>
<pre class="brush: java;">
@Path(&quot;sample&quot;)
public class SimpleService {

	@Path(&quot;greet&quot;)
	@GET
	public String doGreet() {
		return &quot;Hello Stranger, the time is &quot;+ new Date();
	}
}
</pre>
<p>The path annotation on the class indicates that this is a root resource class and the path value given specifies the base URI for all the web service methods contained in the class.<br />
On the <code>doGreet</code> method we have <code>@Path</code> which is used to specify the path template this method should match. The <code>@GET</code> annotation is used to differentiate between a sub-resource method that handles the actual web service request and a sub-resource locator method that returns an object that will instead be used to handle the request. In this case, the method has the <code>@GET</code> annotation which means this method handles the request and returns the result.<br />
If you navigate to <a href="http://localhost:8080/restwebdemo/rest/sample/greet/">http://localhost:8080/restwebdemo/rest/sample/greet/</a> you should see a welcome message with the current date and time.</p>
<p>Now we&#8217;ll look at adding parameterized web services that extracts parameters from the request URL and uses them to form the output. Add the following method to the web service class :</p>
<pre class="brush: java;">
@Path(&quot;sayHello/{name}&quot;)
@GET
public String doSayHello(@PathParam(&quot;name&quot;) String name) {
	return &quot;Hello there &quot;+name;
}
</pre>
<p>Again we have the path annotation to indicate what URLs this method will match, and this time we have have <code>{name}</code> added to the URL. This lets us extract a part of the url and give it a name. This name is used in the <code>@PathParam</code> annotation in the method signature to assign the URL fragment to the name parameter . To test our new method, redeploy the application and go to the URL  <a href="http://localhost:8080/restwebdemo/rest/sample/sayHello/Andy">http://localhost:8080/restwebdemo/rest/sample/sayHello/Andy</a> to get the response  <code>Hello there Andy</code></p>
<p>We can also use request parameters to provide values to the method by using the <code>@QueryParam</code> annotation. We&#8217;ll create another method that is similar but uses a query parameter instead.</p>
<pre class="brush: java;">
@Path(&quot;sayHello&quot;)
@GET
public String doSayHelloWithRequestParam(@QueryParam(&quot;name&quot;) String name) {
	return &quot;Hi there &quot;+name;
}
</pre>
<p>This time, the URL to use is <a href="http://localhost:8080/restwebdemo/rest/sample/sayHello?name=Andy">http://localhost:8080/restwebdemo/rest/sample/sayHello?name=Andy</a> to get the same message.</p>
<p>To make things more interesting, lets add a new page that lets us enter a name in a form and submit it to the web service.  Add a new page called <code>form.html</code> with the following content : </p>
<pre class="brush: xml;">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Insert title here&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action=&quot;rest/sample/sayHello&quot; method=&quot;GET&quot;&gt;
Name &lt;input id=&quot;name&quot; name=&quot;name&quot;/&gt; &lt;input type=&quot;submit&quot; /&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Go to this page at <a href="http://localhost:8080/restwebdemo/form.html">http://localhost:8080/restwebdemo/form.html</a>, enter your name and click submit and you should be greeted by name in the next page.</p>
<p>Notice that we had to set the form method to <code>GET</code> because our web service is only set up to respond to GET requests. If we change the form method to POST we can get the following error message : </p>
<pre class="brush: plain;">
HTTP Status 405 - Method Not Allowed
type Status report
message Method Not Allowed
description The specified HTTP method is not allowed for the requested resource (Method Not Allowed).</pre>
<p>Remember, with REST, those actual verbs have meaning and adds meaning to the request so it is strict on how it matches the method to be called.</p>
<p>To solve this problem, we can add a new method to handle form POSTs like so :</p>
<pre class="brush: java;">
@Path(&quot;sayHello&quot;)
@POST
public String doSayHelloWithFormParam(@FormParam(&quot;name&quot;) String name) {
	return &quot;Hi there &quot; + name;
}
</pre>
<p>Here we changed the <code>@GET</code> to a <code>@POST</code> to allow the different verb and changed the annotation on the <code>name</code> method parameter to <code>@FormParam</code>. The path remains the same because we can have service methods that match the same path, but for different request verbs. We can even have the same verb and path as long as the content type returned is different. The content type is used to specify the type of output the is returned from the method. It is set by adding a <code>@javax.ws.rs.Produces</code> (not to be confused with the CDI <code>Produces</code> annotation).  The annotation takes a string parameter that indicates the type of media returned from the method. Common media types are defined as constants in the <code>MediaType</code> class so you can use :</p>
<pre class="brush: java;">
@Path(&quot;sayHello&quot;)
@POST
@Produces(MediaType.APPLICATION_XML)
public String doSayHelloWithFormParam(@FormParam(&quot;name&quot;) String name) {
	return &quot;&lt;message&gt;Hi there &quot; + name+&quot;&lt;/message&gt;&quot;;
}
</pre>
<p>If you run your form again, and post it, you will get an xml response as follows : </p>
<pre class="brush: xml;">
&lt;message&gt;Hi there Andy&lt;/message&gt;
</pre>
<p>Depending on your browser, if you return just the text, you will get an error because the plain text isn&#8217;t valid XML and the browser expects XML because that is the response type set on the response from the web service.</p>
<p>To finish up, we are going to do something a little more interesting, we will create a web service to return the name of a course from the database using the sandbox data built into the archetype. For various reasons, we will take the most direct route to getting data access which is to make the web service bean a stateless bean and inject a persistence context using the <code>@PersistenceContext</code> annotation.</p>
<ol>
<li>Add the <code>@Stateless</code> annotation to the <code>SimpleService</code> class and an entity manager field annotated with <code>@PersistenceContext</code> along with the getters and setters.</li>
<li>Add a new method to return the course name for the given course id parameter. We will return it as text for the time being :
<pre class="brush: java;">
@Path(&quot;courseName/{id}&quot;)
@GET
public String getCourseNameFromId(@PathParam(&quot;id&quot;) Long id) {
	Course c = entityManager.find(Course.class, id);
	if (c == null) {
		return &quot;Not Found, try the index &lt;a href='/restwebdemo/'&gt;page&lt;/a&gt; and come back&quot;;
	} else {
		return c.getTitle();
	}
}
</pre>
<p>Note that the automatic type conversion takes place and the value is converted to a <code>Long</code> automatically. If the course is not found, we suggest the user goes to the main page of the demo. We aren&#8217;t just being overly helpful, the test data is generated when you request one of the application pages for the first time. In the current persistence context, when you redeploy, the database is dropped and rebuilt so it will be empty. You need to go to the front page to automatically create the data and then go back to  your page to view the course. An example URL is <a href="http://localhost:8080/restwebdemo/rest/sample/courseName/124">http://localhost:8080/restwebdemo/rest/sample/courseName/124</a>.
</li>
<p>Of course you could grab the course object and build your own XML or JSON response to send back to the client, or use a third party library like Jackson to build the JSON response. However, as we&#8217;ll see next time, Java EE 6 has all these goodies built in for us, and with a few annotations, we&#8217;ll be slinging objects back and forth in no time at all.</p>
<p>You can download the source code for the project from <a href='http://www.andygibson.net/blog/wp-content/uploads/2011/02/restwebdemo_pt1.zip'>here</a>. Simply unzip, build with maven (<code>mvn clean package</code>) and deploy to Glassfish.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/simple-restful-web-services-with-glassfish/feed/</wfw:commentRss>
		<slash:comments>3</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>
	</channel>
</rss>

