The Holy Java

Building the right thing, building it right, fast

Archive for November, 2007

The Ultimate Web UI Framework

Posted by Jakub Holý on November 25, 2007

Recently I have found myself in the need of a framework for creating rich, responsive and highly interactive web-based user interfaces that would ideally be easy to use and fast to learn. I was basically only interested in the view part of the presentation tier, that’s the UI running in user’s browser and interacting with him/her. I had no preferences regarding the ‘M’ and ‘C’ of MVC, in other words the server-side of the presentation-tier.

After doing some research I’ve found a couple of candidates:

  • Echo2
  • Google Web Toolkit (GWT) with the GWT-Ext components library
  • JBoss RichFaces (it is based JSF; perhaps use with Seam)
  • OpenLaszlo/Flex
  • Others: Wicket, Grails, Struts 2, …

The listed frameworks are quite different one from another. We can categorize them in a couple of ways w.r.t. different aspects:

Client-side versus server-side interaction handling
Does the presentation logic that controlls user interaction and UI changes run on the client and only sends/receives data when it’s necessary or does the presentation logic run on the server-side with (nearly) each action of the user resulting in a request?
Implementation language: Java, XML+JavaScript, html/css/js, other
Is the interface described using the classical combination of JSP, HTML, CSS and Javascript, or is it described in pure Java, or does it use the combination of XML and JavaScript, or even something else?
Interaction model: event-based or request-driven
And so on…

Regarding the frameworks, which I’ll describe later on, we can say:

  • Client-side: GWT and OpenLaszlo or Flex run mainly on the client while the others more on the server
  • Language: With GWT & Echo you define your UI in pure Java, with Flex/OpenLaszlo in xml+js, JSF uses the classical JSP & co. combination.

Introducing the frameworks

Disclaimer: I’m no master of these frameworks. The information below is a compilation of opinions of their users and info from various sources like documentation, articles and blogs.

All of these frameworks are open-source.

Echo 2 (demo)

  • UI defined by Java classes as with Swing, event-based
  • runs on the server-side and most user actions result in a request being sent to the server
  • commercial IDE for – I suppose – graphical design of the UI; but you can code it without that in any editor

Pros

  • UI defined in Java
    • => you don’t need to spend weeks learning JSP, JSTL, custom taglibs, HTML, CSS, JavaScript. This makes also developers cheaper.
    • => support for refactoring
  • A number of existing components
  • Nice look&feel
  • Only the code and content that is currently actually needed is downloaded to the client, other parts are downloaded as needed via Ajax – this should make the download of an echo 2 application and its start faster but may slow it later when you may need to wait for an additional stuff to be fetched
  • Backed by a commercial company, seems to be pretty alive with a reasonable community

Cons

  • Runs mainly on the server-side, many user actions result in a request, which makes it slower and less responsive. For example switching a tab in the demo took usually around a second (this may be given by the current load, limits etc.of the server, but frameworks that handle this completely on the client side don’t have any such problems)
  • the Eclipse-based EchoStudio 2 IDE for rapid visual development of Echo 2 UI is commercial though you can, of course, code your ui by hand in any editor
  • A new API to learn – it could be perhaps more similar to Swing API to make it easier for newcomers

Google Web Toolkit (GWT) with GWT-Ext components

As with Echo 2, you create your UI by writing Java classes, using a Swing-like API. But here the UI components (widgets) you’ve written are compiled at the development-time into html/css/javascript.

Pros

  • Pure Java development => less knowledge required, support for refactoring – as with Echo 2
  • The components (widgets) are pure html/css/javascript and can be embedded into any page, even a static one or one created via another framework (you could e.g. place the component on a JSF page)
  • Runs on the client-side – a GWT application is a true rich UI running in the user’s browser, the presentation flow and user interaction is handled locally as much as possible. The server-side is only called when data interchange in necessary.
  • Backed by Google; no need to say more :)
  • Steap learning curve – according to some you can start writing reasonable GWT applications in a week
  • A rich and growing set of components provided within GWT-Ext
  • Debugging: You can run the UI in a hosted mode within a special browser provided by Google without compilation into html/…, thus being able to use Java debugger etc. for it

Cons

  • Java: provides only a subset of java.lang and java.util. Currently only works with Java 1.4, the upcomming GWT 1.5 will only work with Java 5.0..
  • Closed-source Java to html/css/js converter
  • All the application files are donwloaded at once to the client, which can make its start slower; on the other hand Google is very good in optimizing the file sizes  and the generated code from the donwload time perspective.
  • According to some people it isn’t a good idea to have all the presentation logic on the client side for security reasons

JBoss Rich Faces (for JSF)

 RichFaces is a JavaServer Faces (JSF) component library that heavily uses Ajax. But it goes beyond that and makes it possible to add Ajax support to existing components/applications, provides skinnable components, makes it possible to pack .js and .css into JAR archives together with your components.

JSF is "the standard", component and event-oriented presentation framework. To get the maximum out of it, you can use RichFaces together with Facelets (see my Facelets post) and the application framework JBoss Seam, which provides among others integration with EJB, business processes, and the "conversation context".

Pros

  • Builds on JSF, the "new" standard (JSR #127, v.1.2 #257, the new v.2.0 #314) for creating web UI and pluggable components. JSF can be also used for creating portlets (see JSR #301 – Portlet Bridge Specification for JavaServer Faces) though I don’t know how much is this supported by RichFaces itself
  • RichFaces components and Ajax-support can be easily added to existing JSF applications and pages

Cons

  • Runs on the server-side, most user actions result in a request, either via GET/POST or in the background via ajax.
  • It carries all the disadvantages of JSF (search on the web…)
  • You need to know JSF, html, css and either Facelets or JSP, JSTL etc.

OpenLaszlo or Flex 

Both these tools/frameworks let you create rich UI in Flash (or also DHTML with O.L.) using XML and JavaScript and both have no relation to Java – they provide for creating rich client-side applications that communicate to the server-side using some standard mechanism, for example web services or RESTful servlets returning xml or json.

OpenLaszlo 4.x has the advantage of being able to compile the UI not only into Flash but also into DHTML (html/css/javascript). See OpenLaszlo demos.

Adobe Flex is development framework for creating rich Internet applications using variations of XML (MXML) and JavaScript (ActionScript). The Flex SDK is open-source, the Eclipse-based Flex Builder IDE for rapid development of Flex applications is commercial. The famous author of Thinking in Java, Bruce Eckel, promotes Flex and mentiones OpenLaszlo (recommended reading!; check also the comments).

Pros

  • Very rich UI with advanced capabilites regarding e.g. multimedia and vector graphics
  • Runs on the client side and only contacts the serer-side when necessary to get or send data
  • You only need to learn the framework’s xml and javascript, not the full stack of jsp/jstl/css/….
  • Can use back-ends not written in Java => encourages writting you server-side components in such a way that they can be used and reused in multiple ways. Because it isn’t bound to any particular server-side framework or language, you can you is with any you like.
  • There is a fair number of existing components for both Flex and OpenLaszlo (especial
    ly for Flex)
  • Flex is faster and richer than OpenLaszlo
  • You can nest Flex application into a page and integrate with it

Cons

  • You need Flash plugin in the browser to use the UIs. OpenLaszlo can generate dhtml, but I’m not sure whether it’s mature enough.
  • The startup may be a bit slower
  • Flesh isn’t HTML and thus search engines like Google cannot search and index it so well
  • an IDE with visual UI builder and other support either isn’t available or only for a fee (though people say you don’t really need one)
  • Flex isn’t completely free: is some cases, like using Flex Data Services on multiple CPUs, you must pay (but see the LGPL Granite DS)

Others: Wicket, Grails, Struts 2, …

There are certainly other popular frameworks that may support rich user interface. But I’ve deliberately limited myself to the most famous ones and those that are somehow unique and catched my attention.

Criteria for  evaluating web UI frameworks (draft)

The following criteria could/should be used when deciding wheher a particular framework is suitable for an application and the problem it tries to solve. 

Practical

  • availability of developers familiar with the framework
  • tools support
  • existing components

Learning & using

  • support community
  • learning curve
  • documentation
  • rapid development: can write UI fast?
  • ease of use – principles like DRY, convention over configuration etc. that make it’s use easier

Non-functional characteristics

  • flexibility (let me do st. unexpected that I really need)
  • performance, scalability
  • maintainability; refactoring supported?
  • suitable for large enterprise apps with many "pages"?
  • user experience (rich <> ajax)

Other

  • evolution: has it momentum? new versions backward compatible?
  • stable and proven framework?

Note: diffferent frameworks are suitable for different cases; there is no single framework that’s the best fit for any problem. Still we would certainly like to keep the number of frameworks used as small as possible.

Summary/Conclusion

I was searching for a framework that would allow me to create rich user interfaces that are very interactive and responsive and don’t load the server too much. After examining some favourite frameworks I’ve decided for a few that I’d like to try.

Different applications have different architectural and UI requirements, which makes some frameworks suitable for the problem at hand and some not. But when we limit ourselves to a user-interaction centered application, I think that the classical frameworks like Struts 1/2 and JSF just aren’t suitable, even with Ajax. They place to much burden on the server, aren’t responsive and interactive enough and don’t always provide for rapid creation of rich interfaces. I like the idea of user interface running on the client, as with GWT or OpenLaszlo, and having only the business logic on the server-side. This provides for richer and more responsive UI and places less burden on the server, which can thus serve more clients. Ganesh Prasad promotes such a solution in his blog entry "Life above the Service Tier" with the term Service-Oriented Front-End Architecture (SOFEA), a rich UI above a service layer. I indeed recommend reading it.

To conclude: I’d use either GWT or OpenLaszlo (or maybe Flex) when a true rich user interface is required and/or when this of technology and approaches isn’t against internal standards of the company. If a more traditional approach is necessary, I’d prefer RichFaces because JSF is quite popular and standard.

Links and resources

  •  Adobe AIR (former Apollo) – runtime for running web 2.0 and Flex applications as desktop application, with full integration, access, and support for running offline.
  • Google Gears – "an open source browser extension that enables web applications to provide offline functionality" by providing JavaScript API for storing & serving resources (html, images…) locally, acess to an embedded database, and more.
  • Microsoft Silverlight – multiplatform and multibrowser plugin and runtime for running rich .NET applications from within a browser. It competes with Flesh (hence Flex) and the new mysterious Sun’s JavaFX.

Articles, blogs etc.

Posted in j2ee, Languages | Tagged: , , , | 8 Comments »

Introducing Facelets

Posted by Jakub Holý on November 19, 2007

You might have already heard about Facelets (docs), a library for Java Server Faces (JSF), and wondered why it is popular and what it is good for. I’ve wondered too and now I want to share the answers with you.

Warning: I’m a novice to Facelets and some things may be not completely exact. 

Facelets is

  • an alternative, non-JSP view technology and handler for JSF that gives you the power of JSP while avoiding its inherent problems with JSF
  • a simple templating system similar partly to Tiles
  • a way to use newer JSF (1.2) in an older servlet container (below JSP 2.1) that couldn’t support it otherwise
  • it’s compatible with JSF 1.2 and can be used with Sun’s RI or with Apache’s MyFaces

 Facelets is an alternative, non-JSP view handler

It’s very difficult and error-prone to use JSP to define JSF views because they’ve different life-cycles and just don’t fit together well. Result: you must enclose most non-jsf content by f:verbatim and you may be sometimes surprised by content appearing in a different order in the resulting html. See Improving JSF by Dumping JSP by Hans Bergsten.

Facelets were designed as a view technology for JSF and let you define your views in XHTML and mix freely JSF components, xhtml, unified expression language (including custom functions), and a subset of JSTL (core, functions; for example c:if). All of these are translated into a jsf component tree and go through the same life-cycle. No more problems with mixing jsf components and jsf-unaware html: everything is a part of a component with Facelets.

You can defined your views in .xhtml, or, if you want to keep your IDE’s support including autocompletion, you can use JSPX with Facelets (JSPX = JSP with xml syntax; Facelets require its view definition to be a valid xml).

Example – mypage.jspx:

<?xml version="1.0" encoding="UTF-8" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core"
  version="2.0">
   <html xmlns="http://www.w3.org/1999/xhtml">
      <head><title>JSPX Facelets example</title></head>
      <body>
         <ui:composition>
            <h:messages id="messages1" styleClass="messages">
            #{myManagedBean.sayHello}
         </ui:composition>
      </body>
   </html>
</jsp:root>

Facelets as a templating system

The framework provides a couple of tags that let you create and apply page templates: in a template you specify variable, page-dependant content (perhaps with some default content) using ui:insert name="…", in a page (a template client) you enclose the code that shouldn’t be ignored by ui:composition template="<template file path>"  and finally use some ui:define name="…" to define content for the template’s ui:inserts. This let you easily define e.g. common layout in for your pages.

The description is a very brief and simplified one, refer to the Facelets templating docs to learn about its full power.

And even more…

 Easy creation of composite components

Another distinct advantage of Facelets is that it let you create extremely easily components composed from other components: you just define the composition as another xhtml fragment, define the tag to use for it in a Facelets tag library. An example from the Facelets docs:

Tag description from a Facelets taglib file mytags.taglib.xml (referenced by the context parameter facelets.LIBRARIES):

<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "facelet-taglib_1_0.dtd">
<facelet-taglib>
<namespace>http://example.com/my</namespace>
<tag>
<tag-name>echo</tag-name>
<source>tags/echo.xhtml</source>
</tag>

<facelet-taglib>

And the tag definition – tags/echo.xhtml: 

<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets">
<span class="message">#{msg}</span>
</ui:composition>

 Called as (notice how the varaible msg is passed; the namespace ‘my’ is defined by: xmlns:my="http://example.com/my&quot;):

<my:echo msg="#{bean.warningMessage}"/>

Debugging/devel support 

By setting the context param facelets.DEVELOPMENT to true you instruct Facelets to display a pretty useful information whenever a processing error occures, inlcuding the exact location of the error in the xhtml/jspx. The developers have indeed taken care of providing useful output here!

When using Sun’s RI, you may also want to set the context params com.sun.faces.validateXml and com.sun.faces.verifyObjects to true.

Deploying Facelets application to JBoss 4.0.4

Notice: I’ve tried Facelets 1.0.10, but the latest version is 1.1.14 – you may prefer to try that one. 

You need the following libraries in your WEB-INF/lib (versions may differ): jsf-facelets-1.0.10.jar, el-ri-1.0.jar, el-api-1.0.jar, jstl-1.1.2.jar (all included in the Facelets download).

You must not have there either Sun’s RI of JSF 1.2 (jsf-api, jsf-impl) or MyFaces libs (myfaces-api-1.1.2-SNAPSHOT.jar, myfaces-impl-1.1.2-SNAPSHOT.jar). The RI requires Java 1.5 that may not be possible to use for political reasons and myfaces conflict with myfaces libraries bundled with JBoss in <jboss>\server\default\deploy\jbossweb-tomcat55.sar\jsf-libs.

Note: If Tomcat  cannot find the myfaces TLDs and complains about unmapped namespace http://java.sun.com/jsf/html or core, extract the TLDs from the myfaces jars and put them somewhere under your WEB-INF.

That’s all – assuming you’ve set your web.xml and faces-config.xml correctly. In web.xml you don’t need anything special outside of normal JSF configuration (Faces servlet and startup listener) unless using extension mapping instead of the prefix /faces/* – in that case you must also specify .xhtml (or .jspx) as the default suffix of JSF pages using the context param. javax.faces.DEFAULT_SUFFIX. In faces-config.xml you need to set Facelets as the view handler (you may define for which resources it should be used, delegationg all others to the default jsp view handler, via its context param. facelets.VIEW_MAPPINGS):

<application>
   <view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
</application>

 That’s all folks, thank you for attention!

Posted in j2ee, Languages | Tagged: , , , , , | 2 Comments »

Truncating UTF String to the given number of bytes while preserving its validity [for DB insert]

Posted by Jakub Holý on November 2, 2007

Often you need to insert a String from Java into a database column with a fixed length specified in bytes.
Using

string.substring(0, DB_FIELD_LENGTH);

isn’t enough because it only cuts down the number of characters but in UTF-8 a single character may be represented by 1-4 bytes. But you cannot just turn the string into an array of bytes and use its first DB_FIELD_LENGTH elements because you could end up with an invalid UTF-8 character at the end (one that is represented by 2+ bytes while only its 1st byte fits into the field). There are two solutions for truncation the string in such a way, that it has at most DB_FIELD_LENGTH bytes and is a valid UTF-8 string.

Approach 1: Replace the invalid trailing byte(s) with a ‘rectangle’

This is as simple as:

int maxLen = DB_FIELD_LENGTH-2;
string = new String( string.getBytes("UTF-8") , 0, maxLen, "UTF-8");

The new String constructor will automatically replace any invalid character (i.e. incomplete utf-8 char; we may only have one at the end) with the character \uFFFD, which looks like an empty rectangle. This character requires 3 bytes in utf-8 – therefore we decrease DB_FIELD_LENGTH by 2; the resulting string will have either exactly maxLen bytes if its last byte(s) is a valid utf-8 character or maxLen+2 bytes if it isn’t valid and this 1 byte was replaced by \uFFFD (3B).

Approach 2: Skip the invalid trailing byte(s) altogether

If you don’t want to have the rectangle character in the place of a split multibyte character, you must do yourself what the String constructor does internally, in a bit different way:

import java.nio.*; import java.nio.charset.*;
Charset utf8Charset = Charset.forName("UTF-8");
CharsetDecoder cd = utf8Charset.newDecoder();
byte[] sba = string.getBytes("UTF-8");
// Ensure truncating by having byte buffer = DB_FIELD_LENGTH
ByteBuffer bb = ByteBuffer.wrap(sba, 0, DB_FIELD_LENGTH); // len in [B]
CharBuffer cb = CharBuffer.allocate(DB_FIELD_LENGTH); // len in [char] <= # [B]
// Ignore an incomplete character
cd.onMalformedInput(CodingErrorAction.IGNORE)
cd.decode(bb, cb, true);
cd.flush(cb);
string = new String(cb.array(), 0, cb.position());

The string will end with the last valid character in the given range.

Approach 3: Manually remove the invalid trailing bytes

As you can see, the approach 2 requires quite lot of coding and method calls. If you know the details of UTF-8, namely how to distinguish an invalid byte or byte sequence then you can simply truncate the byte array and then remove/replace the invalid bytes. I’d be glad for the code :-)

Posted in Databases, Languages | Tagged: , , , , | Comments Off