Red Hat



In Relation To Ilya Shaikovsky

In Relation To Ilya Shaikovsky

Practical RichFaces second edition is published!

Posted by Ilya Shaikovsky    |    Sep 6, 2011    |    Tagged as

After some waiting time and much promising announcements I can proudly tell that the Practical RichFaces book is published! It’s very happy moment for Max Katz and I because a lot of effort was made to make it happen. We’ve done our best to make it as much useful for JSF developers as possible, and now we believe that it doesn’t matter if you’re a novice in JSF world or skilled developer with rich expertise in various development areas – everyone should find useful parts inside.

The book completely dedicated to development with latest RichFaces 4 release and that means that it's all based on new JavaServer Faces 2. Let me briefly describe what is waiting our readers inside.

Book Content Overview

We start with describing new and most important pieces of JSF 2. It should be useful for future understanding of how the component works, and how the RichFaces extends standard JSF. We will tell not only about brand new features but also highlight most important general points for those who just starting to learn JSF 2. Good understanding of where are the core features and where the extension points should greatly help the developers with further development and troubleshooting of any kind.

Then we continue with RichFaces. Two chapters are dedicated to RichFaces core framework features and tags (a4j:). That knowledge should become a baseline for any developer who is planning to work with RichFaces 4. Because any rich component starting from simplest ones and up to most complex built according to the same basic rules and follows the same approaches that we will describe there. It's simple just to play with JSF creating pages using simple drag and drop operations in your favorite IDE. But only good knowledge of basics will make your future application really extendable and efficient. That was our main point during writing that chapter.

After the core features we will spend most of the time describing various component groups in rich: RichFaces components library. Every component section, in every group provides set of ready-to-use examples starting from very basic (using component on simple page) and to really interesting ones (like custom model for data and tree components, using server and client side components API and customization options and so on). We paid significant attention to making examples as useful as possible by making them as real-life as possible. Most of the complex samples were done according to common Web use-cases, interesting requests from RichFaces community or good questions sent to us directly. So you may think about those chapters as about a good combination of cookbook and reference guide.

A few chapters in the end will describe utility components and functions which are also included in the rich: library. We will tell (also with numerous examples) about new RichFaces validation facilities like client and object validation, components providing drag and drop functionality, and about functions and other utility tags available in RichFaces.

Penultimate chapter will describe redesigned Skins feature of RichFaces 4. Being simplified and optimized Skins become even more powerful than before allowing you add styling to the whole application in a very short time and then perform detailed customization of any depth without using any proprietary formats but relying to standard CSS enhanced with EL support.

Finally, the last chapter will show you the RichFaces Components Development Kit (CDK). Also being fully redesigned in RichFaces 4, it become really easy to use tool which allows you to create JSF 2 components of any complexity in a very short time doing most of routine work for you. This chapter demonstrates how to build a complete example of custom component written from scratch and implemented with all the RichFaces capabilities including skinning.

Full table of content and other information are available at Apress page.
All sources available at Github.

Acknowledgements

After finishing that work on the book and also looking backward to my working experience in RichFaces development I would like to extend a few special thanks to the guys without whom it would not be possible. It’s Alexander Smirnov, Nick Belaevski and Pavel Yaschenko. There were many other great developers working on that project for sure, but these three people were always the core team and great mentors and supporters for anybody who had most complex challenges in JSF world. It’s their ideas implemented now in RichFaces 4 and incorporated in JSF 2. Besides I would like to extend special thanks to Jay Balunas who helped me a lot in establishing myself as a good (as I hope :) ) JBoss community member.

It was (and will be) always easy to move forward together with you guys. So, thank you all!

So, the book is now here, and we are looking forward for your feedback! Hope it will help to make a bunch of good starts for many Java developers.


[Get updates of my blogs in twitter]

[My jroller.com blog]

RichFaces 4 - programmatic control of partial processing

Posted by Ilya Shaikovsky    |    May 26, 2011    |    Tagged as JSF Rich Faces

There is an important feature in RichFaces 4 that get documented at wiki recently and today I want to point you to that article. That article is related to Programmatic control of partial processing in RichFaces 4.

If you working with RichFaces 3.3.x and looking for the same info - do not ignore that page. It's written as comparison of 3.3.x and 4.x functionality so you will see RichFaces 3.3.x methods also!

Questions which are adressed in that article (for both RichFaces 3.3.x and 4.x) listed below. Again all the answers related to programmatical access to PartialViewContext and not just working at component/attributes level.

  • How to add component to set of execute'd ones.
  • How to add component to set of render'ed ones.
  • How to check if current request is Ajax request.
  • How to limit Ajax updates to just set of render'ed components excluding automatically rendered ones.
  • How to append JavaScript event handlers from server side
  • ...more

So look through the article and let RichFaces team know about your experience of using all that stuff. And share your thoughts about anything still missing at User Forum.


[Get updates of my blogs in twitter]

[My jroller.com blog]

Migration to RichFaces 4 - RichFaces Data Models.

Posted by Ilya Shaikovsky    |    May 11, 2011    |    Tagged as

Overview

I believe that this probably one of the most expected articles to come. It will touch the RichFaces iteration component in-depth, covering advanced models which we are using under the hood. Actually real enterprise application using huge data sets, applies paging with lazy data loading, uses sorting, filtering, selection and the other features which makes then application really rich and interactive. So in most cases you could not rely on simple lists or maps with data wrapped using default models. And in order to achieve the best RichFaces tables experience with a good performance and scalability you need to understand the base principles of our models.

Models sample

At first I would like to introduce new sample available on our live demo – Arrangeable Model Sample. It works using Hibernate Entity Manager and all the paging/sorting/filtering operations really performed at DB level instead of performing in wrapped model.

In that article I will guide you through the base points which you should look in that sample in order to get main ideas and be able to work on your own models.

Why do we need the models

Let's start from a good question – why RichFaces introduces custom models having JSF javax.faces.model.DataModel contract already. And the reason is pretty simple. In difference with JSF 2 implementation which is supposed just to provide basic stuff RichFaces introduces new rich components and adds new features on top of them. Here is just overview:

  • Trees components family. With support of swing-based data models and RichFaces custom data models. With additional providers which allows to create data model declaratively from any custom non-hierarchical model. With selection feature plugged and available using different modes (Ajax, client, server)
  • Tables components family. RichFaces unifies sorting/filtering/paging features among two rich tables. It adds the ability of master-detail layouts creation in rich:dataTable with the built-in feature of collapse/expand details subtables. It adds Ajax lazy loading of the data on vertical scroll and selection with rich:extendedDataTable. And so on..

Of course all that stuff requires good model base. And in order to standardize the API between different components providing unified contract to the RichFaces developers we designed our models.

ExtendedDataModel Overview

From the beginning let me introduce our models principles and then later we will see how them are implemented in the showcase demo.

ExtendedDataModel

is a base model abstract class which provides the contract for all the other models particular implementations. Let’s see closer to that class:

public abstract class ExtendedDataModel<E> extends DataModel<E> {

    public abstract void setRowKey(Object key);

    public abstract Object getRowKey();

    public abstract void walk(FacesContext context, DataVisitor visitor, Range range, Object argument);

}

Well, we seeing new entity introduced there. And it’s rowKey. Let’s see the goal of that entity. Working with complex data structures (like trees) and using advanced UI component features like filtering/sorting/paging/selection in tables we need to have a simple way to identify the object in the model. And just rowIndex’es doesn’t play nice enough as requires additional complex look-up mechanisms (to identify db object according to index in wrapped model) to do that. And with the rowKey you could just use the same id which you are using at db level.

Besides you see walk() method introduced there. RichFaces iteration components uses visitor pattern while working with model. So that method should perform model iteration and call the visitor passed as a parameter in order to handle every object in the model.

ExtendedDataModel implementations

  • SequenceDataModel – default implementation of the ExtendedDataModel for the tables. Used when filtering and sorting not used by the component.
  • ArrangeableModel – implementation of the ExtendedDataModel which implements Arrangeable interface additionally which are used to add sorting and filtering support.
  • TreeSequenceKeyModel abstract model and all the models which extends it used by the tree component family. That model is out of scope for that article.

Sample Code

At first I would like to say that will not describe all the code used in the sample. You could easily check it at showcase live or obtain from SVN repository and explore in your favorite IDE. Besides the fact that it will be boring and will make article really huge I also want to say that the goal of that write-up – to guide you in the right direction while reviewing RichFaces data models usage principles.

And overview of that sample functionality:

  • Obtaining the list of Person object s from the db according to given filtering and sorting rules
  • Displaying objects using the rich:dataTable
  • Addition of the controls which control sorting and filtering
  • Addition of the rich:dataScroller which allows breaking the data loading from db to the pages.

Sample Code – Base Person entity

That would be self-explanatory I believe. We just using simple and frequently used classes to define Person object.

@Entity
public class Person {
    
    private String name;
    private String surname;
    private String email;
    @Id
    @GeneratedValue
    private Long id;
//getters and setters
}

Sample Code – Generic Model

Now let’s look closer to the model code.

JPADataModel

–is a generic model which supposed to provide unified approach of working with data for all implementers. It’s parameterized with the class which should be defined to work with particular entity classes in models which will implement it. And besides it passed with the EntityManager in order the implementer classes to be responsible for particular EntityManager lookup.

Also from the beginning you should note abstract getId(T t) method which should be also implemented in the model which implements that abstract model. It should return the id of the particular entity which will be used as rowKey in that model.

Now let’s review two most important methods there. And let’s look to arrange() method from the beginning. It probably too simple to have it listed but any way:

public void arrange(FacesContext context, ArrangeableState state) {
    arrangeableState = state;
}

Just wanted to give some simple explanation of why we perform just simple storing of the passed state in the model property without any further processing. If you will look or already looked to RichFaces sources you will see that default ArrangeableModel implementation of that method performs actual sorting and filtering. But that’s done because our default model works with wrapped model (e.g. simple list or map passed as rich:dataTable value). But in our case we will load the data from db according to current data table page and apply sorting and filtering using db queries also. So we just need to store all the information passed from component in ArrangeableState object for future usage in walk().

Now let’s look to walk() method:

    @Override
    public void walk(FacesContext context, DataVisitor visitor, Range range, Object argument) {
        CriteriaQuery<T> criteriaQuery = createSelectCriteriaQuery();
        TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
        
        SequenceRange sequenceRange = (SequenceRange) range;
        if (sequenceRange.getFirstRow() >= 0 && sequenceRange.getRows() > 0) 
	{
            query.setFirstResult(sequenceRange.getFirstRow());
            query.setMaxResults(sequenceRange.getRows());
        }
        
        List<T> data = query.getResultList();
        for (T t : data) {
            visitor.process(context, getId(t), argument);
        }
    }

The component calls that method a few times during lifecycle and expects it to iterate over the model calling the DataVisitor which will process every object (e.g. encode row for the object at render phase).

Besides visitor, table component passes the Range object there which contains information about from which row the table wants get the data (defined using first attribute or set by rich:dataScroller while switching pages) and the number of rows to fetch (defined using rows attribute). So all we are doing here – just creating query with given sort, filtering and range parameters, loading data from db to the List of entities and finally iterate over that list passing every object to DataVisitor for processing.. You probably will be interested in createSelectCriteriaQuery() method as it performs actual applying of sort and filter parameters. But actually I would like to leave it just to you because JPA queries creation question really out of scope of that article and well explained already at more specific resources.

Besides you may be interested to look into getRowCount() method:

    @Override
    public int getRowCount() {
        CriteriaQuery<Long> criteriaQuery = createCountCriteriaQuery();
        return entityManager.createQuery(
	    criteriaQuery).getSingleResult().intValue();
    }

So there we’re applying sorting and filtering creating the criteria in order to return the rowCount for current component state.

Sample Code – Specific Model Class

The implementation of our generic model placed in PersonBean and defined with the next code:

@ManagedBean
@SessionScoped
public class PersonBean implements Serializable {
    //...
    private static final class PersonDataModel extends JPADataModel<Person> {
        private PersonDataModel(EntityManager entityManager) {
            super(entityManager, Person.class);
        }
        @Override
        protected Object getId(Person t) {
            return t.getId();
        }
    }
    //...
    private EntityManager lookupEntityManager() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        PersistenceService persistenceService = 
	    facesContext.getApplication().
	    evaluateExpressionGet(facesContext, "#{persistenceService}", 
      PersistenceService.class);
        return persistenceService.getEntityManager();
    }

    public Object getDataModel() {
        return new PersonDataModel(lookupEntityManager());
    }
    //...
}

So actually all we are doing there - performing lookup of entity manager and initiating the particular model implementation with the Person class as entity class and that entity manager.

Sample Code – Page Code

We used two pages there. At first arrangeableModel-sample.xhtml:

<h:form id="form">
    <rich:dataTable keepSaved="true" id="richTable" var="record" 
	value="#{personBean.dataModel}" rows="20">
        <ui:include src="jpaColumn.xhtml">
            <ui:param name="bean" value="#{personBean}" />
        	<ui:param name="property" value="name" />
            </ui:include>
            <ui:include src="jpaColumn.xhtml">
        	<ui:param name="bean" value="#{personBean}" />
        	<ui:param name="property" value="surname" />
            </ui:include>
            <ui:include src="jpaColumn.xhtml">
        	<ui:param name="bean" value="#{personBean}" />
        	<ui:param name="property" value="email" />
            </ui:include>
            <f:facet name="footer">
		<rich:dataScroller id="scroller" />
            </f:facet>
    </rich:dataTable>
</h:form>

Nothing pretty interesting there. We just defining table pointed to our model and including the columns passing properties of the person and the bean to it.

And the second is jpaColumn.xhtml:

<ui:composition>
    <rich:column sortBy="#{property}"
	sortOrder="#{bean.sortOrders[property]}" filterValue="#{bean.filterValues[property]}"
	filterExpression="#{property}">
	<f:facet name="header">
            <h:commandLink action="#{bean.toggleSort}">
            	#{bean.sortOrders[property]}	
            	<a4j:ajax render="richTable" />
            	<f:setPropertyActionListener target="#{bean.sortProperty}" 
		    value="#{property}" />
	     </h:commandLink>
	     <br />
	     <h:inputText value="#{bean.filterValues[property]}">
	         <a4j:ajax render="richTable@body scroller" event="keyup" />
	     </h:inputText>
	</f:facet>
	<h:outputText value="#{record[property]}" />
    </rich:column>
</ui:composition>

That’s actually more interesting for us. Most important what you should note there that we passing just Person properties names as sortBy and filterExpression values. Usually you used EL binding to iteration object property and boolean expression in case you using our default models. But that’s not the case for us. As we implementing our model with in-db sorting and filtering – all we need to know just properties names and we will apply the rules in queries like you could see in the model.

Exercises

That sample is still not ideal for sure. Most important you could easily see that there is absolutely no caching. Every time when walk() or getRowCount() called it queries the db with the request for data. You should add it on your own because there is actually no unified recipe for all the situations. Somebody could need just to read the data from db once when filtering sorting or page changes and be sure that it never changes more between requests. In some cases you should consider that data could be inserted/deleted/edited concurrently by different users so the List obtained in walk() method could be changed even between different walk calls and so on. So it’s up to you to define the rules for that. The same applied to rowCount. It’s highly important to cache it also as possible because it’s called also multiple time during request (by both table and data scroller)

Besides you might want to add Weld/Seam in order to be able to tie beans, entities and services in more graceful way.

The result

Even considering all you could open the demo that blog article would be boring without at least single screenshot of the result we achieved. So here is the table after we performed sorting by surname and filtered by emails to obtain only persons with emails in .com domain:

More information

As usually please refer to RichFaces Documentation to get more info from JavaDoc's and references.

Getting started with RichFaces 4.0 Push

Posted by Ilya Shaikovsky    |    Mar 23, 2011    |    Tagged as Rich Faces

Overview

RichFaces Push allows you to perform realtime client side updates triggered via events from the server side. We integrate with the Atmosphere framework which provides various transport mechanisms according to concrete browser support(Comet, HTML5 WebSockets). On the server events are managed by integrating Java Messaging Service (JMS). This provide enterprise level messaging integration all the way to the browser!

In this blog I will describe our irc-client example application that was created to introduce the RichFaces push features. It provides the following functionality:

  • Connect to the freenode.org IRC server
  • Join a channel with choosen nickname
  • Receive all channel messages (nick change, join, part...)
  • Send messages to the channel
  • Observe the list of joined users with real-time updates

In this blog I'm only going to review the important configuration, and source code snippets from the application. The full source code can be checked out from SVN so you can try it for yourself. Instructions for building and deploying the application is in the readme.txt.

Dependencies

To save time with application setup I have created a starter application using richfaces-archetype-simpleapp archetype. Next we need to update application pom.xml to add Atmosphere fremework dependency. For the client side a4j:push uses jquery-atmosphere.js plugin (added implicitly by the component renderer).

NOTE: that particular sample targeted for JBoss 6 Application Server. So we will use JBoss HornetQ available out of the box. Using RichFaces Push under Tomcat or Jetty requires additional JMS dependencies and configuration code. We will work on maven profiles and additional optional classes for that case also in future releases. At the moment the only place to review that configuration is with our developer demo which configured for tomcat using external HornetQ dependencies and configuration class for its initialization.

We need to add the atmosphere-runtime to the pom.xml. This is only needed if you are using the push component.

<dependency>
    <groupId>org.atmosphere</groupId>
    <artifactId>atmosphere-runtime</artifactId>
</dependency>

Also as the demo shown there provides simple IRC client we added one more dependency:

<dependency>
    <groupId>pircbot</groupId>
    <artifactId>pircbot</artifactId>
    <version>1.4.2</version>
</dependency>

PircBot is a simple framework for writing IRC bots.

Configuring JMS

Lets first discuss why we need JMS at all? Why not just use for example push context object? The answer is pretty straightforward. Usage of JMS at the back-end provides excellent integration with EE containers, and advanced messaging services. It also frees you from managing various entities at your business layer. If you are already using JMS for messaging in your application - you will just continue to send the same messages and you just need to to declare a4j:push at views which should listen that topics.

We assume that you're familiar with JMS so will not provide details here. To learn more about it visit JMS documentation.

Now it is time to configure JMS for our example. We will use JBoss 6 AS for application deployment as mentioned in dependencies section. So we'll use JMS server bundled with JBoss AS. We need to create topics which will be used by Push to check for the messages. Let's start JBoss 6 AS and open http://localhost:8080/admin-console. We will use default admin/admin credentials to log-in. Then click the JMS topics in navigation menu and create new JMS topic with the following settings:

Name: chat

JNDI name: /topic/chat All the others: by default.

In the same form we need to add roles for that topic. For that demo application we will create single role with next parameters:

Name: guest

Send: yes

Consume: yes

create subscriber: yes

delete subscriber: yes

create durable subscriber: yes

delete durable subscriber: yes

IMPORTANT: The last two options are critical for push functionality as we using durable subscriptions in order to be able to receive all the events including ones which were sent while the push was not connected to the server. So if they are set to false - push will not be able to register subscribers.

So here is what you should see after JMS setting done:

That's all. Now we are ready with JMS configuration.

NOTE: if you not familiar with JBoss configuration using admin-console visit JBoss AS Administration Console User Guide.

Web Application Configuration

Now let's add application settings required by RichFaces Push. We need an additional filter and a few context-param's to be added. Here is what we used for that demo application:

<context-param>
    <param-name>org.richfaces.push.jms.connectionUsername</param-name>
    <param-value>guest</param-value>
</context-param>
<context-param>
    <param-name>org.richfaces.push.jms.connectionPassword</param-name>
    <param-value>guest</param-value>
</context-param>
<filter>
    <filter-name>PushFilter</filter-name>
    <filter-class>org.richfaces.webapp.PushFilter</filter-class>
    <async-supported>true</async-supported>
</filter>
<filter-mapping>
    <filter-name>PushFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

Let's review those parameters in details. At first we need the PushFilter to be installed and mapped to Faces Servlet. It will handle the push request and serve event using the Atmosphere runtime. And connectionUserName and connectionPassword context parameters are needed in order to defined the credentials used to work with JMS for connecting and subscribing to topics.

Here is the table with all the parameters which could be used in your application:

context-param Name Default value Description
org.richfaces.push.jms.connectionFactory /ConnectionFactory JMS connection factory JNDI name
org.richfaces.push.jms.topicsNamespace /topic used as a root name from which all topics are resolved: i.e. 'chat' topic by default will be looked up via /topics/chat JNDI name.
org.richfaces.push.jms.connectionUsername - Username used for connection and topics creation/listening
org.richfaces.push.jms.connectionPassword - Password used for connection and topics creation/listening

Note: there are also JNDI references to credentials strings available:

  • java:comp/env/org.richfaces.push.jms.connectionUsername
  • java:comp/env/org.richfaces.push.jms.connectionPassword

An alternative to using web.xml definitions is to provide all the parameters using properties file org/richfaces/push.properties.

TopicsContext initialization

Now we need to initialize org.richfaces.application.push.TopicsContext with the JMS topics we will listen for. For this purpose we created a JSF 2 System Event listener which handles PostConstructApplicationEvent:

public class TopicsInitializer implements SystemEventListener {
   public void processEvent(SystemEvent event) throws AbortProcessingException {
       TopicsContext topicsContext = TopicsContext.lookup();
       Topic topic = topicsContext.getOrCreateTopic(new TopicKey("chat"));
       topic.setMessageDataSerializer(DefaultMessageDataSerializer.instance());
       topic.addTopicListener(new SessionTopicListener() {...});
   }
  public boolean isListenerForSource(Object source) {
       return true;
   }
}

and registered it in faces-config:

<application>
    <system-event-listener>
        <system-event-listener-class>org.ircclient.listeners.TopicsInitializer</system-event-listener-class>
        <system-event-class>javax.faces.event.PostConstructApplicationEvent</system-event-class>
    </system-event-listener>
</application>

With this we have created new topic in TopicContext with chat name (the same as we defined configuring the JMS).

Actually MessageDataSerializer and TopicListener creation are optional, so let's briefly describe the main idea of these objects.

  • Messages serializer is used to serialize the message to the expected format for passing to the client. By default built-in serializer will serialize the message data to JavaScript.
  • Session topic listener is used to handle subscriptions (pre and post-processing) and unsubscription events. This could be used for example in order to check user permissions prior to connecting to some topic and perform some additional post-processing after some push component successfully attached to topics. In the sample there are just logging used so the code is omitted there.

Application Code

We are done with settings and push initialization stuff, and it's time to actually explore the example code to see how we manage the IRC connections, and how push is used for page updates according to server-side events.

Logging to IRC

This section is not directly related to Push but describes the code used for connection to IRC. Here is the simple page used:

<rich:panel header="Connect to IRC">
    <h:form>
        <rich:messages style=”color:red”/>
            <h:panelGrid columns="2">
                <h:outputText value="Your nickname:" />
                <h:inputText required="true" id="name" value="#{chatBean.userName}" />
                <h:outputText value="Channel:" />
                <h:outputText value="RichFaces" style="font-weight:bold"/>                        
                <h:outputText value="Server:" />
                <h:outputText value="irc.freenode.org" style="font-weight:bold"/>                
            </h:panelGrid>
        <h:commandButton value="Connect" action="#{chatBean.connect}" />
    </h:form>
</rich:panel>

It's rendered as:

Note that for simplicity purposes the channel and server names are using constants. In the future we plan to extend the sample with ability to open multiple channels and so on..

And here is the ChatBean.java used:

@ManagedBean
@SessionScoped
public class ChatBean extends PircBot implements Serializable {
private static final String SERVER_URL = "irc.freenode.org";
private static final int SERVER_PORT = 6667;
private static final String CHANNEL_PREFIX = "#";
private static final String SUBTOPIC_SEPARATOR = "_";
private static final String DEFAULT_CHANNEL = "richfaces";
private String channelName;
private String message;
public String connect() {
       try {
           this.connect(SERVER_URL, SERVER_PORT);
           this.joinChannel(CHANNEL_PREFIX + DEFAULT_CHANNEL);
           channelName = DEFAULT_CHANNEL;
       } catch (NickAlreadyInUseException e) {
           FacesContext.getCurrentInstance().addMessage(null,
               new FacesMessage(FacesMessage.SEVERITY_ERROR, this.getName() + " nick 
               already in use", this.getName()
               + " nick already in use"));
           return null;
       } catch (IOException e) {
           FacesContext.getCurrentInstance().addMessage(null,
               new FacesMessage(FacesMessage.SEVERITY_ERROR, "Sorry, server unresponsive. 
               Try again later.",
               "Sorry, server unresponsible. Try again later."));
           return null;
       } catch (IrcException e) {
           FacesContext.getCurrentInstance().addMessage(null,
               new FacesMessage(FacesMessage.SEVERITY_ERROR,
                   "Sorry, we encountered IRC services problems. Try again later.",
                   "Sorry, we encountered IRC services problems. Try again later."));
        return null;
       }
       return "chat";
   }
...
}

As you can see our bean extends the PirBot abstract class. So we just using PircBot api in order to get connected to server. And performing redirect to most interesting for us chat.xhtml page.

Client main page

Screenshot below shows you the result we want to achieve on that page:

Here is the complete listing of the chat.xhtml page. We'll review it in details below:

<script>
    function getMessageString(data){
        return data.author + " - " +data.timestamp+ ": " + data.text;
    }
</script>
<rich:panel header="Welcome to #{chatBean.channelName} channel at #{chatBean.serverName}" 
id="chatpanel">
    <rich:panel styleClass="chatOutput" bodyClass="#{chatBean.channelName}Output" />
    <rich:panel styleClass="chatList">
        <rich:list value="#{chatBean.users}" var="user" id="users" type="unordered">
            #{user.nick}
        </rich:list>
    </rich:panel>
    <br clear="all" />
    <hr />
    <h:form>
        <a4j:push address="#{chatBean.listSubtopic}@chat"
            onerror="alert(event.rf.data)">
            <a4j:ajax event="dataavailable" render="users" execute="@none" />
        </a4j:push>
        <a4j:push address="#{chatBean.messagesSubtopic}@chat"
            onerror="alert(event.rf.data)" ondataavailable="jQuery('&lt;div/&gt;').
            prependTo('.#{chatBean.channelName}Output').text(
            getMessageString(event.rf.data))" />
        <h:inputTextarea value="#{chatBean.message}" rows="3" style="width:80%" id="nm" />
        <a4j:commandButton value="Send" action="#{chatBean.send}" render="@none" execute="@form" />
    </h:form>
    <hr />
    <h:form>
        <rich:panel header="Change nickname:">
            <h:inputText valueChangeListener="#{chatBean.changeNick}" id="cn" />
            <a4j:commandButton value="Change" execute="@form" render="@none"/>
        </rich:panel>
        <h:commandButton value="Disconnect" action="#{chatBean.leave}"/>
    </h:form>
</rich:panel>

I will show you two options of performing push updates.

  1. Using ondataavailable JavaScript handler which will grab the data from the JMS event directly on the client.
  2. Using a4j:ajax behavior to trigger an Ajax request which will perform partial update when the push informs us about server event.

So the first panel:

<rich:panel styleClass="chatOutput" bodyClass="#{chatBean.channelName}Output" />

is just a container for the chat text which will be updated via JavaScript.

And the second panel:

<rich:panel styleClass="chatList">
    <rich:list value="#{chatBean.users}" var="user" id="users" type="unordered">
        #{user.nick}
    </rich:list>
</rich:panel>

contains the rich:list component which displays the users connected to the channel. It will be updated via an Ajax request that is triggered when the event about list change is populated at server side.

Client side updates on server-side events using JavaScript

Let's review the first a4j:push component more closely:

<a4j:push address="#{chatBean.messagesSubtopic}@chat" onerror="alert(event.rf.data)"
    ondataavailable="jQuery('&lt;div/&gt;').prependTo('.#{chatBean.channelName}Output').
    text(getMessageString(event.rf.data))" />

It's used to get the messages into the main chat window. Here is the TopicContext declaration and main methods from the ChatBean which are generates events for that push:

import org.richfaces.application.push.TopicKey;
import org.richfaces.application.push.TopicsContext;
...
private transient TopicsContext topicsContext;
public String getMessagesSubtopic() {
   return this.getUserName() + SUBTOPIC_SEPARATOR + channelName;
}
private TopicsContext getTopicsContext() {
if (topicsContext == null) {
topicsContext = TopicsContext.lookup();
}
return topicsContext;
}
@Override
protected void onMessage(String channel, String sender, String login, String hostname, String message) {
   try {
       Message messageObject = new Message(message, sender, DateFormat.getInstance().format(
new Date()));
       getTopicsContext().publish(new TopicKey("chat", getMessagesSubtopic()), messageObject);
   } catch (MessageException e) {
       LOGGER.error(e.getMessage(), e);
   }
}
public void send() {
   this.sendMessage(CHANNEL_PREFIX + channelName, message);
   try {
       Message messageObject = new Message(message, this.getName(), 
DateFormat.getInstance().format(new Date()));
       getTopicsContext().publish(new TopicKey("chat", getMessagesSubtopic()), messageObject);
   } catch (MessageException e) {
       LOGGER.error(e.getMessage(), e);
   }
}

onMessage method - just overriden PircBot method and it's invoked when the message comes from the other chat users. And send method is invoked when we are sending a message. This is a standard JSF action of the send button.

As you can see in order to raise an event for a4j:push we just publish it to the TopicContext. publish method accepts two parameters:

  • TopicKey key - adress which consist of topic and subtopic names.
  • Object data - actual data passed to client side event.

Messages subtopic generated by getMessagesSubtopic() method used by a4j:push component on the page and is unique for every user and channel, so only current user will receive the event populated by the object.

The Message object passed as data is pretty simple POJO with three String properties - author, text and timestamp. It's later used on the client in push oncomplete to create formatted string by getMessageString(data) JavaScript method and later add to chat div:

<script>
    function getMessageString(data){
        return data.author + " - " +data.timestamp+ ": " + data.text;
    }
</script>
IMPORTANT: As was mentioned before the other way to publish an event is by just sending it to JMS bus. So you have no need to use our TopicContext in this common case. We've just used this approach for simple example as we have no components other than our simple JSF bean. See Additional Details section for more information about publishing via JMS bus.

Ajax updates on server-side events using a4j:ajax

Now let's review the second approach to perform updates according to events received by a4j:push:

<a4j:push address="#{chatBean.listSubtopic}@chat" onerror="alert(event.rf.data)">
    <a4j:ajax event="dataavailable" render="users" execute="@none" />
</a4j:push>

It's used to update the rich:list which shows the current channel users. Here is the main methods from the ChatBean which are generates events for that push:

public String getListSubtopic() {
   return this.getUserName() + SUBTOPIC_SEPARATOR + channelName + "List";
}
@Override
protected void onUserList(String channel, User[] users) {
   try {
       getTopicsContext().publish(new TopicKey("chat", getListSubtopic()), null);
   } catch (MessageException e) {
       LOGGER.error(e.getMessage(), e);
   }
}
@Override
protected void onJoin(String channel, String sender, String login, String hostname) {
   try {
       getTopicsContext().publish(new TopicKey("chat", getListSubtopic()), null);
       Message messageObject = new Message("joined channel", sender, 
           DateFormat.getInstance().format(new Date()));
       getTopicsContext().publish(new TopicKey("chat", getMessagesSubtopic()), messageObject);
   } catch (MessageException e) {
       LOGGER.error(e.getMessage(), e);
   }
}

We are using the same publishing through TopicContext at server side just defining different subtopic for that a4j:push. And passing null as data because we do not planning to process anything at client side. That's where:

<a4j:ajax event="dataavailable" render="users" execute="@none" />

come in play. When push receives the event an ajax behavior sends a request which just perform rich:list render with new values. Pretty simple isn't it?

Additional Details

There I want to pay your attention to some details not covered within the article.

Single Connection

As you can see in this example we used two a4j:push component on a single page in order to demonstrate two different ways to process push events. It is important to know that this does not mean wo connections are getting opened. All the instances of the push component uses single connection and only the subscribed one gets the event for processing according to it's adress after some event is received. You can verify that by using Firebug for FireFox for example.

Publishing via JMS bus

JMS messages types supported by push are:

  • ObjectMessage
  • TextMessage

Corresponding data from getObject or getText passed to DataSerializer and getting serialized to the client data(to JavaScript using default serializer).

To be Continued...

And finally I want to announce topics which planned to be covered in next Push related articles.

Integration with CDI events

Being a first class citizen in JEE6 ecosystem CDI getting paid much attention during RichFaces development for sure. And support of CDI event system by a4j:push are also topic for upcoming separate blog entry!

And more...

There are a lot of possibilities with this component, too many to describe using just a single article. So follow our blogs or RichFaces twitter for any future examples and documentation updates related to this great component!


[Get updates of my blogs in twitter]

[My jroller.com blog]

RichFaces 4 - Object Validation

Posted by Ilya Shaikovsky    |    Feb 24, 2011    |    Tagged as
Article updated. Mistake with 3.3.x functionality description corrected in Implementation details section

Introduction

As we reviewed in a previous blog with JSF 2 and RichFaces 4 you already have the Bean Validation support all the way to the browser with our client side validation. So you can effectively work with your server side object without any additional view level code related to validation.

This blog is going to review the last (but not least) validation feature which RichFaces 4 adds to JSF 2 . It's called Object Validation and provides a way to validate all your model Object fields considering even ones which were not used in the current view.

Why do you need that? The very first example which came to my mind as it appears frequently on various forums is dependent fields validation.

Password Validation Example

Let's check the password validation example:

<h:form>
	<rich:panel header="Change password" style="width:500px">
		<h:panelGrid columns="3">
			<h:outputText value="Enter new password:" />
			<h:inputSecret value="#{userBean.password}" id="pass"/>
			<rich:message for="pass"/>
			<h:outputText value="Confirm the new password:" />
			<h:inputSecret value="#{userBean.confirm}" id="conf"/>
			<rich:message for="conf"/>
		</h:panelGrid>
		<a4j:commandButton value="Store changes"
			action="#{userBean.storeNewPassword}" />
	</rich:panel>
</h:form>

And the simple managed bean source:

@ManagedBean
@RequestScoped
public class UserBean {

    @Size(min = 5, max = 15, message="Wrong size for password")
    private String password;
    @Size(min = 5, max = 15, message="Wrong size for confirmation")
    private String confirm; 
//...
    public void storeNewPassword(){
        FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Succesfully changed!", "Succesfully changed!"));
    }

//Getters and setters
}

So we solved half of the problem:

We are seeing the error messages if the password fields do not satisfy the validation rules given. Nothing is checking if passwords are the same though, just that they are independently valid. So what is the easiest way to validate if the fields are equals? We could perform that in action but that is quite late in the JSF lifecycle for validation. We could use some solutions using f:attribute in order to pass dependent field id to the other input and find the component by that id in custom validate method. There are also some other ways which are pretty easy to find across different knowledge-bases'. But most of them are either invoked in an improper phase (like action at INVOKE_APPLICATION) or has possible maintenance problems(f:attribute solution requires us to be patient with id's changes in view as validation depends on them).

RichFaces 4 Object Validation for cross-field validation

This is where RichFaces 4 Object Validation feature come in play! Here is what we propose to use:

<h:form>
	<rich:graphValidator value="#{userBean}" id="gv">
		<rich:panel header="Change password" style="width:500px">
			<rich:messages globalOnly="true"/>
			<rich:messages for="gv"/>
			<h:panelGrid columns="3">
				<h:outputText value="Enter new password:" />
				<h:inputSecret value="#{userBean.password}" id="pass"/>
				<rich:message for="pass"/>
				<h:outputText value="Confirm the new password:" />
				<h:inputSecret value="#{userBean.confirm}" id="conf"/>
				<rich:message for="conf"/>
			</h:panelGrid>
			<a4j:commandButton value="Store changes"
				action="#{userBean.storeNewPassword}" />
		</rich:panel>
	</rich:graphValidator>
</h:form>

And the Bean(Updated with implements Cloneable):

@ManagedBean
@RequestScoped
public class UserBean implements Cloneable{

    @Size(min = 5, max = 15, message="Wrong size for password")
    private String password="";
    @Size(min = 5, max = 15, message="Wrong size for confirmation")
    private String confirm="";

    @AssertTrue(message = "Different passwords entered!")
    public boolean isPasswordsEquals() {
        return password.equals(confirm);
    }

    public void storeNewPassword(){
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Succesfully changed!", "Succesfully changed!"));
    }

So lets look through the sample details. rich:graphValidator tag should wrap the inputs bound to the object which we are interested in validating. The value attribute should be pointed to that bean name. Then at PROCESS_VALIDATION phase all the object fields will be validated according to constraints added. And in that particular case isPassWordEquals will be validated using AssertTrueValidator. That looks just like we expected!

Different passwords entered(but valid according to size):

Verification successful:

Implementation Details

UPDATED(28.02) section below. Actually 3.3.x used the same way. Was written that it worked at model updates by mistake.

Just one question appears. Those who know the JSF life-cycle will ask immediately about how the bean could be validated before the model updates? Does RichFaces propose to use validation after process updates phase? No. We perform a clone() on your bean instance at validation phase and updating new instance with all the new values submitted(that's why we still need to wrap all the inputs related to rich:graphValidator). We then validate the cloned object firing validation messages if needed. Your model objects remains clean, lifecycle gets interrupted properly after Process Validations phase and messages encoded to client during Render Response.

NOTE: if cloneNotSupportedException thrown from the object – validation will be done at model updates. And that is the only exception to our architecture which really can't be workaround-ed.

Try it out!

Now having JSF 2 Bean Validation support standardized, RichFaces 4 Client Side Validation and Object Validation features we believe you will be able completely concentrate on your business tasks and will not spend time for any additional JSF development in the validation phase. Try our new features in RichFaces 4.0.0.M6 and let us know about any problems or questions appeared. That will help us greatly to provide those features stable and well documented prior to RichFaces 4 Final release!


[Get updates of my blogs in twitter]

[My jroller.com blog]

RichFaces 4 - Client Side Validation

Posted by Ilya Shaikovsky    |    Feb 17, 2011    |    Tagged as

Introduction

One great feature in JSF 2 is that it provides built-in support for JSR-303 bean validators. This means that now it is the containers responsibility to validate your model objects at multiple application tiers according to your annotation based constraints. Take a look at a simple JSF managed bean with JSR-303 annotations added:

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@ManagedBean
@RequestScoped
public class UserBean {

    @Size(min=3, max=12)
    private String name = null;
    @Pattern(regexp = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[a-zA-Z]{2,4}$" , message="Bad email")
    private String email = null;
    @Min(value = 18)
    @Max(value = 99)
    private Integer age;
///...
//Getters and Setters
}

With JSF 2 all the validators added using bean validation annotations will be registered on components bound to the bean properties and triggered in the Process Validation phase. So you have no need to define additional validators using JSF standard validator tags such as f:validateLength or f:validateDoubleRange or use the required attribute. But all that stuff is applied only on the server side. In the past you needed to create some custom validators for client side which are not connected to server side rules directly but just copies that functionality. This of coarse leads to additional maintenance and complexity.

Now with RichFaces 4 we provide that final level of abstraction to the validation ecosystem. RichFaces Client Side Validation feature(CSV abbreviation used across wiki pages and jiras) consist of:

  • JavaScript validators implementations for nearly all JSF and JSR-303 validators.
  • Mechanism which register corresponding client validators to the components which bound to annotated fields or uses f:validate* attached.
  • rich:message(s) components were added with client side objects which allows to manipulate with them on client side. Used to add/remove messages which appeared at client side.
  • Extension points which allows the user to provide JavaScript implementation for his custom server side validators (in the future).

Usage

First need to mention a common requirement for both JSF and RichFaces using bean validation. In order to use it with JSF 2 - you should use JEE 6 application server which is bundled with a JSR-303 implementation. Or if using just Tomcat or another simple servlet container add validation-api jar and some validators provider (e.g. hibernate-validator) to your application libraries.

Then all you need to add to the component in order it to start using client validators is new rich:validator behavior:

<h:inputText value="#{userBean.name}">
	<rich:validator/>
</h:inputText>
@Size

constraint rules defined in UserBean above will be applied there. Or you can use a similar definition for old-style JSF validators:

<h:inputText value="#{personBean.name}">
	<f:validateLength minimum="3"/>
	<rich:validator/>
</h:inputText>

Client implementation of Length validator will be registered to be called on the client.

Note: You still could use JSF validators tags but it's really preferable to migrate to Bean Validation. As you can see from that sample you still duplicating the validation at view and model level using annotation based constraints for your entities and defining the same view validators with separate tags.

<rich:validator> is a behavior which just triggers all the client validators methods according to the registered server side validators. As a behavior it could be defined for any event available on parent component. In previous examples default event change used. Let's modify examples to use keyup event:

<h:inputText value="#{userBean.name}">
	<rich:validator event="keyup"/>
</h:inputText>

Ajax Fall-back

In case you registered some validators but they have no client implementation available — Ajax fall-back will be used. This means that <rich:validator> will invoke all the available client validators. And if all of them returned valid, RichFaces will perform an Ajax request invoking any server side validators.

Note: For now Ajax fall-back is always used if a client validator is not available. In future we planned to design some way to invoke only available client validators and not send Ajax request for the others RF-10142. Could be useful in some cases where additional request to server are not expected because validators uses some complex services invocations or makes db calls for example.

Messages from client validators

And the last question is - how do users get notified with the client side validation results? It's rather simple actually. Messages for client validators will be displayed using the same rich:message(s) components which are used for common server side validation messages.

So let's review complete sample for the Edit user info form:

<h:form>
<rich:panel header="User information">
	<h:panelGrid columns="3"> 
		<h:outputText value="Name:" />
		<h:inputText value="#{validationBean.name}" id="name">
			<rich:validator />
		</h:inputText>
		<rich:message for="name" />
		<h:outputText value="Email" />
		<h:inputText value="#{validationBean.email}" id="email">
			<rich:validator />
		</h:inputText>
		<rich:message for="email" />
		<h:outputText value="Age" />
		<h:inputText value="#{validationBean.age}" id="age">
			<rich:validator />
		</h:inputText>
		<rich:message for="age" />
		<h:outputText value="I agree the terms" />
		<h:selectBooleanCheckbox value="#{validationBean.agree}" id="agree">
			<rich:validator/>
		</h:selectBooleanCheckbox>
		<rich:message for="agree" />
	</h:panelGrid>
</rich:panel>
</h:form>

in case of failure of any validator registered to name h:inputText component - message below will be updated by CSV JavaScript showing the information label. Here is the screenshot from richfaces-showcase application:

All the messages for inputs appeared without any server side validation invocation. Script validation invoked after you changed the field and shifting focus out of the component. In this case only one Ajax request was sent – after clicking the check-box (AssertTrue validator client implementation is not available for M6 actually so you see Ajax fall-back in action). Pretty easy isn't it?

M6 functionality

In RichFaces 4 Milestone 6 all the server side functionality related to registered validators look-up, validators script output, messages and behavior rendering were done. As for client side functionality – all messages, JSF validators and most of JSR-303 validators are complete. We have a few validators still missing (e.g. AssertTrue/False, Past) but they will be added in nearest time. See developer richfaces-showcase demo which was added with CSV samples prior to M6.

Note: As it was mentioned before missed validators will be invoked using Ajax fall-back.

Start Using Now

Even considering some minor issues reported and a few validators still missed – it's worth to start using the CSV right now. You will need to do nothing in the future in order for new validators to start working once they are implemented. When you update to next version they will be automatically added by behavior script renderer and start working on the client side. Also, you can help let us know about any problems or concerns prior to final.

The future plans for validation

  • Add default levels of validation support. This means that we will provide an option that will enable <rich:validator> automatically at some level such as for a form or view.
  • Add support to Action components. This means that you will be able to add <rich:validator> to your "save" form button and it will call all the validators for inputs in the form prior to submit.
  • Complete instructions for creation custom validators. Basic mechanisms is ready so we just need to check how it will works and document.

[Get updates of my blogs in twitter]

[My jroller.com blog]

RichFaces 4 Overview. Part IV – Inputs Components.

Posted by Ilya Shaikovsky    |    Nov 22, 2010    |    Tagged as

We're done with two more milestones [M3] [M4], introduced GAE support, visited great JavaOne event and finally I'm ready to continue this series in order to guide you through RichFaces 4 migration!! In this write-up I will review the migrated input components.

Inplace Components

rich:inplaceInput and rich:inplaceSelect components are almost unchanged from a usage point of view (we want your migration to be smooth :) ). However, the markup and client-side code, which was the cause of number of issues raised by the community, were completely reviewed and rewritten.

So, meet the well-known inplace components in RichFaces 4:

<rich:panel style="width:220px;">
	<f:facet name="header">
		<h:outputText value="Form built with inplaces"></h:outputText>
	</f:facet>
	<h:panelGrid columns="1">
		<rich:inplaceInput defaultLabel="click to enter your name" />
		<rich:inplaceSelect defaultLabel="click to choose your country"
showControls="true">
			<f:selectItem itemLabel="USA" itemValue="0"/>
			<f:selectItem itemLabel="Canada" itemValue="0"/>
			<f:selectItem itemLabel="UK" itemValue="0"/>
		</rich:inplaceSelect>
	</h:panelGrid>
</rich:panel>

And the result:

You can choose the events which will activate the editing and storing, configure advanced settings like storing on blur, add disablement conditions, add UI controls for applying values, and so on. Also, the components support navigation and control using the keyboard.

Input Number components

Let’s check one more pair of components which have also been migrated with minimal changes to RichFaces 4.x. It’s the also well-known rich:inputNumberSlider and rich:inputNumberSpinner components. The most noticeable change (except markup optimization) is that keyboard navigation is greatly improved from the 3.3.x version. We removed some unnecessary cases of getting focus from internal controls (the buttons in the spinner), and made some of the parts additionally focus-able (the slider element in slider). The first change was done because you already could change the value with the up and down keys directly. The second was done because the text input is, in general, not required, and could be hidden for the component, using the horizontal slider for input. The usage of left and right arrow keys in the text input could not be processed in the same manner as they should work for cursor change.

So let’s check the code which you used in 3.3.x:

<rich:inputNumberSlider value="50" />

<rich:inputNumberSpinner value="50" step="10"/>

And the result:

Combo vs SuggestionBox – unified rich:autocomplete component

In 3.3.x we had two separate components (rich:suggestionBox and rich:comboBox) for simplified input with autocomplete support. Both of them provided similar functionality but worked in different modes (one used Ajax and the other worked completely on the client). The second difference was that suggestionBox was able to be attached to any input and comboBox had the input and button built-in. So, after pre-migration redesign, we decided to create single rich:autocomplete component with all the features combined. The only feature it lost was the ability to be attached to any input, but we are planning the introduction of using behaviors for such components after the final release.

The most important attributes to define the usage are as follows:

  • mode attribute. The client and ajax values are well known to 3.3.x combo and suggestion component users. Also in 4.x, we are introducing the new cachedAjax mode! It is used when you prefer to load suggestions using Ajax when the component is actually activated, but do not perform any reloads after further input clarifications.
  • autocompleteMethod and autocompleteList attributes. Both of these attributes define the endpoints for data-fetching by the component. A method attribute should be used if you want to generate suggestions dynamically according to the prefix entered (suggestionBox variant), and list should be used to point the component to static list of strings. Both attributes work in any mode. For client and cachedAjax mode, further suggestion-filtering is done at the client-side by the built-in component or a custom filter function.
  • layout and fetchValue attributes. Instead of the default built-in list of strings and a simple div-based layout, you could choose to use custom objects and a table or list layout for presentation by using the layout attribute. For example, you could show the suggestions list in a more convenient and informative way with a few columns of details. In that case, the fetchValue attribute should be defined in order to determine what to insert during selection from the table.

All the other attributes came from the suggestionBox and comboBox components, and are well known to those who used the components in 3.3.x: fetchValue, tokens, autofill, minChars, selectFirst (previously selectFirstOnUpdate) and so on.

Let check some samples. The first is a simple autocomplete in cached Ajax mode which requests suggestions after the first character is entered. It supports the entering of comma-separated strings.

Code:

<h:form>
	<rich:autocomplete mode="cachedAjax" minChars="1" tokens=","
		autocompleteMethod="#{autocompleteBean.autocomplete}" />
</h:form>

And the result:

And the second sample. Here you can see custom objects and table layout usage. Pure client-side suggestions are taken from the list objects used. Also there is an additional button on the input to show the suggestions.

Code:

<rich:autocomplete mode="client" showButton="true" layout="table"
	autocompleteList="#{capitalsBean.capitals}" fetchValue="#{cap.name}" var="cap">
		<rich:column>
			<h:graphicImage value="#{cap.stateFlag}"/> 
		</rich:column>
		<rich:column>
			<h:outputText value="#{cap.name}"/>
		</rich:column>
		<rich:column>
			<h:outputText value="#{cap.state}"/>
		</rich:column>
</rich:autocomplete>

And the result:

Select component

Great news! You no longer need to use suggestionBox suggestObjects feature, which has limitations and is not native for input in 3.3.x). And you are no longer required to create more complex converters, as with the 3.3.x comboBox, in order to transform the label (which was only supported in selectItem) to an actual object value. In 4.0 Milestone 5 we are introducing the rich:select component!

The select component has a direct keyboard-input feature and unified skinning for any browser, unlike the standard selectOne component, yet it works completely the same as the standard component under the hood!

It’s pretty simple from a functional point of view. You can type directly into the text input and it will suggest one of the selectItems which suits the current input. Also, you can just choose from the list, restricting direct input as for a normal select. For incorrect input, the current value will not be validated successfully as for the normal select component.

Let’s check in the code:

<rich:select>
	<f:selectItem itemValue="0" itemLabel="Option 1" />
	<f:selectItem itemValue="1" itemLabel="Option 2" />
	<f:selectItem itemValue="2" itemLabel="Option 3" />
	<f:selectItem itemValue="3" itemLabel="Option 4" />
	<f:selectItem itemValue="4" itemLabel="Option 5" />
</rich:select>

Rendered as a standard select without direct typing support:

And this one:

<rich:select enableManualInput="true" defaultLabel="start typing for select">
	<f:selectItems value="#{inplaceSelectBean.capitalsOptions}" />
</rich:select>

Accepts user input using keyboard:

Calendar

The rich:calendar component was also migrated with few changes from a functional point of view. It still has the following main features:

  • Pop-up and inline modes
  • Ajax and client month scrolling
  • Client and server side dates disablement and styling
  • ...

So let’s see some different states of calendars:

<rich:calendar datePattern="dd/MM/yyyy hh:mm:ss"/>
<rich:calendar popup="false"/>

Will look like:

And after some manipulation:

The most noticeable difference that should be considered during migration is that we are planning to redesign our macro-substitutions-based templating. So for now, day markup redefinition is not possible, but it will be available in future after the base templating feature is done. For that reason, the data model has no getData for now, because it can't be used without templating.

One more note related to organizer creation using that component: after templating for cells becomes available, it should still be possible to implement simple cases as in 3.3.x. But there is a separate component in our plans related to pure organizer creation. The main reason for this is that most common cases for the content of day definition uses some repeats, dataTables, or lists (or any other iteration components), and those components require server-side rendering support. As such they can’t be done just using client templating.

To be continued...

P.S. What on my way besides those articles

I'm proud to announce that me and Max Katz are starting to work on new RichFaces 4 book (Apress) to be published in the first half of 2011. I’ll be posting outline and more details later.


[Get updates of my blogs in twitter]

[My jroller.com blog]

Google Application Engine Support with RichFaces 4

Posted by Ilya Shaikovsky    |    Oct 18, 2010    |    Tagged as

Support for cloud deployment of RichFaces based applications was one of the hot topics for a long time and finally it’s there! Actually the development was mostly completed a month ago and was already announced at Java One sessions. The official announcement was postponed in order to stabilize the feature and to create a special archetype to make it an easy start.

Let’s review what was done and the steps which should be performed to deploy your RichFaces application to Google Application Engine.

Restrictions of GAE deployment

Google Application Engine deployment introduces some restrictions for the Java developer. Here are some of them which are important for us to get started:

How to avoid Java2D? Maven plugin for resources generation.

One of the most important restrictions which required additional development from our team was the Java2D usage restriction. RichFaces Skinning mechanism relies to these classes for dynamic resources generation to support application skinning. To meet GAE restriction without losing RichFaces look'n’feel flexibility a new Resource Plugin that creates static version of RichFaces resources was needed:

  • Substitute skin parameters to CSS for all skins used by application
  • Compress CSS files
  • Provides relative URLs in CSS
  • Generates skin images
  • Extracts all JavaScript files used by application and compress them
  • Generates descriptor for all processed files. RichFaces framework use this descriptor to point to appropriate resources (e.g. placed on external server/CDN)

Check plugin definition and configuration at generated application pom.xml (maven-resources-plugin)

All that is needed after that is to define static resource location in web.xml using context parameter like:

    <context-param>
        <param-name>org.richfaces.staticResourceLocation</param-name>
        <param-value>#{facesContext.externalContext.requestContextPath}/static-resources/#{resourceLocation}</param-value>
    </context-param>

Note: that this can also be useful for serving resources from different servers to aid in scalability in production environments.

What should be considered additionally

There are some more points related to GAE restrictions. Some of them are not directly related to RichFaces usage but should be considered by any JSF developer:

  • Current push component architecture – does not support listener serialization.

So we still need to complete push architectural redesign in order to support cloud environment properly for that component.

  • Creation of new threads is not allowed

So trying to port some simple examples from 3.3.x directly which relies on threads (e.g. poll/push) – will not works.

  • Running JSF 2.0 at GAE requires some additional settings even without RichFaces 4.

Check that article from GAE knowledge base for details.

  • No write access to file system

Developer should configure cache to use Google Memcache implementation.

Archetype for GAE project generation and build

As was mentioned above, and at JavaOne we have created a special archetype in order to create JSF 2.0, RichFaces 4 application skeleton already configured for GAE deployment. To generate a project – just execute:

mvn archetype:generate -DarchetypeGroupId=org.richfaces.archetypes 
-DarchetypeArtifactId=richfaces-archetype-gae -DarchetypeVersion=4.0.0.20101004-M3 
-DgroupId=<yourGroupId> -DartifactId=<yourArtifactId> -Dversion=1.0-SNAPSHOT 

Now the project could be built using simple mvn install execution

Notes:

  1. First released version of the archetype is in 4.0.0.20101004-M3
  2. The readme.txt file contains instructions for deploying to GAE server, or using the local GAE SDK developer server for local testing.

Deploying applications to GAE account

In order to avoid copy and paste work – here is the link to official instructions which we successfully using for our tests deployments. If you already have your account created, application registered and GAE SDK configured properly:

  • Make sure you updated version in appengine-web.xml before redeploying
  • Execute appcfg update <path to exploded archive with application>
  • That’s it! Just go to your account and check that the application in place and working!

Get updates of my blogs in twitter

My jroller.com blog

JSF 2.0 CookBook by Anghel Leonard review

Posted by Ilya Shaikovsky    |    Oct 4, 2010    |    Tagged as Discussions JSF

Overview

Actually I’m a fan of this kind of book, as in my opinion they are useful for beginner and experienced developers. It’s always good to have it to be able to review all the possible solutions for concrete case and start quickly with prototyping. So that’s why I accepted Packt Publishing proposal to review JSF 2.0 CookBook by Anghel Leonard with pleasure.

Finally I’ve finished reading it and now wanting to share my opinion about its advantages and problematic parts. From the beginning I want to give quick overview of common points and then to go through the whole book to highlight recipes I really liked and propose some kind of errata for other ones.

Positives

It has a really good structure for recipes! I’m able to open any recipe without going through some overviews about conventions and environments info and just use the recipe! Every recipe contains description of technologies and tools used. Also it points us to the archive with complete application and has good explanations of key points for sure. Many of the JSF world FAQ’s are covered well in the book and most of them could be picked by just copying the sample code from book applications.

Also need to highlight that in most cases – all the alternatives for implementation of the same use-case are covered. That allows the user to choose most convenient way for him!

And I believe that in general – that book really worth a place on your shelf because could answer at many common questions or at least provide some pointers about where to check for the answer.

Some criticism

Well there is always some place for critical words. But let that criticism not to confuse the author and the guys who plans to read it. I just want to highlight some points which I believe will be useful for author in future and will make the readers to go through some problems easier.

Most of the examples show clean and useful samples – but sometimes author uses just “hello world” style for complex cases and the developer could miss the points or underrate the feature importance. That the main problem of some recipes. And I’m not sure if recipes where there are no code samples at all (there are few present) should be in such book.

Author uses JSP through the entire book. However – it’s deprecated in 2.0 and was not really popular in 1.2 after facelets came to the scene. It’s not a big problem for sure – but in some cases some important info missed. For example – custom component recipes – says about TLD descriptors but has nothing about taglib’s needed for the component.

So let’s go through the book shortly. Again – critic words which could appears there – only pointer for the readers to pay their attention more and to the author – to consider in future.

Going through

Now let's look some closer to book content.

Conversion/Validation chapters

Both chapters are described really well and will be useful for the developers who need to get a quick start with that JSF area. Most cool points which I like to see included into JSF CookBook, as they are asked much across the community – converters with passing parameters, validation using regular expressions with useful list of common expressions, JSR 303 recipes for validators groups and calling the validation from your java code.

Some Problems
  1. For better understanding - RichFaces bean validator recipe @NotEmpty case could be slightly extended with information that in general JSF 1.2 not validates the empty inputs at all. So need to mention that it will work only using RichFaces framework (which provides standard input renderers extensions to support null-values validation). Not just to say how cool it is to use RichFaces J but just to make sure that developer will realize where the problem is if will try the validation without RichFaces and it will stop working.
  2. Author missed to highlight the difference between BeanValidator and AjaxValidator in RichFaces. They described as completely similar. Most important that should be mentioned that ajaxValidator – is a combination of Ajax Support and Bean Validator.

File Management

This provides a good overview of all the component libraries which provides solutions for that topic. All the samples covered well and could be just picked to real application from the samples. The only minor problems lack of samples for the solutions without usage any additional libraries (download, export).

Security

The recipe contains good overview of JSF security and Acegi. But in my opinion chapter lacks some basic information and could be slightly extended with the pure JSF solutions.

Custom Components

This chapter is one which caused most of my questions. It’s sad as custom components creation – one of the most important topics in JSF – so I paid much attention to that chapter. Overview is short and really clear and looks really good as an introduction for the beginner... However screenshot of the lifecycle contains basic mistake. The “encoding” and “decoding” labels was put to wrong phases opposite to the places where them should be.

“EmailInput” – not looks as a best example of custom component. As written at all the classical JSF books resources - “before creation of the new component – double-check that you can’t achieve the result via some composition”. Even considering that the author probably wanted to gave really simple overview – the question remains then - why he was need to override renderer methods of the input? Standard input renderer should be enough there and it’s a way to confuse developer as he could decide that extension of the components still requires from him to override base functionality every time.

“ImageViewer” – again maybe it was better to extend the graphicImage component instead of writing from scratch.. And the code not looks really clean especially in adding Ajax capabilities section where the new JS not listed normally but only included in renderer as escaped String.

“ProxyId library”. Need to admit that I never heard about this interesting extension. But that probably related to the facts that RichFaces already provides the rich:clientId, rich:element, rich:findComponent and other functions to perform different operations on components using their short id’s. And not a section problem but note for me to check - author not listed but interesting to know how that proxyId will works in iteration components.

“Accessing resources from custom component”. From my point of view – that is most useless recipe in that chapter... I believe that we should not believe that JSF beginner – could understand the difference of approaches using just brief descriptions. In order this section to become recipe – it should provide the code and explanations based on it.

“RichFaces CDK”. At first small notes:

  • For those who will read the book only now – the settings for maven – has been changed after we switched to JBoss nexus repository.
  • Author should explicitly define that this shows CDK from RF 3.3.3 in action. As in 4.x it is completely redesigned and not compatible with the old one.

“Getting Ready” in “RichFaces CDK” contains the info on manual folder and pom.xml creation. However it could be done by archetype as written in our CDK reference. “How to do it” – at first asking the user to type the command from the screenshot – looks not good.. At least for big 3-row command. J The rest of the recipe in general explained well. Minor note - project could be easily created by archetype instead of manual sample creation.

“Composite Components” section explains the process really well and provides short but good samples.

“Mixing dojo and JSF”. In general – the recipe will work well for somebody who needs to get the idea about how to use dojo widgets in JSF components. But I’m confused with the facts that author proposes just output attributes needed by dojo using component but include all the resources on the samples page. It looks like not very maintainable solution.

AJAX in JSF

“DynaFaces” – recipe which unfortunately is not described well in my opinion. Just “drag and drop some components and then add Ajax transaction” – is not enough to understand who could need those recipe and why he need dynaFaces. Why it’s still useful – self-descriptional application archive.

“Tomahawk suggestAjax” and “A4j Ajax” recipes are clean and well described.

“Writing reusable AJAX components” recipe contains really weird issue – there is no Ajax which is mentioned in section name J. Just common spinner component optimized for usage of multiple instances on the page.

Main issue of that chapter on my opinion – lack of really common tasks recipes... E.g. how to perform optimized Ajax editing of huge tables, how to organize wizards, how to lazy load data after page rendered and some more... Simple cases are useful for sure as shows basics... But the developers has to implement much more complex issue in real enterprise applications and that questions appears on different community forum continuously

Localization

The chapter covers all the main cases which could be needed by the developer and recipes look clean at most.

Let’s highlight some samples there. “Accessing message resources from a class” – pretty good recipe and looks clean while you looking for the most important Helper class which performs obtaining the localized String. Minor problem there – it contains no result screenshots and actual properties listing – so not really easy to get what the user will see in the result. Need to start application from examples archive to check. Selection a timezone in JSF 2.0 – good pointer for the reader to possible problems. Even having no recipe author at least pointed the developer to the fact that he should pay attention and check for additional information. Displaying Arabic characters recipe – again uses JSP only.. But what about facelets? There are some other tricks existing and it’s knowledge needed by the developer more.

JSF Images, CSS and JS

“Injection of CSS“ recipe are we really talking about styling here? So why do I see only that dry source code and not at least a single image of the beautiful page created? :) It's could be not easy for the beginner to imagine what did the author achieved there (the beginner could not know the rules to apply those attributes for the component) without going again to examples archive.

“Dynamic CSS“ - I believed that there I will see how to use EL in CSS stylesheets :) B.t.w. frequently asked use-case which could be shown there - highlighting in the table cells/rows using styles which returned according to row model type, (e.g. Important or LowPriority). But the sample there unfortunately looks more static.

“Java Script injection“ well simple and clean example gives some ideas how I could apply my JS knowledge in JSF. Just working with JSF hidden fields section confuses me as there is nothing about hidden fields. (Actually I expected h:inputHidden usage) “Passing parameters“ could become also really useful section – but the examples miss some more real usage cases. “Opening popups using JSF and JS“ - looks good and answers the initial question really fine..

“Rss4jsf“ – Thanks for the pointer :). I've missed that framework and plan to look though now. It looks clean and easy to use. “Resources in JSF 2.0“ – it would be good to have a few words about access from Java objects. But proposed descriptions and samples of usage in the views looks clean and self-explanatory.

JSF Managing and testing

JSF Unit – want to highlight great overall descriptions, good samples and list of most used API. The only charts usage – not really related to testing, and in general contains no recipe but just pointer to library site… But that not really make the whole chapter less useful.

Facelets

Almost nothing to say – but that because the chapter has no problems in general and well written :)

Want only to highlight “composition component for JSF 2.0” section. It’s really good sample. But the main problem – for some reason (seems because a section name) I expected that it will be about composite component especially considering that the author mentions JSF 2.0. And it’s actually about custom tag from 1.2. But as far as I realized that that is just custom tag recipe and not actual composite component I re-read it and want to admit that it’s pretty good for that topic.

“Passing action” – really good to see there. It’s most weird issue in Facelets 1.x and most frequent question from the guys who creating custom facelets.

JSF 2.0

Good and useful chapter again – so let’s just look to some concrete samples which I want to pay readers attention.

Why we need Pretty Faces to create bookmarkable URLs in 2.0? It’s JSF 2.0 core feature. This just seems placed in wrong chapter. It was good for 1.2 when GET requests were not supported out of the box. Later we will found section about JSF 2.0 navigation enhancements and view parameters usage. In general the overview of them written fine. Just already mentioned problem - it loses some real case to show its coolness (it could be greatly used in common case of product list – product details navigation).

Mixing JSF and other technologies.

“Seam”. Configuration overview contains all general pointers to set-up Seam.. However in my opinion to try Seam the reader need more information or real samples. And wow! It’s the first write-up (even considering that short one) about Seam which is not talks about Conversations at all! :)

“Mixing JSTL and JSF”. It’s unfortunately not about mixing but about replacement h:dataTable to c:forEach. And I do not see advantages – why should I use it?

“Integration with Hibernate and Mixing Spring and JSF”. I think that such kind of content is just not for cookbook. Being the guy who need to learn something new from the real kick start samples - I still not see how to do at list something simple with that.

“JPA”. Finally I’m seeing some sample and it’s cool that I finally could check how to actually reach the db in my JSF action. It’s sad that login action not implemented but in general I understand how to proceed with that. So seems most useful recipe in that chapter.

Configuring JSF related technologies.

Some lack of versioning information. E.g. only RichFaces 3.3 and older versions requires Filter. But in general such section could be useful in order to quickly check the settings required for libraries usage.

Conclusion

Actually my conclusion was already written at the beginning. I believe that the book will find a place on your shelf and you will check it from time to time when needs to implement some concrete case quickly. All the problematic parts listed – just pointers for the author for future and I believe that he could successfully continue his works creating useful books for JSF community developers.

Get updates of that blog in twitter

Packt launch fifth annual Open Source Awards

Posted by Ilya Shaikovsky    |    Aug 30, 2010    |    Tagged as

Birmingham, UK. 9th August 2010

The 2010 Open Source Awards was launched today by Packt, inviting people to visit www.PacktPub.com and submit nominations for their favorite Open Source project. Now in its fifth year, the Award has been adapted from the established Open Source CMS Award with the wider aim of encouraging, supporting, recognizing and rewarding all Open Source projects.

WordPress won the 2009 Open Source Content Management System (CMS) Award in what was a very close contest with MODx and SilverStripe. While MODx was the first runner up, SilverStripe, a Most Promising CMS Award winner in 2008, made its way to the second runner up position in its first year in the Open Source CMS Award final.

The 2010 Award will feature a prize fund of $24,000 with several new categories introduced. While the Open Source CMS Award category will continue to recognize the best content management system, Packt is introducing categories for the Most Promising Open Source Project, Open Source E-Commerce Applications, Open Source JavaScript Libraries and Open Source Graphics Software. CMSes that won the Overall CMS Award in previous years will continue to compete against one another in the Hall of Fame CMS category. These new categories will ensure that the Open Source Awards is the ultimate platform to recognise excellence within the community while supporting projects both new and old. “We believe that the adaption of the Award and the new categories will provide a new level of accessibility, with the Award recognizing a wider range of Open Source projects; both previous winners while at the same time, encouraging new projects” said Julian Copes, organizer of this year’s Awards.

Packt has opened up nominations for people to submit their favorite Open Source projects for each category at www.PacktPub.com/open-source-awards-home . The top five in each category will go through to the final, which begins in the last week of September. For more information on the categories, please visit Packt’s website www.PacktPub.com/blog/packt’s-2010-open-source-awards-announcement

Contacts

Julian Copes PR Executive, Packt Publishing

julianc@packtpub.com www.PacktPub.com

About Packt

Packt is a modern, unique publishing company with a focus on producing cutting-edge books for communities of developers, administrators, and newbies alike. Packt’s books and publications share the experiences of fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Their solutions-based books give readers the knowledge and power to customize the software and technologies they’re using to get the job done. For more information, please visit www.PacktPub.com

back to top