Tag Archives: web

Easier Multi-Field Validation with JSF 2.0

One of the most frequent needs when developing application forms is multi-field validation (or cross-field, but I’m not using this term because when I put it on Google I actually got some post-war pictures). I’m talking about situations where we need to compare whether an initial date is earlier than an end date or a value is lower than another one. Isn’t it an obvious feature in every business-oriented framework? Not really. Unfortunately, the JSF specification doesn’t support it by default. Therefore, until its latest production release (JSR 245 – JSF 2.1), JSF did not offer an out-of-the-box multi-field validation feature.

We probably can hope for something coming in JSF 2.2, since the JSR 344 mentions “Multi-field validation”. Meanwhile, developers have used their fruitful creativity to implement their solutions. You can find plenty of working alternatives at Stackoverflow.com; people creating their own components; frameworks built on top of Java EE trying to cover this feature; and many other cases.

I didn’t like any solution I found. Some are complex, others are not so elegant. So, I decided to be creative as well and try a simpler solution, easy to understand and change when the time for refactoring comes. It doesn’t mean that I’m proposing something better than other proposals. I’m just proposing something simpler.

In the following example, I check whether an allocated budget is smaller than a budget limit. If not, then a message is shown to the user. The example considers only two fields, but it can scale to as many fields as you wish.

Step 1: create an attribute in the managed bean for each field to be validated:

The attributes below are exclusively used in the multi-field validation.

private BigDecimal validationAllocatedBudget;
private BigDecimal validationBudgetLimit;

In this example, I’m coding inside a class named MBean, annotated with @ManagedBean and @RequestScoped.

Step 2: create a validation method in the same managed bean for each field

This solution considers validation methods implemented in the managed bean instead of implementations of the interface javax.faces.validator.Validator.  You can give any name to validation methods as long as you define three standard parameters, which are the FacesContext, the UIComponent, and an Object representing the value input in the field. Only the value is useful for our validation. See the validation methods:

public void validateAllocatedBudget(FacesContext context, UIComponent component, Object value) {
this.validationAllocatedBudget = (BigDecimal) value;
}

public void validateBudgetLimit(FacesContext context, UIComponent component, Object value) {
this.validationBudgetLimit = (BigDecimal) value;
if(this.validationBudgetLimit.compareTo(this.validationAllocatedBudget) < 0) { throw new ValidatorException(new FacesMessage("Invalid allocated budget!");    } }

The method validateAllocatedBudget doesn't validate the allocated budget. It simply set the attribute validationAllocatedBudget to allow its value to be used afterwards. It is possible because the validation methods are called in the same sequence they are declared in the JSF code. So, you can create a simple method like that for each field involved in the validation. The effective validation occurs in the method validateBudgetLimit, which is the latest called validation method in the JSF file, thus the last one to execute.

It's a good idea to declare attributes and validation methods in the same order of the fields in the form. The order doesn't interfere the functioning of the algorithm, but it helps to understand the logic. On the other hand, the order of calls in the JSF file is important.

Step 3: use the parameter validator to reference the validation method

The methods described above are called from the fields below. Remember that the attributes and methods were implemented in the class MBean.

<h:outputLabel for="allocBudget" value="Allocated Budget"/>
<h:inputText id="allocBudget" label="Allocated Budget"
    value="#{mBean.operation.allocatedBudget}"
validator="#{mBean.validateAllocatedBudget}"/>

<h:outputLabel for="budgetLimit" value="Budget Limit"/>
<h:inputText id="budgetLimit" label="Budget Limit"
    value="#{mBean.operation.budgetLimit}"
    validator="#{mBean.validateBudgetLimit}"/>

That's it! 🙂 Merry Christmas and Happy New Year! o/

Book Review: Programming Collective Intelligence

When the volume of data managed by our application significantly grows, we start thinking about ways of extracting information from the databases. We know that there are a lot of hidden information there, but we don’t know exactly what they are and how to get them. Year after year, people have been working on solutions such as data mining, data-warehouse, business intelligence, and others to figure out those hidden information. At the same time, people also look for ways of using those new information not only for reporting, but also to give constant feedback to the application in order to achieve better results over time. This looks very much to a self-learning mechanism, that we can formally call machine learning.

Nowadays, a new dimension are absolutely relevant when applying machine learning on data analysis: the user’s behaviour and preferences as individuals and as part of the collectivity. This is clearly the influence of social networks on all sort of applications. They are exploring new possibilities of improving the user experience, but how can we be part of that party? Do we need to get a PhD degree to follow the wave? Is it finally possible to make the subject accessible to ordinary programmers? No, we don’t need a PhD degree and yes, it’s finally possible to make our applications smarter. This is what I’ve noticed while reading the book Programming Collective Intelligence, written by Toby Segaran.

At the beginning, I felt uneasy with the chosen programming language – Python – but I was gradually getting used to it because Python is not that hard to understand. In any case, I think this book would reach a larger audience by writing the examples in Java, which is constantly fighting with C for the first position in a well known ranking of popularity. On the other hand, the book targets more websites/portals and we know that Java is not really the first choice when companies decide to develop an application for a larger audience. Independent on the programming language we master, we can always convert what we’ve understood from Python to our favorite language. At the end, the success when implementing those machine learning algorithms come from our ability to solve computational problems, not from our ability of learning new programming languages.

On which concerns the content, the book brings together a large variety of real world problems from websites and services that we frequently use. It concludes reviewing and comparing the described algorithms, helping the reader to easily visualize the applicability of the different methods and to decide which one is the best for the problem we are actually facing.

This book has a new and better approach to present complex subjects such as data mining, machine learning, and statistics. By contextualizing the subject with real scenarios, the author improved the didactic in an unprecedented manner, since this is not the case in academic books. Actually, Programming Collective Intelligence can also be used by undergraduate and graduate students, since there are exercises at the end of each chapter. This is great because sometimes we finish the study of a chapter without realizing what else can be done with those algorithms. This is not common in this kind of book (non-academic) and yet very appreciated.

Choosing Between Vaadin and JSF

With the recent release of Primefaces 3.0, JSF finally reaches an unprecedent level of maturity and utility that puts it face to face with other popular Rich Internet Applications (RIA) options, such as Google Web Toolkit (GWT), ExtJS, Vaadin, Flex and others. This open source project also proved to be very active and in a constant growing path.

I have been working with JSF + Primefaces since October 2010, when I started developing the project JUG Management, a web application conceived to manage user groups or communities focused on a certain domain of knowledge, whose members are constantly sharing information and attending social and educational events. JSF is a standard Java framework for building user interfaces for web applications with well-established development patterns and built upon the experience of many preexisting Java Web development frameworks. It is component-based and server-side user interface rendering, sending to clients (web browsers) pre-processed web based content such as HTML, JavaScript and CSS. My experience on this technology is openly available on java.net.

Meanwhile, I had the opportunity to create a Proof of Concept (PoC) to compare JSF and Vaadin in order to help developers and architects to decide between one of them. Vaadin is a web application framework for RIA that offers robust server-side architecture, in contrast to other Javascript libraries and browser plugin-based solutions. The business logic runs on the server while a richer user interface, based on Google Web Toolkit (GWT), is fully rendered by the web browser, ensuring a fluent user experience.

The result of the PoC was surprisingly interesting 🙂 It ended up proposing both technologies instead of eliminating one of them. I found out, exploring available books, articles, blogs and websites, that despite being able to implement all sorts of web applications, each technology has special characteristics, optimized to certain kinds of those applications. In practical terms, if we find out that JSF is better for a certain kind of application, that’s because it would take more time and code to do the same with Vaadin. The inverse logic is also true. In order to understand that, we have to visit two fundamental concepts that have direct impact on web applications:

  • Context of Use considers the user who will operate the application, the environment where the user is inserted, and the device the user is interacting with.
  • Information Architecture considers the user of the application again, the business domain in which he or she works on and the content managed in that domain.

Notice in the figure bellow that the user is always the center of attention in both concepts. That’s because we are evaluating two frameworks that have direct impact on the way users interact with web applications.

Visiting the concepts above we have:

Environment
Some applications are available for internal purpose only, such as the ones available on the intranet, other applications are used by external users, such as the company website.

Users of internal applications are more homogeneous and in limited number, which means that the UI can be a bit more complex to allow faster user interactions. That explains the fight Microsoft Office vs. Google Docs. The last one is not yet fully acceptable in the office environment because it has less functionalities than Microsoft Office. The latter is, on the other hand, more complex and more expensive. However, a limited number of users to a larger number of features makes acceptable to have some additional costs with training sessions to profit from the productivity features.

A company website targets heterogeneous users in unlimited environments. It is not possible to train all this people, thus simpler user interfaces with short and self-explanatory interactions are desirable.

Considering the environment, we would recommend Vaadin for homogeneous users in limited environments and JSF for heterogeneous users in unlimited environments.

Device
Different devices demand multiple sets of UI components, designed to look great from small to large screens. Fortunately, both frameworks have components to support the full range of screen sizes from regular desktops to mobile devices. The problem is that different devices bring different connectivity capabilities and the application should be ready to deal with short band-width and reduced transfer rates. In this case, Vaadin seems to be more suitable for multiple devices, as long as the variety of devices is not so extensive, because the user interface is rendered locally, using JavaScript, and it has a richer Ajax support to optimize the exchange of application data with the server.

Business Domain
In principle, good quality UI frameworks such as JSF and Vaadin can implement any business domain. The problem is how experienced the team is with the technology or how small is the learning curve to master it. Business is about timing and the technology that offers the best productivity will certainly win. If your team has previous experience with Swing then Vaadin is the natural choice. If the previous experience was more web-oriented, manipulating HTML, CSS ans Scripts, then JSF is recommended.

Content
Content is a very relevant criterion for choosing between Vaadin and JSF. In case the application needs to deal with volumous content of any type, such as long textual descriptions, videos, presentations, animations, graphics, charts and so on, then JSF is the recommended over Vaadin because JSF uses a web content rendering strategy to profit from all content-types supported by web browsers without the need for additional plugins or tags. The support for multiple content is only available on Vaadin through the use of plugins, which must be individually assessed before adoption.

User
Last, but not least, we have the user, who is the most important criterion when choosing a UI framework. We would emphasize two aspects:

  1. The user population: the largest is the target population the highest are the concerns about application compatibility. It must deal with several versions and types of browsers, operating systems, computers with different memory capacity and monitor resolution. All these without failures or security issues. For larger populations, the most appropriate technology is the most compatible one in a cross-platform environment, which is the case of JSF, since it uses a balanced combination of HTML, JavaScript and CSS, while Vaadin relies only on JavaScript and CSS. But shorter populations would have better profit with Vaadin because cross-browser compatibility is and will remain being a very hard work to be done by Vaadin’s development team behind the scene.
  2. User’s tasks: If the application is intensively operated by users then it is expected that it has more user’s tasks implemented. On the other hand, if the application is rarely used or has short intervals of intensive use, then there is a lower concentration of user’s tasks. According to the PoC, Vaadin is the technology that provides the best support on delivering user tasks with richer user interaction because of its fast visual response. JSF is less optimized on which concerns the user interaction.

In conclusion, instead of discarding one of these frameworks consider both on the shelf of the company’s architectural choices, but visit the criteria above to make sure that you are using the right technology to implement the expected solution. A simple way to apply those criteria would be to assign weights to each criterion, according to the project’s characteristics; set which technology is appropriate for each criterion; and sum the weights for each technology. The highest weight elects the technology to be used in the project.

New CEJUG Open Source Project

As I have mentioned yesterday, I’m working on a new project, managed by the CEJUG community, which aims to develop a web application for managing Java User Groups. We put it into production in the first day of the decade, January 1st, 2011, and we made the source code freely available on our java.net project.

The first goal we want to achieve is the definition of what is actually being a CEJUG member. Nowadays, we simply consider all those registered in our technical mailing as members. This simplicity is good for management purposes, but we lose lots of information because of that. We don’t know, for instance, for what reasons a member is leaving the group. Did we do something wrong? What can we do to get better and get members back into the boat? We also noticed that even non-technical people, as entrepreneurs, recruiters, and those who decided to unsubscribe because of too many messages, would like to keep in touch with the group, not necessarily going into technical discussions, but proposing other ways to help. Adopting a separate application to manage subscriptions would help us to collect more feedback and be more inclusive.

Developing our own solution can make data work in our favour and allow our sustained growth. Consequently, we are generating an additional source of knowledge for the community. This application is open source and everyone can run and see how CEJUG works. Beginners will have a solid source to start their studies on the development of Java web applications, experts can help with bug fixing, refactoring, and developing new features according to our issue tracking. Adopted design patterns may be subject of valuable and warming discussions in our community.

Of course the application was developed in Java 😉 We have the duty to write the software architecture document in the coming days, but we can already say in advance what we are using to develop and deploy the application. The presentation layer was developed in JSF 2.0, using the Primefaces component library; the business layer was implemented in EJB 3.1; the persistence layer was implemented in JPA 2.0; data is persisted in MySQL; and everything is running on Glassfish 3.0.1 Application Server. The current version was developed using Netbeans 6.9 due to its productivity when developing JEE applications. We rely on the container to manage security, database transactions, connection pools, and email sessions.

The next step is to document the application, add customisable features and internationalise it in order to spread its adoption by several other JUGs out there. We are looking for contributors and supporters to make this a successful open source project. We hope one day, we could promote interoperability between JUGs through this application, sharing mutual knowledge, events, effort on the growth of the Java platform and the Java community.

You Know What? I Love My Blog

During some procrastination time that I gave to myself last night, I’ve spent some time exploring all posts that I have published on my blog since 2007. I’m talking about 105 posts, an average of 4 per month, which is not that much in comparison to other more popular blogs, but at least I’ve been quite regular over the years.

All these posts tell a lot about my research time in Belgium, thoughts, wishes, ideas, opinions, and much more. It’s so amazing the amount of experiences that I’ve shared with you, the feedback that some of you shared with me. Yeah! For me, post’s comments are the best part of this blog.

I remember how happy I was when my blog was 1 year old with almost 300 unique visitors per month. I thought: “Wow! 300 different people reading my ideas! It’s a lot of people!”. I wouldn’t expect that 2 years later I would have more than 1.400 unique visitors per month. Today, I’m having the same thought I had 2 years ago, since 1.400 visitors is a lot of people too ;). But I know that some of you are laughing because it is still a small number in comparison with other popular blogs, but I’m proud of each one of my visitors, mainly the 450 ones that come here more than once every month.

I wish I could share more with you here because each post represents only 20% of the full experience that I had. Actually, I don’t have any profit from here, making it more like a hobby than a responsibility. I even tried putting some Google advertising on the right, but I’ve got only 3 clicks during these 6 months of exposure, which means absolutely nothing :D. What makes it worth is the possibility to talk to myself, to talk to you like in a restaurant and the feedback I receive when I write technical articles, mostly solving basic problems that annoy a lot of people, and I receive comments from all over the world thanking for the solution I have proposed.

Now, I would like to conclude with a attempt of poem that stays in the subconscious of this blog:

I might regret but I don’t

I might regret doing things not related to my work just to solve other people’s problem, but I don’t because those things taught me many other things that I didn’t expect to learn.

I might regret starting my research so late, but I don’t because pressure is also part of the game.

I might regret allowing my love to spend several weeks far from home, but I don’t because it would be very selfish, these trips are great for her carrier, and I admire her achievements.

I might regret losing contact with some friends that I’ve made here, but I don’t because they proved to be more selfish than the friendly acceptable.

I might regret drinking and eating too much some times, but I don’t because Belgium has the best beers in the world, Europe has the best cuisine and I won’t be here for so long.

I might regret giving up opening a business in Europe, but I don’t because what I’m planning now will help a lot more people than I was planning to help before.

Last but not least, I might regret to be too much optimistic even not archiving many wishes I had, but I don’t because so many miracles have happened in my life, proving that optimism brings most of my wishes and what it doesn’t bring I also gain in terms of lessons learned.

Thank you for your visit(s)!