Mar 05

PrimeFaces Push 2.0

PrimeFaces Push has been around since 3.4 and with 5.0 it has been greatly enhanced thanks to the official partnership between PrimeTek (PrimeFaces) and Async-IO (Atmosphere).

First a few words on Atmosphere; The Atmosphere Framework is the most popular asynchronous application development framework for enterprise Java. The Atmosphere Framework provides the enterprise features required to build massive scalable and real time asynchronous applications using transports like WebSocket, Server Side Events and traditional Ajax Techniques.

  • It’s been proven in production: ReverbWall Street JournalGameDuellVMWareAtlassian and many more
  • Easy to write portable and asynchronous applications with a really simple API for both client and server
  • Supports WebSockets and fallback transports transparently
  • Proven to scale
  • Cloud Enabled!

PrimeFaces Push 2.0 is based on Atmosphere as its predecessor and follows an annotation based approach this time. Old APIs are deprecated and still supported for backward compatibility.

The easiest way to create PrimeFaces Push application is by using the @PushEndPoint annotation. This annotation makes it easy to build application with PrimeFaces Push without the need to interact with Atmospheres more sophisticated API. If you are familiar with the PrimeFaces Push 1.0, this new implementation significantly reduce the number of code required to build a powerful real time application by transparently installing Atmospheres components like heartbeat, idle connections detections, disconnect state recovery etc. It also allows the use of external dependency injection framework like CDI, Spring or Guice.

For example, PrimePush ships with an extremely simple chat application, which support multi room, all transports supported transparently, message caching and more. All of this in less than 100 lines! It is strongly recommended to look at the demos after reading this introduction to see how simple it is to build an application with Atmosphere.

@PushEndpoint
The annotations attributes available are

“path”: The path to the resource.

The default is “/” so if your have mapped the PushServlet to “/*”, all request will be delivered to your annotated class. You can also customize the path. The path value will be used to map an incoming request uris path to an annotated PushEndpoint class.

Class Scope Annotations;

@Singleton
Singleton annotation can be used to force PrimeFaces Push to create a single, thread safe instance of a PushEndpoint annotated classes. For example, if your application set the @ PushEndpoint’s path attribute with using path templates “{something}”, by default a new instance of the annotated classes will be created. When annotated with Singleton, a single class will be created.

Method Scope Annotations
When using the @PushEndpoint annotation, it is recommended to use the following annotations.

@OnOpen
The OnOpen() will be invoked when the underlying connection is ready to be used, e.g for write operations.

Annotated method needs to take the form of

@OnOpen
public void onOpen();

@OnOpen
public void onOpen(RemoteEndpoint r);

@OnOpen
public void onOpen(RemoteEndpoint r, EventBus e);

The RemoteEndpoint represents the physical connection and can be used to write some data back to the browser. The EventBus can be used to fire messages to one or more RemoteEndpoint using regex expressions.

@OnMessage

The OnMessage() will be invoked when a message is ready to be deliver, e.g as a result of a EventBus publish operation or when a browser is POSTing some bytes. The annotation’s attributes available are:
“encoders”: A list of [Encoder]() that will be used to encode the annotated method return value. The returned value of an annotated OnMessage method will be broadcasted to all resource associated with the Broadcaster, associated with this annotated classes. For example, the following will transform an object of type `Response` into a “String” ready to be sent back to the Browser.

public final class JSONEncoder implements Encoder<Response, String> {
    ObjectMapper mapper = new ObjectMapper();

    public String encode(Response s) {
        return mapper.writeAsString(s);
     }
}

Encoders can be chained, e.g the returned value of an Encoder can be used as an input for the next defined Encoder.

“decoders”: A list of [Decoder]() used to decode a broadcasted messages into an object matching the methods signature. For example, a message coming from a Browser can be transformed into an object before it gets delivered to the annotated @OnMessage method:

public class JSONDecoder implements Decoder&lt;String, Message&gt; {

@Override
public Message decode(String s) {
    String[] userAndMessage = s.split(":");
    if (userAndMessage.length <= 2) {
        return new Message().setUser(userAndMessage[0]).setMessage(userAndMessage[1]);
    } else {
        return new Message(s);
    }
  }
}

Decoders can be chained, e.g the returned value of an Decoder can be used as an input for the next defined Decoder. You can annotate several methods with the Message annotation.

@OnClose
The @OnClose() will be invoked when the client disconnect, e.g close the connection, when a network outage happens or when a proxy close the connection. Annotated method needs to take the form of:

@OnClose
public void onClose();

@OnClose
public void onClose(RemoteEndpoint r);

@OnClose
public void onClose(RemoteEndpoint r, EventBus e);

You can only annotate a single method with this annotation.

RemoteEndpoint

The RemoteEndpoint() class represents the remote connection, e.g the Browser. An instance of RemoteEndpoint hold information about the headers, queryString, body, uri, path and path segments that can be used for manipulating the incoming request. If you are familiar with the Servlets “HttpServletRequest”, the RemoteEndpoint can be seen as an improved version. You can also use a RemoteEndpoint#write to write back messages that will be delivered uniquely to the browser.

EventBus
A distributed lightweight event bus which can encompass multiple PushEndpoint instances. The event bus implements publish / subscribe and point to point messaging.
Messages sent over the event bus can be of any type. For publish / subscribe, messages can be published to a Java class annotated with the [PushEndpoint#value]()
using one of the method annotated with [OnMessage](). The EventBus is the recommended way for delivering messages.

Chat Sample

Demo is available at Labs Showcase.

First we annotate the class with the “PushEndpoint” annotation, and define the path to “{room}/{user}”. That means this class can be invoked with URI taking the form of “/room_1/userA”, “/room_2/userB”, “/room_1/userC”. In this example, userA and userC will be part of the same room, being able to chat together, where userB will be in another room. That’s all we have to define to support a multi room application.
We want our class to be stateless, so we use the @Singleton so we are guarantee to have a single instance of this class

The OnOpen annotated method (line 12) will use the EventBus for publishing a message to all connected users. Since we only want users of the same room to
received the message, we retrieve the rooms name by looking up the proper path segment (line 16). Same for the user, we use the path segment to retrieve the value send
by the browser (line 17).

Then we create a simple Message bean. That bean will be delivered to all users of our room. The bean will be delivered via the annotated OnMessage
method. In this particular case, the defined decoder won’t be called as the delivery object is already an instance of Message. We could have called EventBus.publish with a JSON String instead of a Message and the same method (line 27) would have been called. For example, when the browser sent a request, the requests body will be decoded using the JSONDecoder and so the requests body delivered as a Message bean.

Message are delivered to the OnMessage annotated method (line 27). There could be one or more method annotated with the OnMessage annotation. Encoder and Decoder are used by PrimePush to match the appropriate method. For this simple application, we don’t need to manipulate the Message by adding, removing of transforming its content. So we just sent back the Message using our Response bean. That bean will be encoded by the JSONEncoder, e.g its the Response object translated into a JSON String representation, and sent back to the Browser.

Finally, the method annotated with the OnClose (line 21) will be called when the browser close the connection, or when the connection gets broken for any reason. The OnClose method can be used to clean up resources.

Et voila! That’s the only code we need to write the server side of our PrimePush application.

More Demos

  • Counter: Global Click Counter
  • Notify: Push FacesMessages to all connected clients instantly.
  • ViewParam: Push data with a GET request using JSF APIs.
  • Checkin: Created with PrimeFaces Mobile, Push your location to everyone to be displayed on a map.
  • Chart: Keep track of visitor browser stats and push stats data to a chart component real-time.

Posted in Uncategorized | 3 Comments
Mar 03

PrimeFaces Mobile Reloaded

PrimeFaces Mobile has been a mobile add-on for PrimeFaces, as a separate project it reached 0.9.4 however never managed to reach a production ready stage due to various reasons. For PF5 is has been built from scratch, merged in PF5 and finally becomes a first-class citizen in PrimeFaces ecosystem.

New PFM

New PrimeFaces Mobile (PFM) is a UI Kit to create JSF applications optimized for mobile devices. PFM is built on top of jQuery Mobile, a touch-optimized HTML5 UI framework providing support for various platforms.

In addition to the seamless integration with jQuery Mobile, PFM features a Mobile Renderkit for popular PrimeFaces components, ajax framework extensions, mobile ajax behavior events, integrated navigation model, lazy loading of pages, responsive widgets and more. Note that new PFM is not backward compatible with old mobile.

Separate Page vs Responsive Design

There are two popular approaches to mobile web development, separate page approach focuses on mobile devices with separate resources and responsive pages uses same page with media queries. Both approaches have pros and cons over each other and PFM follows an optimized separate page design which suits better for JSF web applications. Responsive widgets such as panelGrid are integrated to deal with different mobile device screen sizes (e.g. smartphone, tablet).

Design Changes

Old approach was too limiting, new PFM follows same design of a regular JSF page with PFM features putting page author back in control. See single page structure for more information.

Mobile Widgets

Each Mobile component is handcrafted with care, if you are already have PrimeFaces experience, thanks to JSF RenderKit feature, using same components with same backend code, you can create a mobile web application in no time. We have provided mobile renderers and widgets for commonly used components such as datalist, menu, panel, accordion, tabview, dialog, growl, forms and many more. Some of the widgets are from jQuery Mobile and we have written various mobile widgets tuned for JSF.

Navigation

Navigations in same xhtml between multiple pages are handled by a specialized navigation handler. Prepending the outcome of the page with “pm:” marks the outcome as a multi page navigation. Regular same domain and external domain navigations are supported as well.

Ajax

jQuery Mobile initializes mobile widgets at page load time automatically for once and widgets have to be refreshed manually if their state changes with ajax e.g. adding new items to datalist otherwise UI doesn’t get enhanced for mobile. This makes jQuery Mobile almost impossible to use in ajax enabled JSF applications.

PrimeFaces Mobile provides ajax update support for all widgets in the mobile renderkit under the hood.

Transitions

If the mobile device has a modern browsers, several cool transitions are supported via the navigation model.

Events

Mobile events are integrated with components as behaviors, best way to describe this is with an example. Check out this DataList demo where swipe event removes an item and taphold shows details in a growl.

Lazy Load

Pages in a multi-page view can be loaded lazily on demand to improve initial page load time. These lazy pages might not even be accessed by the user so loading them with an on-demand approach has a significant speed boost with many pages in a single view. To mark a page to be lazy loaded, enable lazy option.

Pass Through Data

JSF 2.2 brought pass through attributes feature and PFM takes advantage of this. No jQuery Mobile feature is hidden by PFM and can be used by passing the necessary html5 data-* attribute to the component.

Theming

Just like in PrimeFaces Core, PFM theming is built on top of the ThemeRoller, this time the Mobile ThemeRoller.

Demo

New Mobile Showcase is a created from scratch and uses a responsive design.

In addition to framework features, we have also created a couple of apps to show what you can do with new PFM; weather, twitter, news, translate, contacts and push. Push sample is especially important because it is powered by the brand new PrimeFaces Push 2.0, as it deserves a separate announcement, we’ll leave it for later.

Roadmap

New PFM will be available in PF5.

Posted in Uncategorized | 4 Comments
Feb 25

PrimeFaces ELITE 4.0.9 and 3.5.25 Released

New Elite versions are here for Elite and Pro users featuring 25 filed improvements.

Common for 4.0.9 and 3.5.25

4.0.9 Only

Download
Binaries, Sources, API docs and VDL docs are available in PrimeFaces Elite Portal for Elite Subscribers as an official release bundle. PrimeFaces PRO Users can access the files from PRO Portal.

3.5.x Support

As 3.5 release is one year old, Elite support for 3.5.x has been dropped. If you require support on 3.5.x, one option is PRO support however we strongly suggest to upgrading to 4.0 Release.

Roadmap

PrimeFaces 5.0 (Community) is under heavy development and planned to be available in mid April.

Posted in PrimeFaces | Comments Off
Feb 12

JSF is not what you’ve been told anymore

Thoughtworks Technology Radar 2014 has made an “outdated” analysis on JSF with focusing on the abstraction of HTML-CSS-JS which is against modern web development. Notice they use the term “J2EE” that explains a lot already about their research.

The analysis has two major problems, JSF is not what they have been told anymore and second “We recommend teams use simple frameworks and embrace and understand web technologies including HTTP, HTML and CSS.” assumes there is a silver bullet in web frameworks where there is none, but there is a silver bullet for each project type. Things can get really messy for complex form oriented web applications with tons of javascript and css, JSF handles the heavy lifting here. I’m not saying you don’t need to know these technologies, it will be great to have this skill set so that you can tweak things around, it is just working with them directly has a bad impact on productivity and project deadlines. This comes from a team who makes a living with writing javascript, css and html. Regarding state, JSF is a stateful framework by nature and state makes web applications easy to develop with. With improved state management techniques introduced in JSF 2.0+ (e.g. stateless mode, partial state saving), JSF can scale as well.

Back to the analysis, it is not valid because it mentions improvements in JSF 2.0 without knowing JSF 2.2 is out for sometime with killer features catching up with so called modern web development (the one where you write your own javascript, css, ajax, html). Also the analysis claim that JSF is chosen because it is standard, remember what happened to EJB 2.x and why non-standard Spring got popular? Similarly, JSF 2.2 compared to 1.0, is what EJB 3.x to 2.x. Still haunted by bad initial reputation and hated by a group who doesn’t like it because it is standard and their favorite framework is not.

Best way to show how powerful JSF is with an example, following page makes use of bootstrap for css and regular html elements considered as JSF components. Plus we have a PrimeFaces messages and ajax update for messages.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:jsf="http://xmlns.jcp.org/jsf"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
            xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>User Page</title>
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet"></link>
    </h:head>
    <h:body style="padding:20px">

        <form jsf:id="userform">

            <p:messages id="msg" showDetail="true" closable="true" />

            <div class="form-group">
                <label for="firstname">Firstname</label>
                <input id="firstname" type="text" class="form-control" placeholder="Enter firstname" jsf:value="#{userView.user.firstname}" />
            </div>
            <div class="form-group">
                <label for="lastname">Lastname</label>
                <input id="lastname" type="text" class="form-control" placeholder="Enter lastname" jsf:value="#{userView.user.lastname}" />
            </div>
            <div class="form-group">
                <label for="email">Email address</label>
                <input id="email" type="email" class="form-control" placeholder="Enter email" jsf:value="#{userView.user.email}" />
            </div>
            <button type="Submit" class="btn btn-default btn-primary" jsf:actionListener="#{userView.save}">
                Submit
                <f:ajax execute="@form" render="msg" />
            </button>
        </form>
    </h:body>
</html>

Page author is not abstracted from HTML, CSS and Javascript at all. When used like this, JSF does the heavy lifting on backend with value retrieval, validation, conversion, model update, actions and so on except rendering. That is up to the page author. When using a javascript mvc framework like angularjs, knockouts or *js, you need to bind the UI with a server backend using javascript calls, here JSF provides the integration out of the box. Note that, you can use these *js frameworks with JSF as well if you want.

Summary
JSF has been around for 10 years, if it was a bad framework, it will easily get lost in the jungle of web frameworks of Java. Various frameworks has reached their technology peek during past 10 years and started to fade away already. In JSF case, First Facelets saved it, JSF 2.0 fixed it along with JSF 2.2 and then PrimeFaces has given it a popularity boost. Clearly it solves a problem better than others which is creating web applications with an easy, efficient and productive way to meet deadlines. With JSF 2.2, using HTML friendly markup and pass through attributes it caught up with latest trends as well. Add PrimeFaces on top of your stack and get a productivity boost.

Haters gonna hate :)

Posted in JSF | 11 Comments
Feb 05

PrimeFaces ELITE 4.0.8 and 3.5.24 Released

Following the bi-weekly release cycle, new Elite versions of PrimeFaces are now available. In addition to regular maintenance and patches, a popular enhancement request; “nested row expansions in datatable” is now implemented as well. Here is the changelog;

Common for 4.0.8 an 3.5.24

4.0.8

3.5.24

Download
Binaries, Sources, API docs and VDL docs are available in PrimeFaces Elite Portal for Elite Subscribers as an official release bundle. PrimeFaces PRO Users can access the files from PRO Portal.

Posted in PrimeFaces | Comments Off
Jan 23

TreeTable Sorting

As a result of a PRO user request, sorting feature is now available for TreeTable. Usage is same as datatable via sortBy attribute of columns where sorting happens with respect to children starting from root. Default sorting feature is also provided along with custom sorting via sortFunction.

Demo is available at PrimeFaces 5.0 Labs.

Posted in PrimeFaces | 3 Comments
Jan 20

PrimeFaces ELITE 3.5.23 and 4.0.7 Released

This Elite release cycle brings defect fixes and the DataScroller component to 4.0.x line. DataScroller is a new addition in 5.0 and due to high demand from ELITE and PRO users, we have ported it to 4.0.7 as well.

Common Changes for 3.5.23 and 4.0.7

Only for 3.5.23

Only for 4.0.7

Download
Binaries, Sources, API docs and VDL docs are available in PrimeFaces Elite Portal for Elite Subscribers as an official release bundle. PrimeFaces PRO Users can access the files from PRO Portal.

 

Posted in PrimeFaces | Comments Off