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

<channel>
	<title>Andy Gibson</title>
	<atom:link href="http://www.andygibson.net/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.andygibson.net/blog</link>
	<description>Open Source Projects &#38; Technical Writings</description>
	<lastBuildDate>Thu, 02 Feb 2012 14:33:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language></language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 2</title>
		<link>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/</link>
		<comments>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 12:28:33 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1841</guid>
		<description><![CDATA[In this second article on implementing Spring MVC in Java EE 6 we&#8217;ll take the metadata we extracted in part one and use it to invoke request mapped controller methods in response to web requests and then direct the user to a web page based on the result of the method. In this article we&#8217;ll [...]]]></description>
			<content:encoded><![CDATA[<p>In this second article on implementing Spring MVC in Java EE 6 we&#8217;ll take the metadata we extracted in <a href="http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/">part one</a> and use it to invoke request mapped controller methods in response to web requests and then direct the user to a web page based on the result of the method. <span id="more-1841"></span></p>
<p>In this article we&#8217;ll be implementing the following functions, the code for which is available for <a href='http://www.andygibson.net/blog/wp-content/uploads/2012/01/mvcdi_part2.zip'>download</a> :</p>
<ul>
<li>Write a servlet that will dispatch the requests to our MVC handler class.</li>
<li>In the MVC Handler, we&#8217;ll take a web request and invoke the appropriate controller method</li>
<li>Take the result from the request mapped method and resolve it to a view which the user is forwarded to</li>
</ul>
<h1>Implementing the Servlet</h1>
<p>Our servlet code takes incoming requests and delegates them to the injected <code>MvcHandler</code> instance.</p>
<pre class="brush: java;">@WebServlet(urlPatterns = &quot;/demo/*&quot;)
public class DelegatingServlet extends HttpServlet {

    @Inject
    private MvcHandler mvcHandler;

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

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

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

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

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

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

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

    @Inject
    private ControllerInfo controllerInfo;

    @Inject
    private ControllerMethodMatcher matcher;

    @Inject
    private BeanManager beanManager;    

	public void handleRequest(RequestContext context) {

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

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

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

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

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

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

    protected boolean matches(ControllerMethod methodToTest, RequestContext context) {
        String path = context.getPath();
        boolean result = methodToTest.matchesRequestMethod(context.getRequestMethod())
            &amp;&amp; (methodToTest.getPrefix() == null || path.startsWith(methodToTest.getPrefix()))
            &amp;&amp; (methodToTest.getSuffix() == null || path.endsWith(methodToTest.getSuffix()));
        return result;
    }
}
</pre>
<p>We can override this class, and re-implement the <code>matches</code> method later on and since we pass in the <code>RequestContext</code> we will have all sorts of information available to us to determine the best match. </p>
<h2>Executing the Controller Method</h2>
<p>We can just use reflection to execute the controller method instance for now. We assume that there are no params for now, that will come later.</p>
<pre class="brush: java;">
private void executeControllerMethod(RequestContext context) {
	Method javaMethod = context.getMethod().getMethod();
	Object outcome = null;
	try {
		outcome = javaMethod.invoke(context.getController());
	} catch (Exception e) {
		e.printStackTrace();
	}
	context.setOutcome(outcome);
}
</pre>
<h2>Seeing it in action</h2>
<p>Finally we can put it all together so we can see it in action in a web application. For now our MVC code is in our web project to make integrating it easier. We can later extract the MVC code to a stand-alone module to use as a library in other projects.  We&#8217;ve already set up a controller and our servlet, now we just need to create a couple of pages based on the string returned from the mapped methods. If we run the application now and go to a url such as <a href="http://localhost:8080/mvcdi/demo/person/list">http://localhost:8080/mvcdi/demo/person/list</a> we will get an error message because <code>listPeople.jsp</code> doesn&#8217;t exist. We&#8217;ll create the following simple jsp pages so we can display something in the browser. Each page just consists of the boilerplate structure and some text that indicates which page we are on.</p>
<pre class="brush: xml;">
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;View Person&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    View Person
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We do this for the following pages in the root of the web directory.</p>
<ul>
<li><code>viewPerson.jsp</code></li>
<li><code>listPeople.jsp</code></li>
<li><code>updatedPerson.jsp</code></li>
<li><code>editPerson.jsp</code> (see below for additional changes)</li>
</ul>
<p>The one different page is the <code>editPerson.jsp</code> page where we want to put a form containing only a button so we can issue a <code>POST</code> request which maps to the method on the controller that handles the <code>POST</code> request from the <code>editPerson.jsp</code> page and navigates to the <code>updatedPerson.jsp</code> page in response.</p>
<pre class="brush: java;">
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Editing Person&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        Editing Person
        &lt;form method=&quot;post&quot;&gt;
            Some Form Here&lt;br/&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Update&quot; /&gt;
        &lt;/form&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If we go to <a href="http://localhost:8080/mvcdi/demo/person/edit">http://localhost:8080/mvcdi/demo/person/edit</a> and click the submit button, we get sent to the page that tells us we just updated someone because that is the page returned from the controller method for the <code>edit</code> path with a <code>POST</code> request method.</p>
<p>You can download (<a href='http://www.andygibson.net/blog/wp-content/uploads/2012/01/mvcdi_part2.zip'>mvcdi_part2.zip</a>) the code for this as a maven project that can run on any Java EE 6 container and has been tested on  both JBoss AS 7 and Glassfish 3.1.1.</p>
<p>This wraps up the second installment of this series on implementing Spring MVC in Java EE 6 and CDI and covers the bulk of the request mapping so we can direct our web requests to controller methods and ultimately to specific pages. Next time we&#8217;ll look at providing model data to the pages.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/implementing-spring-mvc-in-cdi-and-java-ee-6-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Implementing Spring MVC with CDI and Java EE 6 part 1</title>
		<link>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/</link>
		<comments>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 12:30:36 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1829</guid>
		<description><![CDATA[One of the opinions I&#8217;ve had over the last couple of years is that Spring makes things look really easy, and CDI is a great dependency injection framework. Throw in this article suggesting you can build your own Java EE 7 and it sounds like a challenge, so for fun, I thought I might have [...]]]></description>
			<content:encoded><![CDATA[<p>One of the opinions I&#8217;ve had over the last couple of years is that Spring makes things look really easy, and CDI is a great dependency injection framework. Throw in this article suggesting you can <a href="http://java.dzone.com/articles/cdi-extensions-you-can-build">build your own Java EE 7</a> and it sounds like a challenge, so for fun, I thought I might have a go at implementing a subset of Spring MVC on top of CDI with Java EE 6.<span id="more-1829"></span></p>
<p>Interestingly, there&#8217;s nothing like Spring MVC for Java EE which is a shame because it is a really good framework. So in this series of articles, I&#8217;ll be covering different aspects of implementing Spring MVC on CDI with the caveat that this won&#8217;t be an exact compatible replica. I&#8217;ll be implementing just enough of each feature to demonstrate that it can be done, but I&#8217;ll leave enough room so that with more work, it can be a more accurate implementation. It goes without saying that these articles assume you are familiar with Spring MVC 3 using annotations and at least a little bit familiar with CDI. I&#8217;ll also mention that the code listed in the articles only contains the code relevant to the implementation for demonstration purposes. I&#8217;ve removed a lot of the null checks and other defensive programming code to make things more readable but they are still present in the final code.</p>
<p>In this first part, we will start by laying all the dull ground work as we capture the metadata from the MVC annotations in the following steps : </p>
<ul>
<li>Define our MVC annotations</li>
<li>Define a class to hold our request mapped methods</li>
<li>Write some code to extract the request mapped methods from a given class and store the metadata</li>
</ul>
<h1>The MVC annotations</h1>
<p>To get started we implement the controller and request mapping annotations which are based on the Spring MVC versions. <code>@Controller</code> marks our classes as MVC controllers that implement MVC methods. Each method that can be mapped to a URL is mapped with the <code>@RequestMapping</code> annotation.</p>
<pre class="brush: java;">@Target({ ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}
</pre>
<p>The request mapping annotation has two attributes (for now), the default <code>value</code> which contains an array of paths that are mapped to this controller or method. For now, we will implement simple path matching, the url must start with the controller path and end with the path defined on the method. We can change to a more complex wildcard/Ant path matching implementation if we want to later. The other attribute on the request mapping is an array of <code>RequestMethod</code> types that indicates the type of requests we want to map to this controller and method. For now, we&#8217;ll just deal with <code>POST</code>, <code>GET</code> and <code>DELETE</code> request types :</p>
<pre class="brush: java;">
public enum RequestMethod {
    POST,GET,DELETE
}
</pre>
<p>Now we can define our request mapping annotation :</p>
<pre class="brush: java;">
@Target({ ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {

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

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

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

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

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

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

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

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

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

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

    @Inject
    private BeanManager beanManager;

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

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

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

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

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

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

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

private void addMethod(String prefix, Method javaMethod) {

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

        String[] paths = mapping.value();

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

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

    }
}
</pre>
<p>The <code>addMethod</code> function will check for a request mapping annotation on the method, extract the metadata and store it in the list.</p>
<p>This about wraps up the first installment which covers the extraction of request mapped methods and storing them for use later on. Next time we&#8217;ll start coding our servlet and core MVC handler that will let us make web requests and invoke the mapped methods on our controller before displaying the appropriate web page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/implementing-spring-mvc-with-cdi-and-java-ee-6/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>More Time Saved By Unit Tests</title>
		<link>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/#comments</comments>
		<pubDate>Sun, 11 Dec 2011 07:10:59 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[DataValve]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1815</guid>
		<description><![CDATA[So I&#8217;ve been meaning to make a fix in one of my projects for a while, and I haven&#8217;t touched the code in over a year, so of course I have to go back and really get back up to speed with the code. The change was for the Datavalve project and it was to [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been meaning to make a fix in one of my projects for a while, and I haven&#8217;t touched the code in over a year, so of course I have to go back and really get back up to speed with the code. The change was for the Datavalve project and it was to include support for passing in collections and using <code>in</code> SQL Statements, so now you can use something like :</p>
<pre class="brush: java;">
provider.addRestriction(&quot;item.statusCode in (:param)&quot;, stateCodeList);
</pre>
<p>This will cause the list of codes to be expanded into an <code>in</code> SQL statement including checking to exclude null items, and as usual, the restriction is not included if the code list is null or contains only null items.</p>
<p>So I have two problems, the first is getting back up to speed on my code, figuring out where the make the change, and making it. The second is making sure my code changes don&#8217;t break anything thats currently working. </p>
<p>For the first problem, I decide to create the unit tests first so I can verify that the change does as expected. Obviously, the tests fail initially, but by looking at the code executed by the tests, I can start to pick out places where I need to start looking to add the new code. After all, tests measure the correctness of the state after the code has been executed. What better place to start looking than seeing what code the test executes. After finding the method that I need to change, I make my code changes and run my tests. All my original tests pass with flying colors, but my new test fails. I take a peek and sure enough I left off the last line of code to add the built object to a list. I put it in, and I have all my tests up and running. </p>
<p>All in all, I&#8217;ve made a large change to some sizable (12K+ LOC) code that I haven&#8217;t seen in over a year, verified that the change works and that it hasn&#8217;t impacted any other code. Not bad for an hour.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/more-time-saved-by-unit-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I&#8217;m Back</title>
		<link>http://www.andygibson.net/blog/personal/im-back/</link>
		<comments>http://www.andygibson.net/blog/personal/im-back/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 03:33:07 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1808</guid>
		<description><![CDATA[So I&#8217;ve been on a bit of break from blogging, I&#8217;ve had lots of things going on, I&#8217;ve moved house twice, and changed jobs a couple of times. I&#8217;ve not even really been checking my email that much (as evidenced by the fact that I didn&#8217;t see my hosting invoices and the subsequent temporary suspension [...]]]></description>
			<content:encoded><![CDATA[<p>So I&#8217;ve been on a bit of break from blogging, I&#8217;ve had lots of things going on, I&#8217;ve moved house twice, and changed jobs a couple of times. I&#8217;ve not even really been checking my email that much (as evidenced by the fact that I didn&#8217;t see my hosting invoices and the subsequent temporary suspension of my blogging web site). I&#8217;ve been spending time with the family over summer and taking a bit of a break from the extra-curricular IT work. I&#8217;ve also been doing some thinking on which direction I want to go in my career. Because of all this,  If you&#8217;ve emailed, or sent a LinkedIn request that I&#8217;ve done nothing with, that&#8217;s why.  However, things have been hotting up in my absence so there&#8217;s certainly a lot of topics to delve into.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/personal/im-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSTL 1.2 Missing From Maven Repositories</title>
		<link>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 12:45:04 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1802</guid>
		<description><![CDATA[It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a number of issues around the web. Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one javax.servlet.jstl [...]]]></description>
			<content:encoded><![CDATA[<p>It seems in the last few weeks or so the Maven JSTL dependency has vanished from at least the central repository. This has caused a <a href="http://www.google.com/search?q=jstl%201.2%20missing">number of issues</a> around the web.</p>
<p>Oracle has released the separate API and implementation dependencies which is really how they should be broken down. Now, instead of having one <code>javax.servlet.jstl</code> dependency you will use the following :</p>
<pre class="brush: xml;">
&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
&lt;/dependency&gt;

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

&lt;/dependency&gt;

&lt;dependency&gt;
    &lt;groupId&gt;javax.servlet.jsp.jstl&lt;/groupId&gt;
    &lt;artifactId&gt;jstl-api&lt;/artifactId&gt;
    &lt;version&gt;1.2&lt;/version&gt;
    &lt;scope&gt;provided&lt;/scope&gt;
&lt;/dependency&gt;
</pre>
<p>I&#8217;m surprised that they would eliminate the pom like that, but it may have been due to licensing issues for the reference implementation which I believe has been an issue for some of the standard Java EE APIs and the reason that there is no real definitive deployment of the APIs and we have to mix and match API dependencies from different sources unless you are using the <a href="http://www.andygibson.net/blog/quickbyte/jboss-java-ee-6-spec-dependency-in-maven/">JBoss Java EE 6 dependency</a> to solve the problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/jstl-missing-from-maven-repositories/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Update</title>
		<link>http://www.andygibson.net/blog/quickbyte/1799/</link>
		<comments>http://www.andygibson.net/blog/quickbyte/1799/#comments</comments>
		<pubDate>Wed, 22 Jun 2011 01:46:53 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[QuickBytes]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Personal]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1799</guid>
		<description><![CDATA[I haven&#8217;t been writing for a while since I&#8217;ve been busy working on several things right now. First off, after a few months of job hunting, I&#8217;ve changed jobs, I&#8217;m now doing some Java contract work down in Pittsburgh. After 11 years at my old job, it was time to move on. The great thing [...]]]></description>
			<content:encoded><![CDATA[<p>I haven&#8217;t been writing for a while since I&#8217;ve been busy working on several things right now.</p>
<p>First off, after a few months of job hunting, I&#8217;ve changed jobs, I&#8217;m now doing some Java contract work down in Pittsburgh. After 11 years at my old job, it was time to move on. The great thing about contract work is the opportunity to work on a lot of different projects in a lot of different places. After being stuck in Cleveland for 11 years, we are ready for some changes.</p>
<p>I also want to try and get into doing some more Java EE 6 and CDI training. A lot of people are unsure of how it is all meant to work together and are missing out on the real beauty and simplicity of working with these frameworks.</p>
<p>Rick, Rob and I have been doing some more work with CDISource and anticipate a release of our source in the next few weeks. Once thats out, I want to start playing with some of the Seam 3 stuff especially with regards to CDI. We announced CDISource and then all of a sudden we all got busy with different things, and we have some code we want to release for which we have a number of articles to write.</p>
<p>Between moving, unpacking, starting a new gig, which always fries the brain for a few weeks, and having my Mum over from Manchester,England, I haven&#8217;t really been having time to write or work on projects. </p>
<p>I have a new release of the Knappsack almost ready to go which includes Spring based archetypes and also a Java EE 6 EAR archetype as well as a couple of new posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/quickbyte/1799/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Announcing CDISource</title>
		<link>http://www.andygibson.net/blog/article/announcing-cdisource/</link>
		<comments>http://www.andygibson.net/blog/article/announcing-cdisource/#comments</comments>
		<pubDate>Mon, 28 Mar 2011 13:38:01 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[CDISource]]></category>
		<category><![CDATA[EJB]]></category>
		<category><![CDATA[Frameworks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[JSF]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[Personal]]></category>
		<category><![CDATA[Weld]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1787</guid>
		<description><![CDATA[In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is [...]]]></description>
			<content:encoded><![CDATA[<p>In the last few weeks I have been rather busy working on a new project with Rick Hightower, who is fairly well known for his training and writings on Spring and JSF, and Rob WIlliams who is a blogger known as much for meddling in new technologies (and getting mad at them) as he is for intertwining various historical and literary references in his posts. The result of this is the <a href="https://sites.google.com/site/cdipojo/get-started">CDISource</a> project which aims to advocate and facilitate the use of the JSR 299 &#8211; Java Contexts and Dependency Injection framework across the Java landscape.</p>
<p>If you&#8217;ve seen my posts or my site before, you&#8217;ll no doubt be aware that I have written at great length about Java EE 6, JSF, CDI , EJB and so on. What I haven&#8217;t written about is the many frustrations I&#8217;ve come up against in dealing with these frameworks on their own and especially when combined, or how their usefulness is often constrained to the application server container. </p>
<p>Java EE in some ways is an archipelago of frameworks that lacks the cohesiveness and all in one wide screen vision that software developers need. Java EE is about the enterprise, in reality its about the web, or even more specifically about Java EE containers. There&#8217;s a whole slew of uses for a good type safe and flexible dependency injection and AOP framework and such as CDI outside of Java EE containers but there is very little information and code to make it actually work.  </p>
<p>Our goal is to make CDI useful and usable on its own without Java EE 6, and to give developers the tools and information to do so. To let them write vendor neutral and portable code, and apply agile and best practices. Developers know how to write good software and don&#8217;t want to sacrifice that for the sake of using a framework to make things easier. To that end we aim to provide code and information that will help facilitate those practices. </p>
<p>There will be some learning for ourselves along the way and we will have to change some of our previously held concepts. I know over the last few weeks having been  getting CDI working and useful outside of the web container it has really altered my perspective on how I think about the dependencies and structure in CDI applications. My perspective has changed even more than when I wrote <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>. </p>
<p>As much as I hate to say it, we did come up with a mission statement, although we found it fairly easy and enjoyable to clearly defined the goals and attitudes of the project. </p>
<p>Our mission is to :</p>
<ul>
<li>Promote and facilitate the use of the Java Context and Dependency Injection (CDI) framework in relation to as many aspects of application development as possible.</li>
<li>Enable developers to take advantage of CDI independently of Java EE.</li>
<li>Provide lightweight, lean and agile access to the underlying CDI container as a core principle in our efforts.</li>
<li>Make testing easy without requiring a complex set of tools or complex deployment scenarios.</li>
<li>Enhance both Java EE development as well as the use of CDI in non Java EE application where possible.</li>
<li>Promote and enable the use of CDI in a vendor neutral environment and maximize the portability of application code across CDI implementations.</li>
<li>Not reject the ideas of Java EE but expand the usability of CDI outside the borders of Java EE application servers with frameworks that are not a part of the specification.</li>
<li>Not reject other CDI efforts but to provide another venue to promote those efforts. This is an addition. This is another voice in support of CDI.</li>
</ul>
<p>We are pretty excited that so far we have been able to live up to the intent of our mission statement with everything we&#8217;ve done so far. Over the next few days and weeks you will see articles and tutorials come out of Rick, Rob and I as we write about the CDISource project and we start to showcase some of the code we have written and start giving you an idea of where we are heading.  </p>
<p>Right now we have vendor neutral support for starting up CDI outside of the web container and also for testing CDI beans with minimal configuration and intrusion on your test cases. We also have a few other pieces that are nearly ready, as well as dozens of ideas to get started on.</p>
<p>You can start by looking at Ricks brand new <a href="http://java.dzone.com/articles/cdi-di-p1">introduction of CDI</a> over on JavaLobby.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.andygibson.net/blog/article/announcing-cdisource/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Simple RESTful services in Glassfish Pt 2</title>
		<link>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/</link>
		<comments>http://www.andygibson.net/blog/tutorial/simple-restful-services-in-glassfish-pt-2/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 12:39:13 +0000</pubDate>
		<dc:creator>Andy Gibson</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[Glassfish]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JEE]]></category>
		<category><![CDATA[Journeyman]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.andygibson.net/blog/?p=1765</guid>
		<description><![CDATA[In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page. In part 1, we looked at creating simple web services and now [...]]]></description>
			<content:encoded><![CDATA[<p>In part 2 of this article, we are going to create a data driven web service that will return JSON and XML to the client, and then use jQuery to add a new item to the database and display it in our page.<br />
<span id="more-1765"></span><br />
In part 1, we looked at creating simple web services and now we&#8217;re going to look at making something more practical and interesting. We&#8217;ll start from where we left off with the source code as it was at the end of the part 1 which you can download from here (<a href="http://www.andygibson.net/blog/wp-content/uploads/2011/02/restwebdemo_pt1.zip">restwebdemo_pt1</a>) if you want to follow along. If not, the final source can be downloaded from here (<a href='http://www.andygibson.net/blog/wp-content/uploads/2011/03/restwebdemo_pt2.zip'>restwebdemo_pt2</a>).</p>
<ol>
<li>First off, we&#8217;re going to change the entity manager that is available for injection to be request scoped. To do this, open up <code>DataRepositoryProducer.java</code> and change the <code>@ConversationScoped</code> annotation on the <code>getEntityManager()</code> method to be <code>@RequestScoped</code>.  The reason for this is documented here in <a href="http://www.andygibson.net/blog/article/a-little-less-conversation/">A Little Less Conversation</a>.</li>
<li>Next we are going to create a simple dao for Course objects, and the only reason to do this is to demonstrate the integration of CDI and the ability to layer your code. Create a new class called <code>CourseDao</code> with the following code.
<pre class="brush: java;">
package org.fluttercode.restwebdemo.bean;

@Stateless
@LocalBean
public class CourseDao {

	@Inject @DataRepository
	private EntityManager entityManager;

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

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

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

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

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

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

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

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

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

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

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

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

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

