Alexander Smirnov’s personal Weblog

May 20, 2011

R3 Web Application Pattern

Filed under: Java — alexsmirnov @ 3:46 pm


The most popular pattern for web application development is Mode View Controller. In this pattern, controller processes Request, updates the Model and call View to generate representation. The pattern is pretty simple and powerful, while it has some disadvantages. Take a look for diagram from Wikipedia article:

The solid lines show direct associations, and dashed ones are optional indirect. All three parts of the application are tight coupled: Controller should know Model structure to update values, View depends from the model structure, and once again Controller depends from view; at least for names of input parameters. That’s pure procedural architecture with dumb model. Controller cannot be reused for different models or views, even different request methods require different procedures in the Controller. So, the goal of proposed pattern is to reduce dependencies between parts of application, and use the power of Object Oriented programming languages.

W3C Architecture

From the “Architecture of the World Wide Web”, each  URI identifies one resource. Resource itself associated with some object. When agent request URI for some resource, it gets back Resource representation. A representation is data that encodes information about resource state. As you can see, it doesn’t complete match MVC pattern.

Resolver, Resource, Representation

The proposed Resolver, Resource, Representation pattern ( R3 ) follows W3C architecture and better fit Object Oriented Architecture.

  • Resolver processes URI from client request and returns Resource instance associated with request URI ; this is called dereferencing the URI.
  • Resource is the programming Object instance, that represent some concept. It contains data fields and methods. Requests that modify resource change its attributes or call methods on Resource Object . Resource can have relations to others. These relations represented as links to URI’s associated with these resources.
  • Each resource has one or more Representations, that converts Resource object into web data.
  • Additional parts of application include mapping between request data and Resource methods / attributes and Representation controller that decides how to show resource for client.

In this architecture Controller becomes URI Resolver decoupled from the both Model and View internals, dumb Model evolves into rich Resource Object with data and methods. In comparison with MVC, only one tight coupling between Resource and View remains.
It’s also fit full REST architecture recommendations. Instances of application Model objects becomes Web URI’s, relationships between them can be represented as links, and object methods mapped to the request methods and data, and Representations can be selected from content negotiation.
Programming Application flow also can be pretty easy: Resource method can return the next object, that becomes a new application state either for the current request or as redirect to URI associated with new state.


May 18, 2011

Neo4j Java EE connector

Filed under: Uncategorized — alexsmirnov @ 12:28 pm

Recently, I needed to add ‘graph relations’ to the data objects in the some JEE application. That application uses JPA and MySQL to store data objects, and first attempt was done by adding “many-to-many” relationships that points back to entity itself, but such schema doesnt work well in SQL. Therefore, we decided to keep graph-like relationships in the Neo4j database.

The next question was: how to add Neo4j to our application and how to coordinate transactions between JPA and Neo4j ? Because we run inside Glassfish 3.1 container, we put graph database outside of application and created Java EE connector neo4j-connector that deployed to server as resource adaptor and manages Neo4j database. Application get instance of GraphDatabaseService from JNDI and doesn’t have to care about database startup/shutdown, configuration, and transactions.

Connector features:

  • Standard JCA 1.6 connector, that can be installed on any Java EE 6 compatible server. For the oldest servers, It’s pretty easy to convert connector to JCA 1.5 API.
  • ResourceAdapter starts Neoj4 database at first request and shutdown it with server.
  • Supports both LocalTransaction and XA transaction. XA support may be not quite correct – instead of using proper XAResource from adapter, it provides access to platform TransactionManager for Neo4j server. Diving into Neo4j internals, I’ve found that it creates couple of XAResource objects and enlists them in the Transaction, while ResourceAdaptor lets to create only one XAResource. Finally, I creater Provider for JEE Server TransactionManager, similar to the Spring Data project.


  1. Check out source code from the Github neo4j-connector project and build it with Maven. Project uses some artifacts from the Jboss Maven repository, so you have to configure it before build.
  2. Deploy connector to your application server. For Glassfish 3, there is shell script that deploys resource adapter and configures connector. All what you need is having asadmin application in the path or GLASSFISH_HOME environment variable. The connector supports two configuration options: dir for the Neo4j database location and boolean “xa” property that switches adapter from Local to XA transactions.
  3. Add neo4j-connector-api library to comple your application. JCA classes loaded in the parent Classloader on the server, you don’t need neo4j classes at runtime. For maven, just add dependency to ejb or war project:

There you go – Neo4j GraphDatabaseService now available as JNDI resource!

 Neo4JConnectionFactory neo4jConnectionFactory;

 GraphDatabaseService createDatabaseService() throws ResourceException{
 return neo4jConnectionFactory.getConnection();

In the EJB services, you don’t have to start/stop transactions by hand, it will be done by container if you set apporpriate @TransactionAttribute for EJB/business method.
In the XA mode, you can use JPA/SQL and Neo4j together, and container will take care for data consistency ( of course, database connection also have to use XADataSource ).

Future plans

  1. Add database configuration parameters to adapter.
  2. Support Neo4j High Availability cluster in the adaptor. I plan to start and configure all necessary services directly in the adapter, using Application Server cluster service where possible. Therefore, JEE application can be scaled without any changes in the code, as it supposed for JEE.
  3. Provide JPA style Object to Graph mapping, most likely as the CDI extension.

April 8, 2011

RichFaces CDK: How To Create JSF Renderer

Filed under: Uncategorized — alexsmirnov @ 1:44 pm

JSF Renderer

JSF Renderer responsible for two functions, rendering component as HTML markup and processing request attributes. While processing attributes in the code usually is simple, generating markup in the Java code may be cumbersome for big components. Just by human mind nature, it would be hard to imagine how calls to ResponseWrited converted to HTML, and then imagine the second transformation, from html and CSS to visual representation.
Also, each element and attribute require five times more characters when generated string itself, that makes renderer code much bigger when original design.
JSF 2.0 offers “composite components” for code reuse, but native component developer still have to write dosens of startElement/writeAttribute/writeText/endElement calls.
RichFaces CDK closes a gap between component html design and Java code. It lets developer to create xhtml template, similar to the composite component and converts that template to Java code. That templates reuses JSF 2 composite component syntax where possible, what lets developers to prototype component as composite and convert it into native for production, with better performance and extended functionality/

Renderer Template

Base structure

Same as JSF composite component, Renderer template is well-formed XML file. The main difference that CDK template should have document element <root> from the cdk namespace “;. To allow XML validation for non-standard html attributes, the default namespace should be “;, associated with CDK xml schema. The full list of template schemes described in the table below:

Namespace URI Schema location Description; HTML 4.0.1 with CDK extensions.; CDK template document; CDK version of JSTL tags; CDK version of JSF 2 composite component tags; Extensions for html attributes to process component pass-throuth attributes

Same as for JSF composite component, CDK contains two main sections: interface with meta information necessary to generate Renderer and implementation with HTML markup.

<composite:interface> Element

Interface section supports <composite:attribute> elements from the JSF composite component, with children <composite:clientBehavior>. The syntax is same as for composite component, while meaning is different: These elements define renderer-specific component attributes. If rendered-specific component generated by CDK, these attributes will be added to the component, and generated code will use getter and setter methods for them instead of attributes Map.
In addition, there are CDK-specific elements used by CDK only:

  • <cdk:class>, the content of that element should be full-qualified Java class name for generated renderer. By default, CDK infer name for generated class by naming conventions.
  • <cdk:superclass>, the content of that element should be full-qualified Java class name for generated Renderer superclass. That class should extend javax.faces.render.Renderer, and can be used to put decode logic and helper methods. By default, renderer extends javax.faces.render.Renderer class.
  • <cdk:component-family>, the content of that element should contain JSF component family ID, used to associate renderer with component. By default, that walue calculated by naming conventions or taken from UIComponent class annotation that contains renderer attribute referrenced to this template.
  • <cdk:renderer-type>, the content of that element contains JSF Renderer type assigned to the generated renderer. Same as for component family, its value can be inferred or taken from UIComponent.
  • <cdk:renderkit-id> defines JSF render kit for which generated rendered belongs to. By default, it’s JSF HTML_BASIC render kit.
  • <cdk:renders-children>, its content contains logical value ( true or false ) that should be returned from getRendersChildren method. By default, CDK doesn’t override that method from superclass.
  • <cdk:import> defines additional Java import directives for generated class. Attributes:
    • package – fully qualified Java package name
    • names – short names for imported classes, comma-separated list
    • static – tells CDK to generate “import static” directive
  • <cdk:import-attributes> allows CDK to import attributes definition from faces-config fragment, same as used by the @JsfComponent#attributes . The ‘src’ attributes should contain URL for that fragment.
  • <cdk:resource-dependency> defines JSF resource used by the component. Resource defined by that element added to @ResourceDependencies annotation for generated type. Attributes:
    • name – defines resource name.
    • library – optional, defines resource library name
    • target – optional, forces resource to be rendered in html head, body, or form element.


While <interface> section defines meta-information, most of the Renderer code generated from the content of <implementation> element. Html content of that element converted to calls of startElement/writeAttribute/endElement ResponseWriter methods.

Encoding children components

JSF Renderer has three methods that participate in encoding process: encodeBegin, encodeChildern and encodeEnd. For components that do not contain children elements ( input field, for example ), it’s better to perform encoding in the single method, usually encodeEnd. If component children encoded in the natural order, developer can left default encodeChildren functionality and render component prolog in the encodeBegin() and finish it in the encodeEnd. For components that can change rendering sequence of its children, rendering of content usually performed in the encodeChildren mathod, with rendersChildren method returns true ( see <cdk:renders-children> element above ).
To define methods used for encoding, developer can put <cdk:body> element. Everything before that element going to the encodeBegin method, and rest of the <composite:implementation> content after <cdk:body> going to the encodeEnd. If this element is empty, no encodeChildren method generated unless ‘enforce’ attribute set to true, so encoding of children components performing by default in superclass. Otherwise, content of <cdk:body> generated inside encodeChildren method.


CDK evaluates Expression Language statements into Java code. It supports Expression Language 2.2 syntax, and recognises their argument types where possible. Because expressions generates as the Java code, the type checking is more strict when it allowed in the dynamic interpreter. For example it impossible to access to unknown method or field if argument recognized as Object.
EL-expressions allowed in text, html attributes, and flow control directives. CDK does not recognise EL-expressions as HTML element names yet.
To call method that returns void, use <cdk:call> element, with call expression provided in element body or by the ‘expression’ attribute.

Flow control

CDK supports JSTL-like directives to control rendering:

  • <c:if> element used to generate Java if() statements. Content of the ‘test’ attribute used to generate condition expression, usually from EL-expression.
  • <c:choose> with <c:when> and <c:otherwise> children elements used to chain Java if() …else if() … else statements. ‘test’ attribute of each <c:when> element used to generate conditions, and content of the <c:otherwise> going to the final else {} block.
  • <c:forEach> used for iterations over collections. Its ‘items’ attribute should be evaluated to Java Collection or array ( Iterator/Enumeration not supported yet ), and variable defined by ‘var’ attribute can be used in EL-expressions inside iteration.

In addition, there is <cdk:switch> with <cdk:case> and <cdk:default> elements using to construct Java ‘switch’ directives. The ‘key’ attribute used to define switch() condition, and ‘values’ attribute from <cdk:case> used to generate case … : statement condition. Of course, these expression should be evaluated to types which valid for Java switch/case statement.


CDK can assign computation results to variables, which can be used in EL-expressions. Predefined variable names are:

  • component – the UIComponent used to call Renderer#encode…() method.
  • facesContext – the current FacesContext instance.
  • clientId – client id of component used to call Rendered method.
  • responseWriter – instance of JSF ResponceWriter used to write Renderer output.

Developer can define his own variables using <cdk:object> element. The variable name defined by the ‘name’ attribute, and value evaluated from the ‘value’ attribute or element body.
The scope of object is the current Java block, hence objects defined in the different parts sepatated by the <cdk:body> statement are not visible in another parts because they are going in different methods. Also, variables defined inside flow control elements are not visible outside of element.


In the typical component, most HTML attributes generated from the component attributes. There are two cases for each attribute:

  1. Attribute value generated as the String.
  2. Pass throw attribute, which content comes from the component attribute, with optional behavior-generated event handlers.

For the first case, developer can provide attribute value as literal or EL-expression. CDK recognises HTML 4 schema ( no HTML5 schema implemented yet ) and properly render URL and boolean values.
In the second case, use attributes from the CDK extensions namespace. Each html attribute has its ‘extension’ version. For these attributes, cdk threat attribute value as the name of the component attribute from which attribute value comes. If component attribute was not set, no html attribute will be rendered. For attributes with associated ClientBehavior events component renders scripts from all behaviors for that event.
To reduce the number of code in component template, there are three attributes for bulk operations:

  • cdk:passThroughWithExclusions, that renders all attributes allowed for html element except ones defined in attribute value ( space separated list ). CDK expect that component attribute name the same as for html. That’s useful to render single-element components or for the root element.
  • cdk:passThrough renders all attributes defined in its value ( space-separated list ). If component and html attributes have the same name, it typed as is. Otherwise, developer can provide component attribute name separated by colon, for example: <cdk:passThrough=” style class:styleClass”, what means render component ‘style’ attribute as html style, and component#styleClass as HTML class.


April 6, 2011

RichFaces CDK – how to create JSF component

Filed under: Java, Java server faces — alexsmirnov @ 3:48 pm
JSF component if pretty complicated beast. In the worst case, you have to create UIComponent class, with a lot of attributes with special getter’s and setters that interacts with StateHelper,  renderer-specific class that contains similar attributes for html-related parameters ( even worse, they require special code if you wish to use attributes access optimization in Renderer ) and defines JSF Behavior events for them, create Renderer class that generates html code using spaghetti of startElement/writeAttribute/writeText/endElement calls, describe these classes in the faces-config.xml, create Facelets taglib.xml to define component as VDL tag, write TagHandler class. If your component fires FacesEvents for some listeners, you also need Listener interface and listener TagHandler with default ListenerWrapper.
Similar work required for the ClientBehavior, except renderer-specific implementation.
Faces Converters and Validators a little bit simple because they don’t require separate renderers and cannot broadcast events.
RichFaces uses special Component Development Kit ( CDK ) that takes rid for most of these tasks and lets developers to concentrate on component functionality only.
In the best case, developer has to only create abstract component class, with functional code only, and Renderer template that describes generated Html with Facelets-like syntax. Everything else generated by the tool.

Define Java Package as Components Library

By default, all components in the same projects included to the same library. Developer can provide package-level annotation to define library for all components which belong to that package
package org.richfaces.cdk.test.component;
import org.richfaces.cdk.annotations.TagLibrary;

Abstract Component Class

Most JSF components contains only a few lines of functional code. With cdk, developer can only create java class with such functionality and lets boilerplate to be generated.

Base Class

The base class can be abstract if it need references to generated methods. That class should be annotated with @JsfComponent annotation that describes generation details:
@JsfComponent(type = “foo.Bar”,
description=@Description(displayName=”Bar Component”,
description=@Description(“Caption Facet”)),
interfaces=Ext.class,         tag=@Tag(name=”abbr”,generate=true,handler=”foo.facelets.barHandler”),
public abstract class AbstractBarComponent extends UIComponentBase

For type-safe definition, optional annotations defined as @JsfComponent attributes, so Java compoler can check their usage and code competition available in modern editors. All annotation attributes are optional and can be inferred by CDK:

  • type() defines JSF component type, used as key when framework creates component instance. Its value can be also defined by public constant COMPONENT_TYPE or inferred from the class name by Naming Conventions#.
  • family() defines component family, common for the group of similar components ( for example, UICommand, HtmlCommandButton and HtmlCommandLink all share “javax.faces.Command” family ).
  • description() defines optional description of component, used by JSF tools and documentation generator. Full description comes from the class JavaDoc comment or can be defined by value() attribute.
  • generate() defines the fully qualified name for concrete component class. There are two options for default value of that attribute. If @JsfAnnotation applied to the abstract class, the name of generated class will be inferred from Naming Conventions. Otherwise, if annotated class is concrete, CDK will not generate concrete component class and use annotated class as component implementation.
  • facets()  defines component facets. It’s array of @Facet annotations. Facet#generate() attribute tells CDK to generate getter and setter for facet.
  • fires() is array of @Event annotations which define JSF events fired by components. It defines FacesEvent class for event, listener and source interface. For each event, CDK generates add/remove/get<Event>Listener methods defined by the source interface, creates eventListener tag handler and creates listener instance that can be binded to EL-expression.
  • tag() is array of @Tag annotations. Using multiply tags for single component is necessary to define tags for different VDL ( View Description Language ), or make aliases. Tag links JSF component and its renderer. If no tag defined for component, but there is Renderer associated with component, Facelets tag will be generated. Tag name, handler class and library will be inferred.
  • attributes() contains array of strings, each contains the name of faces-config.xml fragment with attributes definitions, that lets CDK to reuse attributes definition in different components. CDK looks for these files in project classpath META-INF/cdk/attributes folder, and provides set of such files for the most html elements and standard components.
  • renderer() associates component with Renderer implementation. There are two options to link component with renderer#: by the renderer type or by the template name. For type, CDK doesn’t check existence of the target renderer, because it would be defined in another module. For template name, CDK enforces both renderer and component to share the same renderer type and family.
  • interfaces() attribute contains array of Java interface classes that should be implemented by generated component, that provides another way to reuse attributes definitions in different components, similar to ‘attributes()’ option. That’s preferred method for user attributes, because it allows type-safe check. The result is the same as including these interfaces in ‘implements’ keyword for component class, but it does not enforce component class to be abstract, and can be used to define interfaces implemented by the renderer-specific components ( see late ).

Renderer Specific Components

In JSF, the single component can have more then one renderer, to allow different client-side representations of the same functionality. For example, base command UICommand component can be rendered as html button ( <input> element ) or link ( <a> element ). Because these representations can have different attributes and ClientBehavior events, JSR best practices recomment to have renderer-specific component that contains bean attributes for specific implementation. CDK follows that structure and lets developer to define renderer-specific components in the base class using @JsfComponent#components() attribute.
This attribute contains array of @RendererSpecificComponents annotations which have the same set of attributes as @JsfComponent, except the family() that should be shared by all components. These annotations lets to define third level of generated classes, specific to the particular renderer.

Define Attributes

JSF component attributes not are plain bean getters and setters, they can contains code to evaluate EL-expressions, and to persist value in the View state. Also, some attributes can be associated with ClientBehavior events. CDK generates all code to make attributes compatible with JSF spec.
To define component attribute, developer can annotate class field or getter method with @Attribute annotation. The method can be abstract, that allows to use that annotation in the interfaces or abstract classes:
signature = @Signature(parameters = {String.class},
returnType = Boolean.class))
public abstract MethodExpression getMethodExpression();
Same as for the @JsfComponent, all annotation attributes are optional.

  • aliases() lets to define different names for the single attribute. In the example above, CDK will generate public MethodExpression getAction(){ return getMethodExpression();}
  • defaultValue() should contain valid Java expression evaluated to the default attribute value.
  • description() contains attribute description for IDE and documentation, the same annotation used elsewhere in CDK. By default, CDK uses method JavaDoc comment to generate description.
  • events() contains array of ClientBehavior events definition. The value of EventName annotation is name itself, and defaultEvent defines marks event as component default#.
  • hidden() attribute tells CDK to remove attribute from tag.
  • literal() disables EL- expressions for attribute.
  • passThrough() defines attribute to be rendered as html attribute without conversion. Attributes with ClientBehavior events always threated as passed through.
  • readOnly disables generation for the setter method.
  • requires() enforces tag handler to check what developer provided explicit value for that attribute.
  • geterate() enforces CDK to generate getter and setter methods for attribute, even if concrete method already exist. If omitted, CDK checks ‘abstract’ modifier for getter and setter methods and generate implementation for abstract methods only.
  • suggestedValue can be used in tools for code competition.
  • signature() only used for attributes with MethodExpression type to define signature of the target method.

Define Facets

Component facets can be defined in the two ways: in the facets() attribute of component annotations ( described above ) or by the getter method @Facet annotation:
public abstract UIComponent getHeader();
The ‘name()’ attribute is optional in this case, CDK uses bean attribute name instead. Same as for the attribute, it uses JavaDoc comment to generate description and generate implementation for abstract methods.

March 25, 2011

Maven deployer plugin for Glassfish 3.1 and Jboss

Filed under: Glassfish, Uncategorized — alexsmirnov @ 4:46 pm

Plugin features

Encouraged by the Jason Lee articles about Glassfish REST API, I added support for that API to the plugin that I use to deploy my projects, and published the code to GitHub. That’s forked from the original Maven Jboss Plugin far ago, and modified to meet my needs:

  • Find module, most suitable for deployment, in the multi-module projects. For the ‘pom’ packaging, plugin checks all dependent modules and deploys artifact with this precedence: EAR, WAR, EJB, SAR. That lets to build and deploy project to the target server in the single command: mvn package deploy.
  • Jboss downloads archives for deployment from network by http protocol. Therefore, when you deploy application to remote server, it’s necessary to put the public address of developer machine in JMX call. Plugin tries to resolve public IP for remote deployment, or can get it from configuration.
  • Added workaround for Jboss 5 bug that crashes in attempt to deploy file from url with http: protocol.
  • https: protocol added, to deploy on secured console.
  • And, at the last, it also supports Glassfish REST api with same features.


         <!-- configuration options -->

Define target server

By default, plugin deploys artifact using http://localhost:4848/ URL for management application.

To define another server, use these configuration options:

  • <targetHost> – hostname or IP address of target server.
  • <targetPort> – http port where management application listening, if it different from default 4848.
  • <secure> – if you use https protocol ( enabled by asadmin enable-secure-console command ).


By default, plugin connected to the target server as user ‘admin’ with empty password what’s Glassfish default. There are several options to define user name and password:

  1. Using <server> element in Maven settings.xml. You can create that element with the same ID as target host name, or tell plugin which id to use by <serverId> option.
  2. Define them in configuration by <username> and <password> element – not recommended for remote deployment because they visible for anyone who have acces tou your project code.
  3. use command line options -Dusername=… and -Dpassword=…

Define deployment file

For the projects with packaging ‘jar’ ‘war’ ‘ear’ ‘sar’ plugin deploys the main project artifact with the same application name as artifactId. For packaging ‘pom’, it tries to find most suitable artifact in project modules:

  1. If some module has ‘ear’ packaging, use it.
  2. Otherwise, try to find ‘war’ module.
  3. if no ‘ear’ or ‘war’ modules found, try to find ‘ejb’ or ‘sar’ modules.
  4. Otherwise, use the last module with packaging ‘jar’

The plugin has ‘aggregator’ flag in its configuration that enforces Maven to build dependent modules first. Therefore, whole project can be built and deployed by the single command:

mvn package deployer:deploy-glassfish

either from the command line, IDE or on the continuous integration server. I really use it to deploy my project to Glassfish running on Amazon EC2 cloud instance. Nirvana…

If default behavior not suitable, it can be overrided by configuration or command line options:

  • <deploymentFile>, -DdeploymentFile – path to archive to be deployed.
  • <name> -Dname – application name.
  • <contextRoot>, -DcontextRoot – web application context path.

Testing client-side part of JSF applications with HtmlUnit

Filed under: Java, Java server faces — alexsmirnov @ 3:54 pm

There are couple tools that can be used to test generated html and client-side scripts. The most accurate tools are  these that run test in the real browser ( for example, Selenium framework ), but, in the some cases, they cannot be used – machine that runs tests has to have GUI ( rare available on continuous integration servers ), preconfigured instances of target browsers, and these tests can take too much time because you have to start new browser instance for each test to eliminate dependencies between them.

Another option is client emulator, that only simulates target browser. Although it’s less accurate then the real browser, the advantages are: no additional software required, it runs faster, and test code has full control on test client configuration. For developer tests in RichFaces, we use HtmlUnit library, integrated with our embedded FacesEnvironment.



HtmlUnit teste require these dependencies :
Test Project
+- org.jboss.test-jsf:jsf-test-stage
+- org.jboss.test-jsf:jsf-test-jetty ( optional )
+- org.jboss.test-jsf:htmlunit-client
+- javax.servlet:servlet-api
+- javax.servlet.jsp:jsp-api
+- javax.el:el-api
+- javax.servlet:jstl
+- junit:junit
+- com.sun.faces:jsf-api
\- com.sun.faces:jsf-impl ( or any other you want to test with ).
htmlunit-client does not contain dependencies for servlet or JSF because it can be used with different versions and implementations.


HtmlUnitEnvironment combines embedded JSF environment and HtmlUnit client designed to work with it. Test example:
public class FacesTest {
 private HtmlUnitEnvironment environment;
 public void setUp() throws Exception {
 this.environment = new HtmlUnitEnvironment();
 public void tearDown() throws Exception {
In this test, the new instance of HtmlUnitEnvironment created  before each test, configured with virtual web application from package ‘org/jboss/test’ content and initialized to serve requests. The tearDown() method stops environment after each test and releases its resources.

Using in tests

The simple test gets JSF page, fills input field with new value and submits form to server.
After submit, it verifies that input element set new value to the session-scope bean ant that value was rendered back by outputText component:
 public void testHelloFacelets() throws Exception {
 HtmlPage page = environment.getPage("/hello.jsf");
 HtmlForm htmlForm = page.getFormByName("helloForm");
 HtmlInput input = htmlForm.getInputByName("helloForm:username");
 HtmlElement submitElement = page.getElementById("helloForm:submit");
 HtmlPage responsePage =;
 HttpSession session = environment.getServer().getSession(false);
 HelloBean bean = (HelloBean) session.getAttribute("HelloBean");
 assertEquals("foo", bean.getName());
 Element span = responsePage.getElementById("responseform:userLabel");
 assertEquals("foo", span.getTextContent().trim());


In Junit 4.x, MethodRule version of environment can be used instead of setup/release it in code. This example does the same as one with @Before/@After methods:
public class FacesTest {
 public HtmlUnitRule environment= HtmlUnitRule.create().withWebRoot("org/jboss/test/hello.xhtml");

March 24, 2011

RichFaces JavaScript service

Filed under: Java, Java server faces — alexsmirnov @ 3:22 pm


In the modern Web interface development, inline event handlers considered as the bad practice – see article for detail.
Also, for performance reason, Web experts ( Yahoo  YSlow, Google  Page Speed and others ) recomend to load  plain html code first, and only add user interaction code at the bottom of page.
For the same reason, all JavaScript files has better to be loaded at the bottom of page too.
jQuery library makes that stile pretty easy, using $(page).ready() or just $() callbacks. But, there is a problem with JSF AJAX: jQuery knows nothing about JSF library, and code inside page.ready handler will nether be called after page update.
Another drawback for JavaScript dependencies comes from the JSF 2 component resources which cannot be changed from per-component dependencies ( useful for development stage ) to solid compact library or external CDN refferences.
RichFaces JavaScript service designed to solve problems above.

How it works

RichFaces provides JavaScriptService object ( available via ServiceTracker )  to render JavaScript defeered JavaScript code at the bottom of the page or inside jQuery page.ready handler.
Getting service instance:
JavaScriptService javaScriptService = ServiceTracker.getService(JavaScriptService.class);

The service instance created by RichFaces initialization listener, and can be replaced by different implementation by custom Module, see documentation for ServiceTracker.
Adding script to be rendered at the bottom of page:
javaScriptService.addScript(facesContext, script);

What does this method do ? It looking for special UIScripts component in the UIViewRoot.componentResources collection, or creates new if there to such component yet, and append script object to the Set of objects submitted to be rendered. To avoid rendering of the same script more then once, it checks collection for the same script ( using equals() method ). If the same object already submitted to be rendered, it returns existing object. Otherwise, new script added to the collection and returned by method. That check allows to render the same script only once, even if component that requires such code rendered many times.
For example, component that wraps jQuery widget can use special ‘class’ attribute to mark its instance on the page, and the same script can activate all widgets using that class as discriminator.
Another method lets developer to append script that will be rendered inside page.ready handler:
javaScriptService.addPageReadyScript(facesContext, script);

The only difference with addScript() method that scripts appended into separate collection that processed in the special way. UIScript component writes them inside such JavaScript code:
<script type=”text/javascript>

$(document).ready(function() {

content of the scripts collection goes here



See jQuery documentation for ready() function for details how it works.
For AJAX requests ( important note – only RichFaces AjaxBehavior supported ) the same scripts rendered in the <execute> part of response that processed after DOM updates. Therefore, the same code works for both page rendering and AJAX modes.
In addition, script object can implement org.richfaces.resource.ResourceLibrary interface and provide additional dependencies. These dependencies will be rendered as links to external resources before in-content <script> element.


Test JSF applications with staging server.

Filed under: Java, Java server faces — alexsmirnov @ 3:18 pm

Test JSF Applications with Embedded Server


JSF is very complicated framework, with a lot of tight related components, that makes testing pretty complicated. It runs inside Servlet container, and framework behavior depends from container configuration. The goal of embedded servlet container is providing flexible test environment suitable to test parts of JSF application: Composite components, view fragments and templates. The idea is very similar to Jboss Arquilian framework, with some JSF-specific extensions. The main answer to the question why to not use Arquillian to test RichFaces components is what it was introduced far before  Jboss implementation. Another answer is JSF-specific features and speed, embedded stage server runs much faster real implementations.


  • Container runs in the same thread that performs client request, what allows test code to inspect request-scope objects, or even interrupt request processing for asserts.
  • Container configuration made from the java code, that lets every test has its own settings and web application content. For example, the same test can be invoked with different initialization parameters.
  • Extremely fast, container doesn’t parese any configuration files, setup network connections or instantiate multiply applications.
  • Single Java object holds container instance, therefore it can be used with any test framework.
  • Integration with HtmlUnit to simulate web client.


  • No JSP compiler, only Facelets views can be used.
  • Ignores web.xml content. Container should be configured from Java code.
  • No network access
  • No JNDI, no injection, only base javax.servlet interfaces.
  • No transactions
  • By default, FacesServlet initialized with suffix-based mapping ‘*.jsf’.


Instantiation of FacesEnvironment

jUnit 4 test class fragment:
private FacesEnvironment environment;
public void setUp() {
environment = FacesEnvironment.createEnvironment().start();
public void thearDown() throws Exception{
This code creates an instance of environment, initializes JSF framework and starts server instance before each test, and releases resources after test. The version of this method with ApplicationServer parameter lets create environment for different server implementation ( currently, embedded Jetty server supported ).


FacesEnvironment class has set of configuration methods to describe web application context and setup server. all methods returns back the same instance, so they can be chained:
withContent(String,String) – define content of web resource for given path:
environment = FacesEnvironment.createEnvironment().withContent(“/test.xhtml”,
“<html xmlns=\”\”\n” +
”      xmlns:ui=\”\”\n” +
”      xmlns:h=\”\”>”+
“<h:form id=\”helloForm\” >”+
”    <h:outputText value=\”foo_bar\” />\n” +
“</h:form>\n” +
withResource(String,String) – put content of classpath resource to the given path in servlet context.
withWebRoot(String) – create virtual web server context from the package containing given resource. Suitable to create web application fragment from resources stored in the jar. Another way to create vitrual servlet context is system property ‘webroot’, that should contain path to the folder with web application content.
withResourcesFromDirectory(String path, URL resource) – Add all resources from the directory to the virtual web application content. Only ‘file’ or ‘jar’ protocols are supported. If this parameter points to a file, it will be converted to a enclosing directory.
withInitParameter(String name, String value) – add ServletContext initialization parameter to value.
withFilter(String name, Filter filter) – add filter in front of FacesServlet.
Additional configuration can be performed directly on the ApplicationServer instance, see JavaDoc for details.

Performing request

To perform JSF request, call environment.createFacesRequest(String url) method:
public void testRequest() throws Exception {
FacesRequest request = environment.createFacesRequest(“http://localhost/test.jsf&#8221;);
String contentAsString = request.getConnection().getContentAsString();
This method gets request URL and returns FacesRequest object, that allows additional configuration ( adding request parameters, cookies, headers ). The request is not active until start() or execute() methods callled. execute() method performs whole request cycle, while start() only initialized request, created FacesContext and returns, that allows test to execute Faces Lifecycle directly inside request context.


FacesRule is jUnit 4 MethodRule that invoked around every test method. It automatically configures and starts converter before method and shut down it after. Using method rule allows to combine with another rules ot test runners – jsf-test MockRunner, Mockito runner, parametrised tests. There is fragment of test that creates mock instances of Jsf beans and run facelets fragment with user registration form, using mock objects for  ‘facade’ and ‘user’ beans:
public class RegisterTest implements ServletRequestListener{

public FacesRule rule = HtmlUnitRule.create().withResource(“/registerTest.xhtml”, “registerTest.xhtml”).withListener(this);
Facade facade;
User user;
public void setUp() throws Exception {
rule.setSessionAttribute(“facade”, facade);
public void requestInitialized(ServletRequestEvent sre) {
sre.getServletRequest().setAttribute(“user”, user);

registerTest.xhtml only includes registration form fragment by <ui:include> directive. Therefore, this test lets check functionality of the single fragment without having real EJB for facade, database, and without inference from other parts of application.

March 23, 2011

JSF Mocks

Filed under: Java, Java server faces — alexsmirnov @ 4:23 pm


In the Test Driven Development mocking real objects is one of fundamental parts. For low-level JSF components and extensions development, having mocking framework environment is necessary for unit testing. Unfortunately, there are some problems:

  1. Most classes from JSF API not interfaces, but abstract and concrete classes. While modern mocking libraries, Mockito, jsf class extensions, and others, allows to mock concrete classes, all of them require some bytecode manipulation library to create mocks at runtime. For example, both Jboss Seam and EasyMock class extensions require different versions of javaassist library.
  2. Libraries like Apache Shale provide stub objects for JSF api, that not so convenient for testing, and none of them had JSF 2.0 version at the Richfaces 4.0 development time.

The idea behind jsf-mock project was similar to Easymock class extension library ( create subclasses for mocked objects that delegate calls to the EasyMock  environment ), but, because we know which classes from JSF API should be wrapped, do it at compilation time and provide ready to use mock objects for tests.

Target environment

Jsf-mock objects can be used with:

  1. both Jsf 1.2 and 2.x, depends only from the jsf-api library used for tests.
  2. EasyMock 2.5.2 and late.
  3. Junit 3.x and 4.x, while we recommend to use Junit 4.8 and later for which we provide runners and method rules that takes care most of configuration jobs.
  4. TestNG.

Mock Generator Maven Plugin

All mock classes generated by the maven-mock-generator-plugin. This plugin intended for internal use to generate jsf-mock library, but can be also used to create mocks for custom JSF components. That plugin generates mock classes for all JSF objects and utility class that instantiates these objects.


The simplest way to create mock objects for JSF is using FacesMock#createMock(Class toMock) method, or similar other from the FacesMock class. These methods have the same signatures and functionality as in the EasyMock class, but, if the class to mock beyond JSF API, it creates an instance of precompiled mock class. Otherwise, call will be delegated to corresponded EasyMock class.

There are some problem with JSF. Sometimes, it may be necessary to use FactoryFinder#findFactory or FacesConstect#getCurrentInstance static methods, that cannot be mocked.


To solve that problem, jsf-mock project contains MockFacesEnvironment class that performs necessary configuration procedures. That class designed to use as internal field in the test class, and can be used with any test framework: Junit 3 and 4, or Testng.

Usage, with Junit 4.8:

private MockFacesEnvironment mockEnvironment;



public void setUp() throws Exception {

this.mockEnvironment = FacesMock.createMockEnvironment();




public void tearDown() throws Exception {

// Necessary to clean up ThreadLocal variable in FacesContext.



MockFacesEnvironment has a set of configuration methods ( having ‘with’ prefix ) that can be chained to describe requested features:


Also, it contains the same set of create…Mock methods as FacesMock class. All mock objects created by environment can be resetted/replayed/verified by single call to environment instance.

Advanced usage, with Junit 4.x

Junit 4 introduced TestRunner feature that allows developer define its own extentions for test environment. Jsf-mock contains MockTestRunner class that simplifies working with mock objects:

  1. For fields in the test class and its superclasses, annotated by @Mock, @Strict, or @Stub annotations, it creates and injects ready to use mock object.
  2. It creates and initializes MockFacesEnvironment object, and injects it into field annotated with @Environment. Developer can describe requested environment features by annotation options. After a test, runner properly releases the environment.
  3. if field with type MockController exists in the test class, it injects controller instance there. That controller can be used to reset/replay/verify all mock objects created by the runner in the single method.

Mocking JSF view

Sometimes, it would be necessary to create not just mock component but fragment of JSF view. For example, to test UIData renderer, table component should contain columne and headers/footers. There is ViewBuilder class to do that:

ViewBuilder viewBuilder = ViewBuilder.createView().children(







Capturing ResponseWriter output

For custom renderers, it would be important to check generated html code. Faces-mocks allows developers to capture renderer output and analyse it with XPath-like criteria:

writer = new RecordingResponseWriter(“UTF-8″,”text/html”);

… call renderer to generate content

// verify output



MockFacesEnvironment creates capturing response writer if it requested by withResponseWriter() call, or Feature.RESPONSE_WRITER option in @Environment annotation.

Maven artifact for jsf-mock project available from Jboss Maven Repository, the source code repository on GitHub is git://

April 12, 2010

RichFaces 3.3.3.Final is out

Filed under: Uncategorized — alexsmirnov @ 3:20 pm

RichFaces 3.3.3.Final is out

RichFaces 3.3.3.Final release was published on Tuesday April 13. I hope it will be the last release for the 3.x version branch, so we can make effort for 4.0 and JSF 2.0 features. Although that release has JSF 2.0 support; it has been designed for backward compatibility only, so developers can run their existing applications on JEE6 containers which shipped with JSF 2.0 out of the box.

The portlet bridge project is also on the way for the final release that should be ready for QA in the end of April. I already changed its dependencies for RichFaces 3.3.3.Final so it will work with the latest stable releases of all involved projects. Besides the JSF 2.0 support, The Jboss Portlet Bridge should be released with its own name “Mobius“. Surely, it’s twisted enough to have that name…

Older Posts »

Create a free website or blog at