<?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>blog.smart-java.nl</title>
	<atom:link href="http://blog.smart-java.nl/blog/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.smart-java.nl/blog</link>
	<description>Ordina J-Technologies - Java Blog</description>
	<lastBuildDate>Thu, 18 Mar 2010 14:08:40 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JSF 2.0 ClientBehavior: Bean Validation in JavaScript</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 21:02:29 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[ClientBehavior]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[JSF 2.0]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=1008</guid>
		<description><![CDATA[In the following article I&#8217;m going to show you my first &#8220;real world&#8221; ClientBehavior and my first impressions from a user&#8217;s perspective.
First, some theory. JSF has support for something called &#8220;attached objects&#8221;. This has been since the very beginning, with Converters and Validators.
Since JSF 2.0, Behaviors have been added to this list. A Behavior, when [...]]]></description>
			<content:encoded><![CDATA[<p>In the following article I&#8217;m going to show you my first &#8220;real world&#8221; <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/javax/faces/component/behavior/ClientBehavior.html">ClientBehavior</a> and my first impressions from a user&#8217;s perspective.</p>
<p>First, some theory. JSF has support for something called &#8220;attached objects&#8221;. This has been since the very beginning, with <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/convert/Converter.html">Converters</a> and <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/validator/Validator.html">Validators</a>.<br />
Since <a href="http://www.javaserverfaces.org/">JSF 2.0</a>, Behaviors have been added to this list. A Behavior, when attached to a component, adds client side scripts to an object. For example, one can imagine a Behavior to do an Ajax request, load some data and show it on the page. This will be a common use case for behaviors. The Expert Group understood this and came up with a specialized <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/behavior/AjaxBehavior.html">AjaxBehavior</a>, which is quite similar to the <a href="http://www.jboss.org/richfaces">Ajax4jsf</a> <a href="http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html_single/#a4j_support">&lt;:a4jsupport /&gt; tag</a>. it adds Ajax functionality to the existing component, without modifying it.</p>
<p>This is ClientBehavior in a nutshell. There are more subtile things to know, see this <a href="http://java.dzone.com/articles/jsf-2-client-behaviors">article by Andy Schwartz</a> for a more thorough explanation of the subject.</p>
<p><strong><em>From now on, I assume at least basic ClientBehavior knowledge and of course JSF knowledge.</em></strong></p>
<p><b>The ValidateBean Behavior</b><br />
With Java EE 6 we got <a href="http://jcp.org/en/jsr/detail?id=303">Bean Validation</a>. And I must admit, I like it a lot. It has a nice declarative language and one ubiquitous model for defining validations for your entire system, from database (generating Bean Validation-aware DDL with JPA 2.0) to UI (the JSF 2.0 BeanValidator, which I implemented for <a href="http://myfaces.apache.org/">Apache MyFaces</a>. That&#8217;s where my enthusiasm started).</p>
<p>But, one validation is missing in the spec (with good reasons of course), namely client side JavaScript validations, to improve usability and decrease server load.</p>
<p>Especially since JavaScript validations are often skipped because of maintenance reasons (validations implemented twice) and we now have a robust platform to implement generic validations, I tried to combine the two new technologies (ClientBehavior and Bean Validation) into one generic JavaScript validator.</p>
<p><b>The ClientBehavior implementation</b></p>
<pre><script type="syntaxhighlighter" class="brush: java">
@FacesBehavior("org.jkva.ValidateBeanBehavior")
@ResourceDependency(name = "validateBeanBehavior.js")
public class ValidateBeanBehavior extends ClientBehaviorBase {
    @Override
    public String getScript(ClientBehaviorContext ctx) {
        UIComponent component = ctx.getComponent();
        if (component instanceof UICommand) {
            UIForm form = findParentForm(component);
            if (form == null) {
                throw new FacesException("No parent form found");
            }
            List&lt;UIInput&gt; inputsInForm = findInputs(form);
            UIMessages messages = findMessages(ctx.getFacesContext().getViewRoot());
            return getSubmitHandler(form, inputsInForm, messages);
        } else {
            throw new FacesException("Unsupported component: " + component + " Only UICommand components are supported");
        }
    }
}
</script></pre>
<p>This class has some interesting things. First, of course the annotations. <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/behavior/FacesBehavior.html">@FacesBehavior</a> simply registers the class as a ClientBehavior under the given name, just like how Managed Beans or Converters work. The second annotation defines a <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/application/ResourceDependency.html">@ResourceDependency</a>. A ResourceDependency simply says: &#8220;Hey JSF, I generate markup which depends on this file. Make sure it&#8217;s available&#8221;. And JSF 2.0 responds with: &#8220;Okay, I will&#8221;.</p>
<p>Also, you probably noticed my ClientBehavior to only understand buttons. That&#8217;s right, you need to attach it to a button and it takes care of wiring all field validations in the form.</p>
<p>It also looks for a messages component. This is used later to make sure the JS error messages are positioned the same as the by JSF generated messages. <a href="http://java.sun.com/javaee/javaserverfaces/2.0/docs/api/index.html?javax/faces/component/UIMessages.html">UIMessages</a> applies to the entire view, so I don&#8217;t just look in the form. A high performance implementation may choose to start searching near the form, since most messages are positioned there, but that&#8217;s way out of scope of this article.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
private String getSubmitHandler(UIForm form, List&lt;UIInput&gt; inputsInForm, UIMessages messages) {
    FacesContext fc = FacesContext.getCurrentInstance();
    StringBuilder sb = new StringBuilder();
    sb.append("return org.jkva.validateBean.validateForm(");
    sb.append("'" + form.getClientId(fc) + "', ");
    if (messages != null) {
        sb.append("'" + messages.getClientId(fc) + "'");
    } else {
        sb.append("null");
    }
    sb.append(", [");
    String sep = "";
    for (UIInput input : inputsInForm) {
        PropertyDescriptor propertyDescriptor = getPropertyDescriptor(fc, input);
        Set&lt;ConstraintDescriptor&lt;?&gt;&gt; constraints = propertyDescriptor.getConstraintDescriptors();
        ValidationPropertyModel model = createValidationModel(input, propertyDescriptor, constraints);

        String fieldValidation = getFieldMetadata(input, model, fc);
        sb.append(sep);
        sb.append(fieldValidation);
        sep = ",";
    }
    sb.append("])");
    return sb.toString();
}
</script></pre>
<p>I know, I know, this is not the most elegant piece of code, but it nicely illustrates the point. I simply aggregates as much validation metadata as possible and writes it into one big JavaScript statement. Not that optimal, but high performance implementations may choose to dynamically generate a JS file with all metadata which only needs to be referenced from the inline JS code.</p>
<p>If you&#8217;d like to know how to obtain the ConstraintDescriptors (the four method calls in the above snippet), just look for the <a href="http://svn.apache.org/repos/asf/myfaces/core/trunk/api/src/main/java/javax/faces/validator/BeanValidator.java">BeanValidator in the Apache MyFaces SVN</a>. I reused the same code here.</p>
<p><b>The JavaScript</b><br />
The JavaScript shown below is part of the static scripts that belong to the ValidateBeanBehavior. It contains the JavaScript code to execute the rules, as passed from the server and, if needed, show the validation errors.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
var org;
if ("undefined" == typeof org) org = {};
if ("undefined" == typeof (org.jkva)) org.jkva = {};
if ("undefined" == typeof (org.jkva.validateBean)) {

    org.jkva.validateBean = {

        validateForm: function(formId, messagesId, validations) {
            var errors = [];
            var form = document.getElementById(formId);
            var elems = form.elements;
            for (var i = 0; i &lt; validations.length; i++) {
                var val = validations[i];
                var field = elems[val.fieldId];
                var error = org.jkva.validateBean.validateField(field, val);
                if (error) {
                    if (val.fieldId) {
                        var label = org.jkva.validateBean.findLabelForField(field);
                        if (!label) {
                            label = val.fieldId;
                        }
                    } else {
                        var label = val.fieldId;
                    }
                    errors.push(label + ":" + error);
                }
            }

            if (errors.length) {
                var messages = document.getElementById(messagesId);
                if (!messages) {
                    messages = document.createElement("span");
                    messages.id = messagesId;
                    form.insertBefore(messages, form.firstChild);
                }

                messages.innerHTML = org.jkva.validateBean.arrayToUnorderedList(errors);

                return false;
            } else {
                return true;
            }
        },

        ...
    }
}
</script></pre>
<p>It&#8217;s a lot of code, which, in essence, validates all input fields in the given form, according to the given validation rules and shows the user an error if needed. This error is positioned at the same spot as where the UIMessages would have been rendered in case of a server side error. This is a best guess though, because when the messages are not rendered (i.e. on the initial request), there is no marker in the page that I can use for positioning. A more sophisticated implementation could enrich all UIMessages in the page to always write some marker &#8220;div&#8221; with an ID to the client.</p>
<p>I&#8217;m going to skip the rest of the JavaScript. It&#8217;s just a bunch of validations and utilities, like utilities to convert Strings to and from Date Objects, based on a <a href="http://java.sun.com/javase/6/docs/api/index.html?java/text/SimpleDateFormat.html">SimpleDateFormat</a> pattern. This pattern is part of the generated JavaScript and is obtained by looking at the attached Converters.</p>
<p><b>Usage in a Facelet</b><br />
To make the ClientBehavior a bit easier to use, here&#8217;s a Facelets taglib which defines a tag for the ClientBehavior (don&#8217;t forget to configure the taglib in web.xml or put it in the /META-INF of a JAR).</p>
<pre><script type="syntaxhighlighter" class="brush: java">
&lt;?xml version='1.0' encoding='UTF-8'?&gt;
&lt;facelet-taglib version="2.0"
                xmlns="http://java.sun.com/xml/ns/javaee"&gt;
    &lt;namespace&gt;http://www.jkva.org/validateBeanBehavior&lt;/namespace&gt;
    &lt;tag&gt;
        &lt;tag-name&gt;validateBean&lt;/tag-name&gt;
        &lt;behavior&gt;
            &lt;behavior-id&gt;org.jkva.ValidateBeanBehavior&lt;/behavior-id&gt;
        &lt;/behavior&gt;
    &lt;/tag&gt;
&lt;/facelet-taglib&gt;
</script></pre>
<p>With the taglib in place, we can use the ClientBehavior, like this:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:jkva="http://www.jkva.org/validateBeanBehavior"&gt;
&lt;h:head&gt;
    &lt;title&gt;test&lt;/title&gt;
&lt;/h:head&gt;
&lt;h:body&gt;
    &lt;h:messages/&gt;
    &lt;h:form&gt;
        &lt;h:outputLabel value="text" for="text" /&gt;
        &lt;h:inputText value="#{myBean.text}" id="text"/&gt;&lt;br/&gt;

        &lt;h:outputLabel value="number" for="number" /&gt;
        &lt;h:inputText value="#{myBean.number}" id="number" /&gt;&lt;br/&gt;

        &lt;h:outputLabel value="date" for="date" /&gt;
        &lt;h:inputText value="#{myBean.date}" id="date"&gt;
            &lt;f:convertDateTime pattern="dd-MM-yyyy"/&gt;
        &lt;/h:inputText&gt;&lt;br/&gt;
        &lt;h:commandButton value="Hello" action="/hello" immediate="true"/&gt;
        &lt;h:commandButton value="Click" action="#{myBean.click}"&gt;
            &lt;jkva:validateBean /&gt;
        &lt;/h:commandButton&gt;
    &lt;/h:form&gt;
&lt;/h:body&gt;
&lt;/html&gt;
</script></pre>
<p>That&#8217;s not too much effort for a client side form validation right? And, these validations are always in-sync with the server side validations.</p>
<p>After a bit of cleanup, I&#8217;ll commit the code into the <strong><a href="http://myfaces.apache.org/sandbox/index.html">Apache MyFaces Sandbox</a></strong>, so you can download it from there when I&#8217;m done. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/17/jsf-2-0-clientbehavior-bean-validation-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to de-frameset a Web App with Apache Tiles 2</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 15:45:12 +0000</pubDate>
		<dc:creator>Assen Kolov</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tiles]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=995</guid>
		<description><![CDATA[To get rid of FRAMESET, a servlet renders any desired URL embodied in a tiles definition.]]></description>
			<content:encoded><![CDATA[<h3>
The problem</h3>
<p>There&#8217;s is a good old application from the days when struts still had to be invented and framesets weren&#8217;t considered evil. The problems associated with a FRAMESET are another topic, the fact is the application owner wants to get rid of them and asked me to look for a solution that would be unobtrusive and easy to implement, understand and maintain.</p>
<h3>
Current Situation</h3>
<p>The application uses no web-app framework, each Use Case is implemented in a separate servlet,  all of them neatly mapped in the web.xml. The FRAMESET setup is classic: apart from the static elements, the navigation happens in a &#8216;body&#8217; and a &#8216;menu&#8217; frame. The normal flow is to select a command from the menu frame, e.g. Place Order results in (&lt;a href=&#8221;/placeorder&#8221; target=&#8221;&#8216;body&#8221;/&gt;), then submit a few forms in the body frame (&lt;form action=&#8221;/placeorder&#8221; method=&#8221;POST&#8221;&gt;&#8230;&lt;/form&gt;). Without frameset, when a HTTP request for /placeorder reaches the application, we want the servlet response decorated  with the other fragments: menu, header and the rest. The differences are essential: there is just one request/response and all page fragments have to share the same HEAD, CSS etc.</p>
<h3>
Introducing Apache Tiles 2</h3>
<p>The good news is that version 2.x of Apache Tiles, which has started as struts extension, is now framework-independent. It offers support for JSP, Freemarker, and can be used directly from a servlet or filter. First of all, a template is needed to replace the frameset, e.g. main.jsp:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib uri=&quot;http://tiles.apache.org/tags-tiles&quot; prefix=&quot;tiles&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
 &lt;link href=&quot;/online/theme/online.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
    &lt;script language=&quot;javascript&quot; src=&quot;/online/js/algemeen.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table border=&quot;1&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot;
 style=&quot;width: 100%; height: 100%&quot;&gt;
 &lt;tr&gt;
  &lt;td colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;top&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
  &lt;td&gt;&lt;tiles:insertAttribute name=&quot;menu&quot; /&gt;&lt;/td&gt;
  &lt;td&gt;&lt;tiles:insertAttribute name=&quot;body&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
  &lt;td colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;bottom&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</script></pre>
<p>Based on that template a tile definition can render a decorated view of any servlet output (e.g. /placeorder). A definition per servlet is needed in tiles.xml:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN&quot;
       &quot;http://tiles.apache.org/dtds/tiles-config_2_0.dtd&quot;&gt;

&lt;tiles-definitions&gt;

 &lt;definition name=&quot;placeorder.tile&quot; template=&quot;/layout/main.jsp&quot;&gt;
  &lt;put-attribute name=&quot;top&quot; value=&quot;/algemeen/onlinetop.html&quot; /&gt;
  &lt;put-attribute name=&quot;menu&quot; value=&quot;/besturing/menu.jsp&quot; /&gt;
  &lt;put-attribute name=&quot;body&quot; value=&quot;/placeorder&quot; /&gt;
  &lt;put-attribute name=&quot;bottom&quot; value=&quot;/algemeen/onlinebottom.html&quot; /&gt;
 &lt;/definition&gt;
&lt;/tiles-definitions&gt;

</script></pre>
<p>This definition still has to be rendered, e.g. from another JSP, let&#8217;s call it placeholder_tiled.jsp:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;%@ taglib uri=&quot;http://tiles.apache.org/tags-tiles&quot; prefix=&quot;tiles&quot; %&gt;

&lt;tiles:insertDefinition name=&quot;placeorder.tile&quot; /&gt;
</script></pre>
<p>A separate tile definition and a JSP page for each servlet would be too much code repetition. Let&#8217;s see how to the output of any servlet.</p>
<h3>
A View decorating servlet</h3>
<p>I like the idea of having separate URLs for the servlet output and for a composite view of the same output. Thanks to Tiles 2 API, one servlet could provide decorated views of the output of all servlets. In tiles.xml, I added a tile definition with all attributes except body defined:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN&quot;
       &quot;http://tiles.apache.org/dtds/tiles-config_2_0.dtd&quot;&gt;

&lt;tiles-definitions&gt;
 &lt;definition name=&quot;main.tile&quot; template=&quot;/layout/main.jsp&quot;&gt;
  &lt;put-attribute name=&quot;top&quot; value=&quot;/algemeen/onlinetop.html&quot; /&gt;
  &lt;put-attribute name=&quot;menu&quot; value=&quot;/besturing/menu.jsp&quot; /&gt;
  &lt;!-- name=&quot;body&quot;  not defined --&gt;
  &lt;put-attribute name=&quot;bottom&quot; value=&quot;/algemeen/onlinebottom.html&quot; /&gt;
 &lt;/definition&gt;

&lt;/tiles-definitions&gt;

</script></pre>
<p>Let&#8217;s define a servlet that will fill in the missing body attribute for each URL ending with .tiled:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">&lt;servlet&gt;
 &lt;display-name&gt;TilesServlet&lt;/display-name&gt;
 &lt;servlet-name&gt;TilesServlet&lt;/servlet-name&gt;
 &lt;servlet-class&gt;com.assenkolov.common.web.TilesServlet&lt;/servlet-class&gt;
 &lt;init-param&gt;
 &lt;param-name&gt;template.name&lt;/param-name&gt;&lt;param-value&gt;main.tile&lt;/param-value&gt;&lt;/init-param&gt;
 &lt;init-param&gt;
 &lt;param-name&gt;attribute.name&lt;/param-name&gt;&lt;param-value&gt;body&lt;/param-value&gt;&lt;/init-param&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
 &lt;servlet-name&gt;TilesServlet&lt;/servlet-name&gt;
 &lt;url-pattern&gt;*.tiled&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</script></pre>
<p>Finally, the servlet itself:</p>
<pre><script type="syntaxhighlighter" class="brush: java">public class TilesServlet extends HttpServlet {
 private String templateName;
 private String attributeName;

 @Override
 public void init() throws ServletException {
  super.init();
  templateName = getInitParameter("template.name");
  attributeName = getInitParameter("attribute.name");
 }

 @Override
 public void service(HttpServletRequest request, HttpServletResponse response) 
  throws  ServletException, IOException {
   ServletContext servletContext = request.getSession().getServletContext();

   TilesContainer container = ServletUtil.getContainer(servletContext);
   AttributeContext attributeContext = container.startContext(request, response);

   // Remove the ".tiled" suffix from the request path
   String requestPath = request.getServletPath().replace(".tiled", "");
   Attribute attr = new Attribute(requestPath);

   Map<string, attribute=""> attrs = new HashMap<string, attribute="">();
   attrs.put(attributeName, attr);
   attributeContext.addAll(attrs);

   container.render(templateName, request, response);
   container.endContext(request, response);
  }
}
</script></pre>
<p>This servlet always renders the same tiles definition, providing an appropriate body. For example, a request to /showOrder.tiled?orderId=100 would render the output of /showOrder?orderId=100 as the body tile in the tiles definition. No separate tiles definition and JSP for each view are needed.</p>
<h3>
What&#8217;s next?</h3>
<p>All the code above only provides an easy template-decorated view for each servlet output. There is sill a lot of work that has to be done manually:<br />
- move all separate styles, scripts etc. from the separate pages to the template<br />
- requestDispacher.forward in a servlet closes the output stream while it is still needed for the tiles template; all forwards must become includes;<br />
- all navigation javascript referring to top.menu ot top.body has to be refatored manually.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/16/how-to-de-frameset-an-old-app-with-apache-tiles-2-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing a Bean Validation ConstraintValidator</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 15:27:16 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[ConstraintValidator]]></category>
		<category><![CDATA[Dynamic Proxies]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Mockito]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=976</guid>
		<description><![CDATA[I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.
First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing a bit with Bean Validation and thought I found an issue: Unit testing a ConstraintValidator. Specifically, parametrized ConstraintValidators.</p>
<p>First, what&#8217;s a parametrized ConstraintValidator? Simple, a Validator that takes a parameter to do its job. A simple example is a length validator that takes the minimum and maximum length as parameters and validates if the value is between those two.</p>
<p>Parametrized ConstraintValidators are everywhere, even Bean Validation itself contains them. For example: @Min(length) and @Max(length), but also normal ConstraintValidators, like @NotNull where you can customize the error message. However, this error message parameter is not very interesting with regards to unit testing individual ConstraintValidators, because the message is generated by the Bean Validation framework.</p>
<p>For example, consider this ConstraintValidator, incl. corresponding annotation:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CreditCardExpiryYearValidator.class)
public @interface CreditCardExpiryYear {
    int expirationInYears() default 10;
    String message() default "{validation.CreditCardExpiryYear.message}";
}

public class CreditCardExpiryYearValidator implements ConstraintValidator&lt;CreditCardExpiryYear, Integer&gt; {
    private volatile int expirationInYears;
    public void initialize(CreditCardExpiryYear constraint) {
        this.expirationInYears = constraint.expirationInYears();
    }

    public boolean isValid(Integer year, ConstraintValidatorContext context) {
        final int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        return year != null
            &amp;&amp; year &lt; nowYear + expirationInYears;
    }
}
</script></pre>
<p>In the future, Bean Validation may become the core mechanism for ensuring correctness in your system. For example, JPA 2.0 leverages Bean Validation annotations to generate additional DDL statements and JSF 2.0 automatically uses Bean Validation when it&#8217;s available. Note: JSF 2.0 uses a new concept, called &#8220;default validators&#8221; to implement this. A default validator is invoked on every input component on a postback.</p>
<p>But, how do we test this stuff? After all, you can&#8217;t instantiate an annotation.</p>
<p>I currently have 4 options:</p>
<ul>
<li><a href="#reflection">Using reflection to use a declared annotation</a></li>
<li><a href="#implementation">Custom annotation implementation</a></li>
<li><a href="#dynamic_proxies">Dynamic proxies</a></li>
<li><a href="#mockito">Mocking, for example using Mockito</a></li>
</ul>
<p><b><a name="reflection">Using a declared annotation</a></b><br />
The first attempt is shown below. Here, I simply declare the annotation in my test case on a dummy instance field (an annotation doesn&#8217;t live on its own) and look it up using reflection. This way, Java takes care of instantiating and initializing the annotation.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    @CreditCardExpiryYear(expirationInYears = 5)
    int expiryAfter5Years;

    @CreditCardExpiryYear
    int expiryAfter10Years;

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_DefaultExpiration() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter10Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 5, null);

        assertTrue(b);
    }

    @Test
    public void testIsValid_Configure5Years() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(getFieldAnnotation(this, "expiryAfter5Years", CreditCardExpiryYear.class));

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
</script></pre>
<p>I personally quite like this approach. The test data is inside the test case. Unfortunately not in the test method, that would be better, but since you can&#8217;t put annotations everywhere in your code, it&#8217;s not easy to implement this decently.</p>
<p>So let&#8217;s look at the next one&#8230;</p>
<p><b><a name="implementation">Custom annotation implementation</a></b><br />
Since Java annotations are just a special case of interfaces, they should be fairly straightforward to implement. However, for some reason, I didn&#8217;t know this until recently. But it&#8217;s actually not different from any other interface implementation. See for yourself.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class CreditCardExpiryYearValidatorTest {

    private int currentYear;

    @Before
    public void setUp() throws Exception {
        currentYear = Calendar.getInstance().get(Calendar.YEAR);
    }

    @Test
    public void testIsValid_CustomAnnotationImpl() throws Exception {
        CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
        val.initialize(new CreditCardExpiryYearImpl());

        boolean b = val.isValid(currentYear + 6, null);

        assertFalse(b);
    }
}
class CreditCardExpiryYearImpl implements CreditCardExpiryYear {
    public int expirationInYears() { return 5; }
    public String message() { return "hello"; }
    public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
}
</script></pre>
<p>Nothing special, right? But I don&#8217;t really like it. I could have also written it inline, but I don&#8217;t like that either:</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_CustomAnnotationImplInline() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    val.initialize(new CreditCardExpiryYear() {
        public Class&lt;? extends Annotation&gt; annotationType() { return CreditCardExpiryYear.class; }
        public String message() { return ""; }
        public int expirationInYears() { return 5; }
    });

    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>I think the above one looks like garbage. So this is also a no-go.</p>
<p><b><a name="dynamic_proxies">Dynamic proxies</a></b><br />
Java itself uses dynamic proxies at runtime to instantiate annotations. So why not also use a Proxy to mock the annotation? See for yourself. </p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_DynamicProxy() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = (CreditCardExpiryYear)
            Proxy.newProxyInstance(
                    this.getClass().getClassLoader(),
                    new Class&lt;?&gt;[] { CreditCardExpiryYear.class },
                    new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return 5;
        }
    });
    val.initialize(new CreditCardExpiryYearImpl());
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>However inline, the implementation looks very clumsy. Unfortunately this is probably as simple as it can get, since you DO need to define the inner class.</p>
<p>And it will become even worse when there are multiple parameters on the bean, since you need to check which method is invoked. This will make the implementation even worse.</p>
<p><b><a name="mockito">Mocking using Mockito</a></b><br />
But, creating and configuring proxies, isn&#8217;t this what mocking libraries do? Exactly, let&#8217;s try.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
@Test
public void testIsValid_Mockito() throws Exception {
    CreditCardExpiryYearValidator val = new CreditCardExpiryYearValidator();
    CreditCardExpiryYear annotation = mock(CreditCardExpiryYear.class);
    when(annotation.expirationInYears()).thenReturn(5);

    val.initialize(annotation);
    boolean b = val.isValid(currentYear + 6, null);

    assertFalse(b);
}
</script></pre>
<p>This looks pretty nice. And it scales well with multiple attributes.</p>
<p>I only doubt it will be the nicest solution when the annotations become more complex. I really don&#8217;t like annotations that contain annotation parameters. Or even worse, arrays of annotation parameters. But reality is, they exist. And if they exist, they also need to be tested. But, OTOH, people who nest annotations probably don&#8217;t mind unreadable unit tests. <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/12/unit-testing-a-bean-validation-constraintvalidator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hibernate, lazy loading and inheritance</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 12:35:15 +0000</pubDate>
		<dc:creator>gnoij</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[Java API]]></category>
		<category><![CDATA[Object Relational Mapping]]></category>
		<category><![CDATA[ClassCastException]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[lazy loading]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=956</guid>
		<description><![CDATA[A common problem with typecasting a lazy loaded entity to its child is a ClassCastException. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.
Suppose we have a class B which extends A and a class C which has class A as a member as shown below.

public [...]]]></description>
			<content:encoded><![CDATA[<p>A common problem with typecasting a lazy loaded entity to its child is a <em>ClassCastException</em>. This exception occurs because the dynamic created proxy implements the baseclass and has no knowledge about its subclasses.</p>
<p>Suppose we have a class <em>B</em> which extends <em>A</em> and a class <em>C</em> which has class <em>A</em> as a member as shown below.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
public class A {

    private Long id;

    private String name;

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public Long getId() { return id; }
}

public class B extends A {

    private String somethingElse;

    public String getSomethingElse() { return somethingElse; }

    public void setSomethingElse(String something) { this.somethingElse = something; }

}

public class C {

    private Long id;

    private A a;

    public A getA() { return a; }

    public void setA(A a) { this.a = a; }

    public Long getId() { return id; }
}
</script></pre>
<p>The following test will fail with a<em> ClassCastException</em> on the last line.</p>
<pre><script type="syntaxhighlighter" class="brush: java">public void testClassCastException() {

	B b = new B();
	b.setName("B");
	b.setSomethingElse("test");

	C c = new C();
	c.setA(b);

	save(c);
	// just for testing purposes we clear the session, so
	// c is actually loaded from the database
	clearSession(); 

	c = retrieve(C.class, c.getId());
	b = (B) c.getA();
}
</script></pre>
<p><em> The methods save(), clearSession() and retrieve() are just helper methods which implement the Hibernate session methods save(), clear() and get().</em></p>
<p>A search on the Internet shows a couple of solutions for this problem.</p>
<ol>
<li><a href="http://sysin.wordpress.com/2009/02/27/hibernate-inheritance-classcastexception-part-1/">Using interfaces as a proxy in the hibernate mappings</a>. This will result in accessing the object through its interface only so all methods must be exposed in the interface. I don&#8217;t want to expose every public or protected method in the interface which are not intended for use by external parties.</li>
<li><a href="https://www.hibernate.org/280.html">Using the Visitor Pattern to access the correct childclass</a>. This means that users of these objects must write a lot of code just to use some getters. I don&#8217;t want to burden someone else with a local Hibernate problem.</li>
<li>Using <em>((HibernateProxy)object).getHibernateLazyInitializer().getImplementation()</em> whenever a typecast of an object to its child class is needed.</li>
</ol>
<p>All of the solutions mentioned above are not suitable for me so I decided on another solution which is a variant of solution 3.</p>
<p>With a slight modification of the method <em>getA()</em> in class <em>C</em>, exposing the <em>HibernateProxy</em> is avoided.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
    public A getA() { return deProxy(a); }

    protected  <T extends Object> T deProxy(T object) {
        if (object instanceof HibernateProxy) {
            return (T)((HibernateProxy)object).getHibernateLazyInitializer().getImplementation();
        }
        return object;
    }
</script></pre>
<p>Now the test completes without failure.</p>
<p>This has to be done for every getter which can return a lazy loaded proxy.</p>
<p>And if you (like me) don&#8217;t want Hibernate code in your domain model, you can move this code to the persistence layer and use dependency injection to use it.</p>
<p>It&#8217;s still not an elegant solution (IMHO there isn&#8217;t one), but its the best usable for me.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/03/08/hibernate-lazy-loading-and-inheritance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Unified Expression Language in Maven-Jetty-Plugin</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 15:51:57 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[bean validation]]></category>
		<category><![CDATA[jetty]]></category>
		<category><![CDATA[JSF 2.0]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[maven-jetty-run]]></category>
		<category><![CDATA[UEL]]></category>
		<category><![CDATA[unified expression language]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=927</guid>
		<description><![CDATA[I like the maven-jetty-plugin. If I download an Open Source project, I usually first look for this baby, because it allows me to quickly run the code in a tested environment. This saves me from a lot of configuration, which would otherwise cause me to lose interest. This often doesn&#8217;t take long&#8230;  
Also, you [...]]]></description>
			<content:encoded><![CDATA[<p>I like the maven-jetty-plugin. If I download an Open Source project, I usually first look for this baby, because it allows me to quickly run the code in a tested environment. This saves me from a lot of configuration, which would otherwise cause me to lose interest. This often doesn&#8217;t take long&#8230; <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Also, you can completely configure the server in your POM, centralizing configuration and making it thus easy to store server settings in version control. Also, the mvn-jetty-plugin benefits from your existing Maven project configuration, like <code>dependencyManagement</code>.</p>
<p>Some of my buddies at Apache even use the maven-jetty-plugin on a daily basis for their real work. I never got this far, mostly because I&#8217;m more familiar with Tomcat, but also because I didn&#8217;t really see it as a mature development tool. However, today I decided to give it a chance.</p>
<p><strong>The first attempt</strong><br />
So, I created a simple webapp in my favorite IDE: <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a> and added a Maven2 POM to enable Maven2 support. All well so far.</p>
<p>This was the initial version of my POM:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>zzz</groupId>
    <artifactId>zzz</artifactId>
<packaging>war</packaging>
    <version>0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.10</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <finalName>ueltest</finalName>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.14</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>foo</stopKey>
                    <stopPort>9999</stopPort>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</script></pre>
<p>All was fine, my test app was running, but I needed to enable <a href="http://www.mojavelinux.com/blog/archives/2009/08/why_you_didnt_know_the_unified_el_is_being_updated/">Unified EL</a> to test <a href="http://myfaces.apache.org/">MyFaces</a> <a href="http://java.sun.com/javaee/6/docs/api/javax/faces/validator/BeanValidator.html">BeanValidator</a>.</p>
<p><strong>Adding UEL libraries</strong><br />
So, I added a dependency to the UEL API and Impl in my POM, but there was an issue. Every web container already provides the old Expression Language in the jsp-api.jar. So I&#8217;m not allowed to package my own EL libraries.</p>
<p>However, I&#8217;m quite stubborn, so I tried anyway:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
...
<dependencies>
    ...
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>el-api</artifactId>
        <version>2.2.1-b01</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>el-impl</artifactId>
        <version>2.1.2-b05</version>
        <scope>runtime</scope>
    </dependency>
    ...
</dependencies>
...
</script></pre>
<p>So, let&#8217;s give it a try:
<pre>mvn jetty:run-exploded</pre>
<p> (MyFaces 2.0 requires exploded deployment in Jetty).</p>
<p>Result? BOOOM!</p>
<pre><script type="syntaxhighlighter" class="brush: plain">
java.lang.LinkageError: loader constraint violation: loader (instance of org/mortbay/jetty/webapp/We
bAppClassLoader) previously initiated loading for a different type with name "javax/el/ExpressionFac
tory"
</script></pre>
<p><strong>The fix, replacing libraries</strong><br />
The error is completely appropriate. You&#8217;re just not allowed to package your own version of the servlet libraries. That&#8217;s the job of the servlet container. Failing to do so will result in the error shown above.</p>
<p>So we need to fix this issue by somehow replacing the Jetty libraries or at least changing the way Jetty loads its jsp-api.jar. This is no trivial task however, since jetty is initialized by Maven and doesn&#8217;t have a fixed directory structure on disk.</p>
<p>So we need to have some way in Maven to configure the Jetty libraries.</p>
<p>First, <strong><em>Jetty doesn&#8217;t have an endorsed mechanism</em></strong>, so that&#8217;s a no-go.</p>
<p>But the fix is actually quite easy, just pass some dependencies into the jetty plugin in the POM.</p>
<p>The final POM looks like this:</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>zzz</groupId>
    <artifactId>zzz</artifactId>
<packaging>war</packaging>
    <version>0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-api</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.apache.myfaces.core</groupId>
            <artifactId>myfaces-impl</artifactId>
            <version>2.0.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.0.2.GA</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.10</version>
        </dependency>
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2.1-b01</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jboss</id>
            <url>http://repository.jboss.com/maven2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>glassfish</id>
            <url>http://download.java.net/maven/2</url>
            <releases>
                <enabled>true</enabled>
            </releases>
        </repository>
    </repositories>
<pluginRepositories>
<pluginRepository>
            <id>jboss-plugins</id>
            <url>http://repository.jboss.com/maven2</url>
        </pluginRepository>
    </pluginRepositories>

    <build>
        <finalName>test</finalName>
<plugins>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
<plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>maven-jetty-plugin</artifactId>
                <version>6.1.14</version>
                <configuration>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <stopKey>foo</stopKey>
                    <stopPort>9999</stopPort>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>javax.servlet.jsp</groupId>
                        <artifactId>jsp-api</artifactId>
                        <version>2.2</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>javax.el</groupId>
                        <artifactId>el-api</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.glassfish.web</groupId>
                        <artifactId>el-impl</artifactId>
                        <version>2.2.1-b01</version>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.mortbay.jetty</groupId>
                        <artifactId>jsp-2.1</artifactId>
                        <version>6.1.14</version>
                        <scope>provided</scope>
                        <exclusions>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jsp-api-2.1</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>start</artifactId>
                            </exclusion>
                            <exclusion>
                                <groupId>org.mortbay.jetty</groupId>
                                <artifactId>jetty-annotations</artifactId>
                            </exclusion>
                        </exclusions>
                    </dependency>
                </dependencies>
</plugin>
        </plugins>
    </build>
</project>
</script></pre>
<p>As you can see, Maven takes care of the heavy lifting. You only need to specify your dependencies and they will override any dependencies with the same groupId, artifactId and type.</p>
<p>So, now I don&#8217;t have any reason not to use mvn-jetty-run to test my code!</p>
<p>Happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/27/using-unified-expression-language-in-maven-jetty-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>REST made easy with Java EE 6 and JAX-RS 1.1</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 06:34:25 +0000</pubDate>
		<dc:creator>Stephan Oudmaijer</dc:creator>
				<category><![CDATA[Java EE]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=893</guid>
		<description><![CDATA[In my previous post I wrote about Spring 3.0 and how Spring MVC enables REST services in Spring 3.0. Java EE 6 adds support for RESTfull services by adding JAX-RS to the specification. In this post I will show how JAX-RS 1.1 will make your life easy when writing RESTfull services for JEE 6. 
GlassFish [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://oudmaijer.com/cms/index.php?mact=News,cntnt01,detail,0&#038;cntnt01articleid=23">my previous post</a> I wrote about Spring 3.0 and how Spring MVC enables REST services in Spring 3.0. Java EE 6 adds support for RESTfull services by adding JAX-RS to the specification. In this post I will show how JAX-RS 1.1 will make your life easy when writing RESTfull services for JEE 6. </p>
<p><a href="https://glassfish.dev.java.net/">GlassFish v3</a> is an open source application server and is the first compatible implementation of the Java EE 6 platform specification. To test the examples in this article I will assume that you use GlassFish (or any other JEE6 enabled application server) to run the examples.</p>
<p><b>Maven2 dependencies</b></p>
<p>Lets start with the Maven dependencies, you can add them all to the <code>pom.xml</code> of your war. I have also included Sun&#8217;s Maven2 repository for downloading the JEE6 dependencies like the javaee-api and Sun&#8217;s JAX-RS 1.1 implementation called Jersey.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
...
<repository>
    <id>maven2-repository.dev.java.net</id>
    <name>Java.net Repository for Maven</name>
    <url>http://download.java.net/maven/2/</url>
</repository>
...
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>6.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-server</artifactId>
    <version>1.1.5</version>
    <scope>provided</scope>
</dependency>
...
</script></pre>
<p>Both dependencies are scoped as provided because GlassFish already ships with these libraries. In fact, my war file is not bigger than 22kb. JEE6 allowes developers to package full blown JEE application as a web archive file, there is no need for an enterprise archive anymore. This makes JEE6 applications really light weight. </p>
<p><b>JAX-RS RESTfull services in JEE6</b></p>
<p>JAX-RS supports configuration through annotations, just like the Spring 3.0 REST annotations. Annotations can be added to both classes and methods. Classes in JAX-RS can be POJO`s. One thing about JAX-RS is that it does not integrate well with other JEE specification, for example the JSR-330 annotations for dependency injection are not supported by JAX-RS (yet), but there is a workaround <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Because of the flexibility of JAX-RS it is possible to annotate EJB SessionBean or CDI components with JAX-RS annotations. So when a bean with JAX-RS annotation is packaged in a war file, the annotations are automatically picked up by the JAX-RS implementation (Jersey in this case). Since EJB3.1 SessionBeans and CDI components support all of the dependency injection features offered by JEE6, JAX-RS now does too! </p>
<p>Below is an example JAX-RS annotated class. The goal of this RESTfull service is to expose two methods of the ProductService through a RESTfull interface. The ProductService is injected using the @Inject annotation. </p>
<p>In JAX-RS the @Path annotation is used to map an URI to a REST service. In the example below I&#8217;ve defined the @Path annotation on the class, this will map all the URIs starting with /product to this class. I also defined the @ManagedBean (CDI) annotation on the class for the @Inject to work properly. </p>
<p>There are two methods within the service which are annotated with @Path, @GET and @Produces. The @Path is the same as with the class, but in this case it maps URI&#8217;s to a method. The URI of a method is relative to URI specified in the @Path annotation<br />
on the class. So the following URLs are mapped in this example:</p>
<li>/product/category/{categoryId} which returns all products in a category</li>
<li>/product/categories which returns all product categories</li>
<p>JAX-WS allowes for mapping HTTP methods like GET, PUT, POST and DELETE to Java methods with the @GET, @PUT, @POST and @DELETE annotations. In this example only the GET method is used. In RESTfull service the HTTP GET is used to retrieve data. To map a GET request to a method you can simply annotate a method with @GET.</p>
<p>The @Produces annotation specifies the Mime-Type of the response data the methods produces. In this example the methods both produce XML data, therefore we need to set the Mime-Type to application/xml. When returning an Object from a method annotated with @Produces, JAX-RS trieds to find an appropriate converter to produces the output. In this case I will use JAXB will to marshall the Objects to XML (see below).</p>
<pre><script type="syntaxhighlighter" class="brush: java">
package com.oudmaijer.webshop.web.rest;

import com.oudmaijer.webshop.domain.Category;
import com.oudmaijer.webshop.domain.Product;
import com.oudmaijer.webshop.service.ProductService;

import javax.annotation.ManagedBean;
import javax.inject.Inject;
import javax.naming.NamingException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.List;

/**
 * Rest service for Products.
 * 
<p/>
 * User: sou12983
 * Date: 18-feb-2010
 * Time: 10:15:04
 */
@Path(value = "/product")
@ManagedBean
public class ProductRestlet {

    @Inject
    private ProductService productService;

    /**
     * Returns all the product categories in XML format.
     *
     * @return
     * @throws NamingException
     */
    @GET
    @Path("/categories")
    @Produces("application/xml")
    public List<Category> getCategories() throws NamingException {
        return productService.getCategories();
    }

    /**
     * Returns all the products in a specified category.
     *
     * @param categoryId
     * @return
     * @throws NamingException
     */
    @GET
    @Path("/category/{categoryId}")
    @Produces("application/xml")
    public List<Product> getProducts(@PathParam(value = "categoryId") Long categoryId) throws NamingException {
        return productService.getProducts(categoryId);
    }
}
</script></pre>
<p><b>JAXB marshalling</b></p>
<p>In order for JAXB to marshall the Objects returned, we need to specify JAXB annotations on the Objects returned from the methods.<br />
In this example I&#8217;ve added @XmlRootElement to the returned Objects to simply marshall the entire Object to XML.</p>
<pre><script type="syntaxhighlighter" class="brush: java">
package com.oudmaijer.webshop.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Product {
...
}

package com.oudmaijer.webshop.domain;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Category{
...
}
</script></pre>
<p><b>Adding Jersey to the web deployment descriptor: web.xml</b></p>
<p>For JAX-RS to work we still need to add a Servlet to the web.xml which maps URL&#8217;s to the services. In this case we need to add the JerseyServlet to the web.xml. In the servlet-mapping all /rest/ URL patterns are mapped to Jersey. We can access the REST services using the following URIs: /rest/product/etc.</p>
<pre><script type="syntaxhighlighter" class="brush: xml">
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>JerseyServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>
</script></pre>
<p><b>Conclusion</b></p>
<p>When building RESTfull services on an JEE6 enabled application server, JAX-RS really makes things easy. You will have to decide for your specific case if you want to use Spring or JAX-RS.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/19/rest-made-easy-with-java-ee-6-and-jax-rs-1-1/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>DefaultMessageListenerContainer troubles in Websphere</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 14:19:57 +0000</pubDate>
		<dc:creator>Michel.Schudel</dc:creator>
				<category><![CDATA[Algemeen]]></category>
		<category><![CDATA[jms]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[Websphere]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=859</guid>
		<description><![CDATA[Using the Spring DefaultMessageListenerContainer makes it easy for you to connect to a jms resource like a Queue so you can pick up messages from that queue.
Using this container in Websphere (6.0, 6.1, 7) some problems occur when you want to do the following:

You use a resource environment reference for your destination, specified in the [...]]]></description>
			<content:encoded><![CDATA[<p>Using the Spring <code>DefaultMessageListenerContainer</code> makes it easy for you to connect to a jms resource like a Queue so you can pick up messages from that queue.</p>
<p>Using this container in Websphere (6.0, 6.1, 7) some problems occur when you want to do the following:</p>
<ul>
<li>You use a resource environment reference for your destination, specified in the web.xml, for the Destination.</li>
<li>You use the property <code>destinationName</code> on the <code>DefaultMessageListenerContainer</code> in combination with a <code>JndiDestinationResolver</code> to look up your resource environment reference like this: <code>java:comp/env/jms/(your destination)</code></li>
</ul>
<p><strong>problem</strong><br />
When you try to start the application, you will get an exception like this: <code>javax.naming.NameNotFoundException: Name "comp/env/jms/(your destination)" not found in context "java:".</code>, although you are sure that your resource environment reference is defined correctly.</p>
<p><strong>cause</strong><br />
The cause of this problem lies in the fact that the lookup occurs in a Thread started by the <code>DefaultMessageListenerContainer</code>, which is unmanaged by Websphere. This thread will not have the jndi queue bindings in its <code>InitialContext</code>.</p>
<p><strong>solution</strong><br />
You can either:</p>
<ol>
<li>Specifiy the jndi object beforehand with a <code>JndiObjectFactoryBean</code>, or a <code><br />
  &lt;jee:jndi-lookup id="myqueue" jndi-name="java:comp/env/jms/(your destination)"/&gt;</code>, and then<br />
  setting the <code>destination</code> property of the <code>DefaultMessageListenerContainer</code> to the ref <code>myqueue</code>, so no actual lookup occurs within the thread of the listener itself.</li>
<li>
  Delegate the listener&#8217;s thread to Websphere with the help of the Spring class <code>WorkManagerTaskExecutor</code>. You can then set the property <code>taskExecutor</code> on the message listener container to reference this class. See the <a href="http://www.ibm.com/developerworks/websphere/techjournal/0609_alcott/0609_alcott.html">IBM article here </a> for details on how to do this.
</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/02/03/defaultmessagelistenercontainer-troubles-in-websphere/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JSF 2.0: The most simple CDI integration use cases</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 19:45:47 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[Java EE]]></category>
		<category><![CDATA[JavaServer Faces]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[CDI]]></category>
		<category><![CDATA[JSF 2.0]]></category>
		<category><![CDATA[Producer methods]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=851</guid>
		<description><![CDATA[If you have (just like me) been following the Web Beans and Contexts and Dependency Injection (CDI) work, you might be thinking (also just like I did): &#8220;That CDI is heavily over-engineered&#8221;. My &#8220;moment of clarity&#8221; was a year ago, at DeVoxx 2008.
It was a talk by Pete Muir of JBoss. He was showing a [...]]]></description>
			<content:encoded><![CDATA[<p>If you have (just like me) been following the Web Beans and <a href="http://jcp.org/en/jsr/detail?id=299">Contexts and Dependency Injection</a> (CDI) work, you might be thinking (also just like I did): &#8220;That CDI is heavily over-engineered&#8221;. My &#8220;moment of clarity&#8221; was a year ago, at <a href="http://devoxx.com/">DeVoxx</a> 2008.</p>
<p>It was a <a href="http://parleys.com/#sl=1&#038;st=5&#038;id=1386">talk by Pete Muir of JBoss</a>. He was showing a really simple use case and tried to implement it using CDI. The talk was really technology driven and I hated it. Why? Because it wasn&#8217;t an improvement compared with the existing technologies. He wrote an application, containing several interfaces, classes (this is not bad) and custom annotations. If the goal was to show some kind of geniosity, it was a good talk. But if the goal was to show how this new technology would make our lives better&#8230; then sorry, he failed miserably.</p>
<p>More than a year further, there have been a lot of movements on the CDI front. And, as an <a href="http://myfaces.apache.org/">Apache MyFaces</a> developer, I&#8217;m of course very interested how to use CDI in a JSF 2.0 application. And as an Apache fanboy, I of course prefer Apache software, in this case MyFaces with <a href="http://openwebbeans.apache.org/">OpenWebBeans</a> and <a href="http://openjpa.apache.org/">OpenJPA</a>.</p>
<p><b>Configuration</b><br />
Since OpenWebBeans is still under development, you need to do some additional steps to get it to work.</p>
<p>The following POM should get you up and running quickly in Tomcat:</p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;org.apache.myfaces&lt;/groupId&gt;
    &lt;artifactId&gt;myfaces-example-ebanking&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;war&lt;/packaging&gt;

    &lt;dependencies&gt;
        &lt;!-- Compile dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
            &lt;artifactId&gt;myfaces-api&lt;/artifactId&gt;
            &lt;version&gt;${myfaces-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt;
            &lt;artifactId&gt;myfaces-impl&lt;/artifactId&gt;
            &lt;version&gt;${myfaces-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openjpa&lt;/groupId&gt;
            &lt;artifactId&gt;openjpa-all&lt;/artifactId&gt;
            &lt;version&gt;${openjpa-version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-digester&lt;/groupId&gt;
            &lt;artifactId&gt;commons-digester&lt;/artifactId&gt;
            &lt;version&gt;2.0&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openwebbeans&lt;/groupId&gt;
            &lt;artifactId&gt;openwebbeans-impl&lt;/artifactId&gt;
            &lt;version&gt;${openwebbeans.version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.openwebbeans&lt;/groupId&gt;
            &lt;artifactId&gt;openwebbeans-jsf&lt;/artifactId&gt;
            &lt;version&gt;${openwebbeans.version}&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.geronimo.specs&lt;/groupId&gt;
            &lt;artifactId&gt;geronimo-interceptor_1.1_spec&lt;/artifactId&gt;
            &lt;version&gt;1.0.0-EA1-SNAPSHOT&lt;/version&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;javax.annotation&lt;/groupId&gt;
            &lt;artifactId&gt;jsr250-api&lt;/artifactId&gt;
            &lt;version&gt;1.0&lt;/version&gt;
            &lt;scope&gt;compile&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- Test dependencies --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;version&gt;${junit-version}&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;repositories&gt;
        &lt;repository&gt;
            &lt;id&gt;Apache MyFaces beta&lt;/id&gt;
            &lt;name&gt;Apache MyFaces beta&lt;/name&gt;
            &lt;url&gt;http://people.apache.org/~lu4242/myfaces200beta&lt;/url&gt;
        &lt;/repository&gt;
    &lt;/repositories&gt;

    &lt;properties&gt;
        &lt;myfaces-version&gt;2.0.0-beta&lt;/myfaces-version&gt;
        &lt;openwebbeans.version&gt;1.0.0-SNAPSHOT&lt;/openwebbeans.version&gt;
        &lt;openjpa-version&gt;2.0.0-M3&lt;/openjpa-version&gt;
        &lt;junit-version&gt;4.7&lt;/junit-version&gt;
    &lt;/properties&gt;
&lt;/project&gt;
</pre>
<p>Note some of the additional dependencies required to run in Tomcat, as opposed to a full blown appserver.</p>
<p>Also, at the moment you need to <b>build OpenWebBeans from source manually</b>. The geronimo-interceptor_1.1_spec dependency will be downloaded to your local Maven repository on a &#8220;mvn install&#8221;. OpenJPA is not needed for this simple use case, but I use it in my project.</p>
<p><b>Code</b><br />
And then, the real code:</p>
<pre class="brush:java">
public class WebUtils {
    private static volatile String basePath;

    @Produces @Named public String getBasePath() {
        if (basePath == null) {
            basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
        return basePath;
    }
}
</pre>
<p>This class contains a so-called Producer Method. As the name suggests, it produces stuff. In this case, it produces a String with Dependent scope. This means the method will be invoked every time the variable is needed. EL expressions or injection are the most common cases for this.</p>
<p>I&#8217;m caching the return value, though it&#8217;s not necessary, since getting the context path is pretty cheap.</p>
<p>The view could look like this (snippet):</p>
<pre class="brush:xml">
...
&lt;link href="#{basePath}/style/default.css" rel="stylesheet" type="text/css" /&gt;
...
</pre>
<p>Another implementation could put the variable into the Application scope, like this:</p>
<pre class="brush:java">
public class WebUtils {
    @Produces @Named @ApplicationScoped public String getBasePath() {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
    }
}
</pre>
<p>As easy it might seem, the approaches shown above require some responsibility from the programmer though. With producer methods, it becomes really <b>easy to mess things up</b>. After all, you&#8217;re effectively creating <b>globals</b>. Tool support may help you here though. For example, the Dependency Analyzer in IntelliJ IDEA 9.0.1 already contains pretty decent <a href="http://www.jetbrains.com/idea/whatsnew/index.html#Java_EE_6_Support">support for JSF 2.0</a> and CDI. And, knowing the reputation of the JetBrains folks, I&#8217;m sure they come up with even more fancy stuff.</p>
<p><b>A more classic implementation</b><br />
A more classic implementation could look like the following:</p>
<pre class="brush:java">
@Named
@ApplicationScoped
public class WebBean {
    private static volatile String basePath;

    public String getBasePath() {
        if (basePath == null) {
            basePath = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
        }
        return basePath;
    }
}
</pre>
<p>I&#8217;m not using producer methods anymore. The WebBean is now a CDI-managed bean.</p>
<p>The client code becomes slightly more verbose, but who cares? I&#8217;ll put the client code in a generic template anyway!:</p>
<pre class="brush:xml">
...
&lt;link href="#{webBean.basePath}/style/default.css" rel="stylesheet" type="text/css" /&gt;
...
</pre>
<p><b>Wrapping up</b><br />
I haven&#8217;t even showed the complete tip of the iceberg. CDI offers several ways to write code and we&#8217;ve yet to find out the (anti) patterns.</p>
<p>I would like to point you to the <a href="http://openwebbeans.apache.org">OpenWebBeans documentation</a> for more info, but unfortunately this is still under development. The good news is that JBoss Weld already has extensive <a href="http://docs.jboss.org/weld/reference/1.0.0/en-US/html/">documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/31/jsf-2-0-the-most-simple-cdi-integration-use-cases/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSF 2.0: Maximum flexibility with System Events</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 15:41:31 +0000</pubDate>
		<dc:creator>Jan-Kees van Andel</dc:creator>
				<category><![CDATA[JavaServer Faces]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=812</guid>
		<description><![CDATA[JSF 2.0 adds a lot of interesting features. Andy Schwartz provides an extensive overview on his blog.
On this blog, I&#8217;d like to elaborate a bit further on the interesting features JSF 2.0 has to offer.
JSF 2.0: System Events
JSF 2.0 comes with a useful feature, called System events. System events are predefined events that are published [...]]]></description>
			<content:encoded><![CDATA[<p>JSF 2.0 adds a lot of interesting features. Andy Schwartz provides an extensive overview on his <a href="http://andyschwartz.wordpress.com/2009/07/31/whats-new-in-jsf-2/">blog</a>.</p>
<p>On this blog, I&#8217;d like to elaborate a bit further on the interesting features JSF 2.0 has to offer.</p>
<p><b>JSF 2.0: System Events</b><br />
JSF 2.0 comes with a useful feature, called System events. System events are predefined events that are published at predefined points in the lifecycle.<br />
System events are either global or component system events.</p>
<p><b>Global system events</b><br />
An example of a global system  event is PostConstructApplicationEvent, which is published when all configuration is done. It can be seen as a JSF replacement for ServletContextListener.</p>
<p>Listener registration is done by invoking Application.subscribeToEvent(Class&lt;? extends SystemEvent&gt; type, SystemEventListener listener).</p>
<p><b>Component system events</b><br />
Component system events only apply to the component to which the listener is attached.</p>
<p>An example of a component system event is PreRenderComponentEvent. This event is published to the appropriate component when it&#8217;s about to be rendered.</p>
<p>Listener registration is done by invoking UIComponent.subscribeToEvent(Class&lt;? extends SystemEvent&gt; type, ComponentSystemEventListener listener).</p>
<p><b>&lt;f:event /&gt; tag</b><br />
The JSF 2.0 spec also defines the &lt;f:event /&gt; tag, which needs to be nested inside a component tag in the web page. This tag is used to make listener registration easier. Just nest the tag inside a component tag in your Facelet, specify the event to listen to and specify a MethodExpression to your listener method and everything works.</p>
<p><b>An example</b><br />
Below is an example of an e-banking login page. It uses a challenge-response authentication mechanism, so it generates a &#8220;random&#8221; challenge when the page is loaded. Because users can navigate to the login page directly (GET-request), we can&#8217;t rely on an action method to be invoked first, so let&#8217;s fix this using system events.</p>
<p><b>First, a bit of history</b><br />
I&#8217;ve always hated to write &#8220;the first&#8221; page in JSF. Since JSF short circuits the lifecycle in the case of a GET request, you don&#8217;t really have an appropriate hook for page initialization, making it difficult to create a dynamic landing page.</p>
<p>One could write &#8220;lazy getters&#8221;:</p>
<pre class="brush:java">
public class MyBackingBean {
    private List<Account> accounts;

    public List<Account> getAccounts() { // Yuck
        if (accounts == null) {
            // Do some expensive database query
            accounts = doSomeWork();
        }
        return accounts;
    }
}
</pre>
<p>It&#8217;s quite obvious this is extremely nasty. You don&#8217;t know when the getter is invoked (EL triggers the invocation), and that if-null check is also ugly. Btw. getters with logic are ugly anyway&#8230;</p>
<p>JSF 1.2 offered a slightly more elegant option with @PostConstruct:</p>
<pre class="brush:java">
public class MyBackingBean {
    private List<Account> accounts;

    @PostConstruct
    public void init() {
        accounts = doSomeWork();
    }

    public List<Account> getAccounts() { // Still not good
        return accounts;
    }
}
</pre>
<p>This is a bit better, but still not very good. The exact point of invocation within the lifecycle is still not obvious. But at least we now know the init() method won&#8217;t be invoked multiple times.</p>
<p>There are other ways to tackle this issue, for example, using a PhaseListener, or using a framework like Seam, but that has issues of its own.</p>
<p><b>Back to the event example</b><br />
Below is a snippet of my login page.</p>
<pre class="brush:html">
&lt;h:form&gt;
  &lt;dl&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Customer ID" for="customerId" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:inputText id="customerId" value="#{loginBean.customerId}" required="true" /&gt;&lt;/dd&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Challenge" for="challenge" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:outputText id="challenge" value="#{loginBean.challenge}"&gt;
      &lt;f:event name="preRenderComponent" listener="#{loginBean.generateChallenge}" /&gt;
    &lt;/h:outputText&gt;&lt;/dd&gt;
    &lt;dt&gt;&lt;h:outputLabel value="Response (always 123456)" for="response" /&gt;&lt;/dt&gt;
    &lt;dd&gt;&lt;h:inputSecret id="response" value="#{loginBean.response}" required="true" /&gt;&lt;/dd&gt;
    &lt;dt&gt; &lt;/dt&gt;
    &lt;dd&gt;&lt;h:commandButton value="Login" action="#{loginBean.loginUsingTokenGenerator}" /&gt;&lt;/dd&gt;
  &lt;/dl&gt;
&lt;/h:form&gt;
</pre>
<p>As you can see, the above snippet contains the challenge response login form. Line 7 is the interesting one. It registers a PreRenderComponentEvent listener method on the LoginBean.</p>
<p>The LoginBean is shown next (snippet&#8230;).</p>
<pre class="brush:java">
@Named
@SessionScoped
public class LoginBean implements Serializable {
    private Integer customerId;
    private Integer challenge;
    private Integer response;
    private @Inject LoginService loginService;
    private Customer customer;
    // Getters and setters

    public void generateChallenge(ComponentSystemEvent event) throws AbortProcessingException {
        this.challenge = loginService.generateChallenge();
    }

    public String loginUsingTokenGenerator() {
        customer = loginService.loginUsingTokenGenerator(customerId, challenge, response);
        if (customer == null) {
            FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(
                        "Username and/or password is incorrect or your account has been disabled"));
            return null;
        } else {
            return "/pages/homepage.xhtml?faces-redirect=true";
        }
    }
}
</pre>
<p>Don&#8217;t mind the annotations, they come from CDI (<a href="http://jcp.org/en/jsr/detail?id=330">JSR-330</a> a.k.a. <a href="http://openwebbeans.apache.org/">Contexts and Dependency Injection</a>). The only thing to remember from these is that this class is a Session scoped managed bean which gets a LoginService injected. Note that I would also prefer ViewScoped, instead of SessionScoped.</p>
<p>Also, don&#8217;t mind the return values in loginUsingTokenGenerator. This is also a new feature in JSF 2.0, called Implicit Navigation.</p>
<p>Note the generateChallenge() method. The throws clause is not mandatory. The argument type must be ComponentSystemEvent though.</p>
<p><b>Wrapping up</b><br />
As you can see, System events and the &lt;f:event /&gt; tag provide a convenient way to hook in custom logic on a per-component basis.</p>
<p>And, because we&#8217;re back to normal OO programming, instead of getter hacking, unit testing the LoginBean is easy as pie!</p>
<p>Pretty neat huh?! <img src='http://blog.smart-java.nl/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/24/jsf-2-0-maximum-flexibility-with-system-events/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>java.util.Calendar.getActualMaximum returns strange results</title>
		<link>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/</link>
		<comments>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 15:55:15 +0000</pubDate>
		<dc:creator>Peter Schuler</dc:creator>
				<category><![CDATA[Java API]]></category>
		<category><![CDATA[Java language]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Calendar]]></category>

		<guid isPermaLink="false">http://blog.smart-java.nl/blog/?p=643</guid>
		<description><![CDATA[At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.
I will therefore share it with you.
The code
Let&#8217;s first look a some code dealing with getting the last day of the [...]]]></description>
			<content:encoded><![CDATA[<p>At the end of last year I encountered something odd in the java.util.Calendar. Now is odd behavior nothing to be surprised of in the Java Calendar but this particular oddness was really hard to spot.</p>
<p>I will therefore share it with you.</p>
<p><strong>The code</strong></p>
<p>Let&#8217;s first look a some code dealing with getting the last day of the month:</p>
<pre class="brush:java">public class CalendarTest {
  public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    int maxDayOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);

    System.out.println("last day of month = " + maxDayOfMonth);
  }
}</pre>
<p>Please read the java doc for <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getActualMaximum(int)">Calendar.getActualMaximum()</a>:</p>
<blockquote><p>Returns the maximum value that the specified calendar field could have, given the time value of this Calendar. For example, the actual maximum value of the MONTH field is 12 in some years, and 13 in other years in the Hebrew calendar system.</p></blockquote>
<p>So the code above can print two different values right &#8230;? 28 or 29 depending on the whether this year is a leap year. As you could have guessed that is another unexpected possibility. I can also print 31. Yes&#8230; really.</p>
<p>I all depends on the date on which this code is executed.</p>
<p>The problem is that Calendar.getInstance() will return a Calendar filled with the current date/time. Let&#8217;s assume the above code runs on the last day of January. The call to getInstance() will return 31-01-2009. The next step puts the month to February. This will result in a overflow as 31-02-2009 is invalid. Because of this Calendar will move the date to 3-03-2000. And March has 31 days.</p>
<p>There is a <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4452473">bug report (status: Closed, Not a Defect</a>) in the SDN which told me that the observed behavior was correct. I was not the <a href="http://forums.sun.com/thread.jspa?threadID=5422080">first</a> person surprised by this and I&#8217;m guessing I will not be the last.</p>
<p>I was &#8230;</p>
<ol>
<li>&#8230; lucky I wrote a decent unit test.</li>
<li>&#8230; lucky to be running said unit test om 31 December.</li>
<li>&#8230; unlucky for having to work on the last day of the year.</li>
</ol>
<p>Otherwise the bug I created would properly have slipped through the QA cycles and would have ended up in production. There it would only be visible on the last three days of every month if someone would specify a date in February.</p>
<p><strong>What about lenient?</strong><br />
The Calendar.setLenient function does protect against invalid input. Let&#8217;s quote the the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#setLenient(boolean)">Calendar java doc</a> about Leniency:</p>
<blockquote><p><strong>Leniency</strong><br />
Calendar has two modes for interpreting the calendar fields, lenient and non-lenient. When a Calendar is in lenient mode, it accepts a wider range of calendar field values than it produces. When a Calendar recomputes calendar field values for return by get(), all of the calendar fields are normalized. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1.</p>
<p>When a Calendar is in non-lenient mode, it throws an exception if there is any inconsistency in its calendar fields. For example, a GregorianCalendar always produces DAY_OF_MONTH values between 1 and the length of the month. A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.</p></blockquote>
<p>So lenient does protect against the programmer/user creating a invalid date in a way that the following code will result in an exception:</p>
<pre class="brush:java">    Calendar c = Calendar.getInstance();
    c.setLenient(false);
    c.set(Calendar.MONTH, Calendar.FEBRUARY);
    c.set(Calendar.DAY_OF_MONTH, 31);
    System.out.println(c.getTime());</pre>
<p>But the exception is only thrown when c.getTime() is called. Calls to getActualMaximum() still work and return 31. So lenient is not useful here.</p>
<p><strong>Lessons learned</strong></p>
<p>The quick fix for this problem is to set the DAY_OF_MONTH to 1 (or any number between 1 and 28) <strong>before</strong> setting the month.</p>
<p>I also learned that Calendar.setLenient() will not protect you from this error. It will only stop you from getting an invalid Date. It does not protect against overflows.</p>
<p><strong>Sould I use JODA time?</strong></p>
<p>At the end of this post I have a question for you. I have no experience with JODA time always preferring to use the standard Date/Time API unless there was a problem. But perhaps I should reverse my views and use JODA time unless I&#8217;m not allowed too? What do you think &#8230; is it time to stop  using the default Calendar API and use JODA time instead? Or should I wait for Java 7 with <a href="http://jcp.org/en/jsr/detail?id=310">JSR 310</a>?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.smart-java.nl/blog/index.php/2010/01/20/java-util-calendar-getactualmaximum-returns-strange-results/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
