Category Archives: AngularFaces

AngularFaces is a JSF component library based on PrimeFaces. It aims to integrate AngularJS as seamless as possible.

Single-Page Applications With BootsFaces

Singe-page applications have become tremendously popular in the last couple of years. They are fast, they are responsive and they can save network bandwidth. The first SPAs that caught the attention of the community were based on JavaScript. So nowadays everybody seems to believe you can’t write an SPA with JSF.

But you can. It’s not even difficult. And it pays: the application becomes much more responsive. This article shows two approaches how to do it with BootsFaces. I’m sure you can do the same with other JSF frameworks like PrimeFaces, too, but I didn’t test it yet.

Currently, there are at least two approaches. You can exploit BootsFaces AJAX to do your navigation, or you can add AngularJS to the equation. The latter approach requires you to learn both Angular and JSF, but it may be useful because it allows you to use client-side AngularJS components.
Continue reading

AngularFaces 2.1.7 published

Fork me on GitHubI made it a habit to publish a new version of AngularFaces every couple of weeks. Today I’ve published AngularFaces 2.1.7 on Maven Central. It should also arrive on JCenter within the next few days. The new version brings a couple of features that make it more apt for big applications.

AngularFaces in the wild

This week I spent a couple of days at a customer’s project, which happens to use AngularFaces. It’s a big project – several hundred JSF views, if I’m not mistaken, so it was really exciting to see how AngularFaces works in such a scenario. The good news is: it works just great. JSF applications become much more responsive with a little help from AngularFaces and Bootstrap. As things go, the sheer size of the application brought a couple of shortcomings of AngularFaces to the light of the day. AngularFaces 2.1.7 addresses an important part of that. I decided not to wait until I solved every point of my backlog, but to publish the version early. The improvements of the current version are clearly worth it.

Download coordinates

Add these lines to your project’s pom.xml:

<dependency>
    <groupId>de.beyondjava</groupId>
    <artifactId>angularFaces-core</artifactId>
    <version>2.1.7</version>
</dependency>

Add this line to your project’s .gradle build file:

compile 'de.beyondjava:angularFaces-core:2.1.7'

Continue reading

AngularFaces 2.1.4 published

Fork me on GitHubToday I’ve published AngularFaces 2.1.4 on MavenCentral. It should also arrive on JCenter within the next few days. The new version fixes a couple of annoying bugs, so I recommend to update soon.

New, improved documentation

There’s also news from the documentation page of AngularFaces. Currently, it’s moving from www.angularFaces.com to https://www.angularFaces.net. The new documentation page is an AngularFaces application featuring BootsFaces 0.6.5, PrimeFaces 5.1 and Omnifaces 2.1. Among other things, running on a web server makes it possible to show interactive live demos instead of static screenshots.

Continue reading

AngularFaces 2.1 Blurs the Difference Between JSF and HTML

I always considered JSF to be to verbose, to ceremoniously. AngularFaces allows you to write JSF pages that almost look like HTML pages.

What it looks like

JSF 2.2 introduced the new HTML5 style of writing JSF pages. Basically, that’s ordinary HTML decorated by a few JSF attributes. AngularFaces picks up this idea and takes it to another level. For example, look at this snippet from my Tetris demo that demonstrates both BootsFaces and AngularFaces 2.1 at the same time:

  <body style="width:1000px" 
        ng-controller="AngularTetrisController" 
        ng-app="AngularTetris" 
        addLabels="false">
    <container>
      <form>
        <tabView>
          <tab title="Settings">
            <b:panelGrid colSpans="3,9">
              <selectBooleanCheckbox value="{{settingsBean.preview}}" 
                                     caption="preview (not implemented yet)" />
              <selectBooleanCheckbox value="{{settingsBean.ignoreGravity}}" 
                                     caption="gravity"/>
              <inputText value="{{settingsBean.numberOfColumns}}" 
                         label="columns (width)"/>
              <inputText value="{{settingsBean.numberOfRows}}" 
                         label="rows (height)"/>
            </b:panelGrid>
            <b:commandButton value="apply changes" ng-show="showApplyButton" />
            <messages showSummary="true" showDetail="true" globalOnly="true"  />
          </tab>
        </tabView>
      </form>
    </container>
  </body>

The embedded preview doesn’t work perfectly because of the scrollbar. Visit http://angularfaces.net/tetris for a better experience.


Continue reading

Final Version of AngularFaces 2.1 Published

Fork me on GitHubAngularFaces 2.1 is more than a bug fix release. It contains a couple of features I deliberately postponed in order to get a thoroughly tested version 2.0 out in times. The list below counts no less than 15 improvements. One of the improvements has nothing to the with code: I put AngularFaces 2.1 under an Apache V2 licence, which is much more liberal than the GPL licence of the previous version.

Examples and code snippets

Pictures say more than words, so let’s start with a couple of screenshots and code snippets. Click the tabs to see the source codes.

ng-table is a great client-side datatable component written in AngularJS. Thus, it’s a natural fit to AngularFaces.

<table ng-table="tableParams" class="table ng-table-responsive">
  <tr ng-repeat="car in $data">
    <td data-title="'Brand'" sortable="'brand'">{{car.brand}}</td>
    <td data-title="'Type'" sortable="'type'">{{car.type}}</td>
    <td data-title="'Year'" sortable="'year'">{{car.year}}</td>
    <td data-title="'Color'" sortable="'color'">{{car.color}}</td>
    <td data-title="'Mileage'" sortable="'mileage'">{{car.mileage}}</td>
    <td data-title="'Price'" sortable="'price'">{{car.price}}</td>
    <td data-title="'Fuel'" sortable="'fuel'">{{car.fuel}}</td>
    <td data-title="'Select'">
      <button class="carFilterButton" jsf:action="#{selectionBean.showDetails()}"
        ng-click="selectionBean.carAsJSon=afToJson(car);">show me!</button>
    </td>
  </tr>
</table>
<input jsf:value="{{selectionBean.carAsJSon}}" style="display:none" addLabel="false"/>
<prime:messages globalOnly="false" />
var app = angular.module('CarShop', ["angularfaces", 'ngTable', 'ngTableExport']).
controller('CarShopController', function($scope, $filter, ngTableParams) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.activeSelections=0;
  
  $scope.select = function(car) {
    console.log(car);
    $scope.selectionBean.carAsJSon=car;
    return true;
  }
  
  $scope.showIfSet = function(ngmodel) {
    if (typeof(ngmodel)=='undefined') {
      return "hidden";
    }
    if (null==ngmodel || ngmodel=="") {
      return "hidden";
    }
    $scope.activeSelections++;
    return "";
  }
  
  $scope.filterBoxStyle=function(){
    var width=400+100*$scope.activeSelections;
    return "" + width + "px";
  }
  
    $scope.tableParams = new ngTableParams({
        page: 1,                  // show first page
        count: 10,                // count per page
        sorting: { brand: 'asc' } // initial sorting
    }, {
        total: $scope.carPool.selectedCars.length, // length of data
        getData: function($defer, params) {
          params.settings().counts=[5, 10, 'all']; // todo: that's a hack!
          var rows = $scope.carPool.selectedCars;
          if (params.filter()) rows=$filter('filter')(rows, params.filter());
          if (params.sorting()) rows = $filter('orderBy')(rows, params.orderBy());
          var page = params.page();
          var pageLength = params.count();
          if (pageLength=='all') 
          $defer.resolve(rows);
          else
            $defer.resolve(rows.slice((page - 1) * pageLength, page * pageLength));
        }
    });

})

Many business applications consist of long forms. AngularFaces simplifies writing such forms by adding labels and messages (including internationalization) automatically. If possible, it validates the form on the client, thus reducing the server load.

     <prime:panel header="If you want to buy this car..."
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="#{carBean.brand}" />
          <prime:inputText value="#{carBean.type}" />
          <prime:inputText value="#{carBean.price}" />
          <prime:inputText value="#{carBean.mileage}" />
          <prime:inputText value="#{carBean.color}" />
          <prime:inputText value="#{carBean.year}" />
          <prime:inputText value="#{carBean.fuel}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="... we need some informations about where to deliver it:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="{{customerBean.lastName}}" />
          <prime:inputText value="{{customerBean.firstName}}" />
          <prime:inputText value="{{customerBean.dateOfBirth}}" />
          <prime:inputText value="{{customerBean.emailAddress}}" />
          <prime:inputText
            value="{{customerBean.iAgreeToTheTermsAndConditions}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="Please confirm you are a human by answering this simple question:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:outputLabel for="captchaField"
            value="{{customerBean.captchaQuestion}}" />
          <prime:inputText required="false" id="captchaField"
            value="{{customerBean.captcha}}"
            ng:captcha="{{customerBean.expectedCaptcha}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:commandButton 
        action="#{customerBean.buy(carBean)}"
        value="Buy this car! (Non-AJAX)" ajax="false"
        styleClass="carFilterButton {{showDetailsClass()}}" ng-disabled="myForm.$invalid"
        style="{{myForm.$invalid?'color:#888':''}}" />
var app = angular.module('CarShop', ["angularfaces"]).
controller('CarShopController', function($scope, $filter) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.doShowDetails = function() {
    if (typeof($scope.customerBean)=="undefined"||
      typeof($scope.customerBean.showDetails)=="undefined") {
      return false;
    }
    return $scope.customerBean.showDetails;
  }
  $scope.showDetailsClass = function() {
    if ($scope.doShowDetails()) 
      return "";
    else
      return "hidden";
  }
  $scope.showFinishedTransactionClass = function() {
    if ($scope.doShowDetails()) 
      return "hidden";
    else
      return "";
  }
  
  $scope.buttonEnabledStyle = function() {
    if ($scope.myForm.$invalid) 
      return "color:#888";
    else
      return "";
  }

});

app.directive('captcha', function() {
  return {
    require : 'ngModel',
    link : function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (typeof(viewValue)=="undefined" || viewValue==null) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        }
        if (viewValue!=attrs["captcha"]) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        } else {
          ctrl.$setValidity('captcha', true);
          return viewValue;
        }
      });
    }
  };
});

The JSF view below shows how to exchange arbitrary data between client and server using the new <ngsync /> tag.

The form contains seven input fields, so the XHTML code repeats itself. I omitted most of the repetitions. The XHTML code uses the new HTML5 style of JSF 2.2:

    <ngsync value="{{staticOptionBean.brands}}"   direction="serverToClient" once="true" />
    <ngsync value="{{staticOptionBean.colors}}"   direction="serverToClient" once="true" />
    <ngsync value="{{dynamicOptionBean.types}}"   direction="serverToClient" cacheable="true" />
...
    
    <!-- ngsync doesn't transport the entire bean recursively, so we have to list each attributes we want to send -->
    <!-- will be fixed in a future AngularFaces version -->
    <ngsync value="{{filterBean.type}}"     direction="serverToClient" cacheable="true" />
    <ngsync value="{{filterBean.brand}}"    direction="serverToClient" cacheable="true"/>
    <ngsync value="{{filterBean.counter}}"  direction="serverToClient" cacheable="true" />
    <!-- end of ngsync workaround -->
    
    <ngsync value="{{filterBean}}" direction="clientToServer" id="filterSyncID" />
    <ngsync value="{{settingsBean}}" direction="clientToServer" id="settingsID" />
    
    <div class="carFilterBox"> 
      <div style="font-weight:bold;font-size:125%">What kind of car are you looking for?
      </div> 
      <div>
        <table style="border-spacing:10px">
          <tr>
            <td width="150px">Brand</td>
            <td width="110px">Type</td>
            <td width="100px">Price</td>
          </tr>
          <tr>
            <td>
              <select id="filterbrand" ng-model="filterBean.brand" ng-options="brand for brand in staticOptionBean.brands track by brand"
                                    ng-change="filterBean.type=''">
                     <option value="">-- choose brand --</option>
              </select>
            </td>
            ...
          </tr>
          ...
           <tr>
            <td>
              <select ng-model="filterBean.yearText" ng-options="year for year in staticOptionBean.years track by year">
                     <option value="">-- choose year --</option>
                 </select>
            </td>
            <td>
              <button ng-show="activateAJAXButton()" class="carFilterButton" jsf:action="index.jsf">update counter
                <f:ajax render="angular" execute="filterSyncID settingsID"></f:ajax>
              </button>
            </td>
            <td >
              <button id="listCarsID" class="carFilterButton" jsf:outcome="table.jsf" >{{filterBean.counter}} cars</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
var app = angular.module('CarShop', [ "angularfaces" ]).controller(
    'CarShopController', function($scope) {
      // This initializes the Angular Model with the values of the JSF
      // bean attributes
      initJSFScope($scope);
      
      $scope.activateAJAXButton = function() {
        if ($scope.settingsBean.updateImmediately)
          return false;
        else
          return true;
      };
      
      $scope.sendFilterToServer = function(newValue, oldValue) {
        if ($scope.settingsBean.updateImmediately) {
          if (newValue != oldValue) {
            try {
              $scope.afSendNGSyncToServer();
            } catch (e) {
              console.log("Ein Fehler ist aufgetreten: " + e);
            }
          }
        }
      };

      $scope.$watch('filterBean.brand', $scope.sendFilterToServer);
      $scope.$watch('filterBean.type', $scope.sendFilterToServer);
      $scope.$watch('filterBean.price', $scope.sendFilterToServer);
      $scope.$watch('filterBean.mileage', $scope.sendFilterToServer);
      $scope.$watch('filterBean.fuel', $scope.sendFilterToServer);
      $scope.$watch('filterBean.color', $scope.sendFilterToServer);
      $scope.$watch('filterBean.yearText', $scope.sendFilterToServer);
    })

Continue reading

AngularFaces 2.1: Apache License V2, AngularJS 1.3 and much more

Yesterday, I’ve published what I hope to be the last release candidate of AngularFaces on Maven Central. Basically, AngularFaces 2.1 RC5 already is the final version. I only called it a release candidate I did a few last-minute changes. I felt the need to run more tests.

AngularFaces 2.1 offers many new features. Today, I’ll present four of them: the new license, AngularJS 1.3, first-class divs and the new AJAX support contributed by Marco Rinck.
Continue reading

How to Modify the JSF 2.2 Component Tree Safely: TagDecorators, TagHandlers and PreRenderViewEvent

Earlier this week Rudy de Busscher published an interesting article about JSF TagHandlers. Today I’d like to go a step further. Let’s have a closer look at them and discuss a second class of JSF tree manipulation classes: the TagDecorators. And, while I’m at it, I’ll also cover to system events, PostRenderViewEvent and PostAddToViewEvent, that can also be used to manipulate the JSF component tree.

Putting it in a nutshell, TagDecorators create JSF tags, whereas a TagHandler can be used to modify tags that already exist. Every JSF application can implement its own TagHandlers or TagDecorators. However, you hardly ever see one of them in the wild.

Obviously most people consider these classes a fairly advanced topic. You can work a long time with JSF without ever seeing one of them. But every once in a while, they come in handy. Rudy’s example is pretty impressive in that regard: sometimes even an everyday task like enforcing user input in capital letters can be implemented simpler and more safely using a TagHandler. AngularFaces uses both TagDecorators and TagHandlers a lot, and JSF 2.2 itself made TagDecorators popular by using them to implement the new HTML5 friendly markup style.
Continue reading

Final Version of AngularFaces 2.0 Published

Fork me on GitHubIt was a hot summer day when I was sitting in the garden and started to dream. Wouldn’t it be nice to add AngularJS to JSF?

Today it’s a sunny day too, I’m sitting in the garden again and AngularFaces 2.0 is finished (it’s even available on Maven Central). Now it’s possible to use AngularJS without abandoning JSF. Even better: it’s very simple, and AngularFaces 2.0 has much more in store for you. It adds a couple of features beyond AngularJS, such as bringing the Bean Validation annotations to the client and helping you to target an international market by reducing the boiler plate code needed to translate an application. AngularFaces is worth a look if you don’t want to involve yourself AngularJS programming.

Continue reading

AngularFaces 2.0 RC4 Published

Fork me on GitHubThe final release of AngularFaces 2.0 is coming near! The latest – and possibly last – release candidate RC4 has been published today. Here’s what’s new and noteworthy about the version:

  • Reduced requirements on the Java version: Java 6, 7 and 8 are supported. The binaries in the distribution folder are compiled with Java 6.
  • You can now use traditional JSF AJAX requests with AngularFaces (although it’s not advisable to do so, because AngularJS doesn’t seem to support this).
  • Improved compatibility to Internet Explorer 11 (and probably older versions as well, but since I’ve updated my PC to the latest version, I can’t really tell).
  • Several common HTML tags can now be used without preceding “h:”.
  • <input> can now be used without “type” attribute. The type is derived from the JSF bean. This isn’t exactly a new feature: AngularFaces supports the same feature for <h:inputText> since a long time. The news is that also the native HTML5 <input> is supported.
  • Client-side error messages use the PrimeFaces design in PrimeFaces views (and the simpler Mojarra design otherwise).
  • AngularFaces input fields can now display boolean JSF bean attributes (and are displayed as checkboxes).

Work on the manual on AngularFaces.com is also progressing nicely. The same applies to the demo applications.

As usual, you find the updated jar file and two demo war files on the AngularFaces dist folder on GitHub.

AngularFaces 2.0.0 RC3 Published

Fork me on GitHubRelease candidate 3 of AngularFaces 2 has been published. Basically, it’s a bug fix release. Here are the release notes:

  • Bugfix: compatibibility with PrimeFaces <prime:datatable>
  • Bugfix: AngularFaces now copes with bean attributes, even if they are Strings (quite a funny bug, if you take in mind Strings are usually tested first).
  • Improved translation support (now includes the attributes “header” and “headertext”)
  • Bugfix: Labels and messages aren’t added automatically if the JSF view designer already defined a label an/or a message
    • In addition, I’ve started to write a tutorial. To read the tutorial, go to AngularFaces.com. The example projects accompanying the tutorial are on GitHub. At the time of writing, the first two steps (“Bootstrapping” and “Labels and Messages”) of the tutorial are finished (plus a couple of sketches of the remaining chapters).

AngularFaces 2.0 Embraces Both HTML5 and PrimeFaces

Fork me on GitHubNow that’s a surprise: AngularFaces becomes more powerful by getting rid of it’s widgets. Quite a development for JSF widget library.

Instead of defining its own widgets AngularFaces 2.0 pimps up widgets provided by other widget libraries. In particular, it adds AngularJS to the new JSF 2.2 HTML5-style widgets. But of course it doesn’t stop there. It’s also compatible to the widgets of Mojarra and MyFaces and to many PrimeFaces widgets. Plus, it allows AngularJS to modify almost every JSF attribute.

Update Sept 16, 2014:
In the meantime I’ve released the final version of AngularFaces 2.0, so you may also be interested in the announcement of the final version.

What’s in store for you

You may already have guessed it: AngularFaces underwent a profound overhaul during the last three weeks. Now it’s much more versatile and much more “Angular”. Let’s summarize the key points of AngularFaces 2.0:

  • It integrates AngularJS and JSF seamlessly. The difference between the two technologies becomes blurry. It doesn’t matter if you modify an attribute on the server side or in your AngularJS code. Both options are available to you. You can even do both, if you insist.
  • In particular, JSF bean attributes are mapped into the AngularJS model. The mapping works in both directions, of course: the next request transfers changes made on the client side back to the server. After processing the user input the server update the AngularJS model again.
  • Bean validation attributes (JSR 303) are evaluated on the client side by AngularJS (resembling the Client Side validation of PrimeFaces).
  • Labels and error messages are added automatically to your input field (unless you tell AngularFaces otherwise).
  • AngularFaces 2.0 makes internationalization much less scary. Translating your application into another language becomes very simple.
  • AngularFaces 2.0 takes a new approach to AJAX. Mind you: you don’t need server side rendering when you’re using powerful Javascript widgets, so I reduced the AJAX responses to the attribute value updates, making them fast and slim.
  • Every AngularJS attribute is treated as a pass-through attribute. You don’t have to declare it explicitly as a pass-through attribute. For instance, ng-show, ng-hide and many more can be used in the JSF file the way you’d use it in a pure AngularJS application.

As a result, AngularFaces views are pretty fast, contain very little boiler-plate code and may look almost like a native AngularJS page. Everybody coming from Javascript programming will get to speed in virtually no time. However, transition from JSF is smooth: you’re free to write a traditional JSF page with a few AngularJS additions.
Continue reading

AngularFaces 2: Even Better Steroids for JSF

Fork me on GitHubAngularJS and other fancy Javascript frameworks stir up the Java world. The Java world has been dominated by server side framework for more than a decade now. Times they are changing. Now everybody’s moving to the client side. The server’s reduced to a faint memory, such as a REST service.

Everybody? Not quite. A lot of developers want to steer a middle course. That’s AngularFaces for you.

By the way, the interest in AngularFaces is tremendous. The AngularFaces announcement has become the second most read article of beyondjava.net, being read a hundred times each day.

So I decided AngularFaces needs a strong grounding. You know, the first version hadn’t really been designed carefully. It just happened. Originally it was just a little experiment. Granted, it works fine, but it’s difficult to add new features to it. The second version is a complete re-write designed for the future. AngularFaces 2.0 has a lot of advantages over it’s predecessor.

And the nice thing about AngularFaces 2.0 is it’s already available as a preview version on GitHub.

Update Sept 16, 2014
Actually, the final version of AngularFaces 2.0 looks completely different from the AngularFaces 2.0 I envisioned four months ago. It doesn’t define components, it’s a plugin to existing components. In other words, it adds functionality to most components of Mojarra, MyFaces, PrimeFaces and probably (although I haven’t run a test yet) to most other JSF widget libraries. Nonetheless I think the ideas described in this article are good ideas worthy to be implemented. The AngularFaces widgets have moved to a project called AngularFacesWidgets.
Have a look at the tutorial at AngularFaces.com if you’re interested in AngularFaces 2.0 and above.
Continue reading

AngularFaces Mentioned by Oracle’s Aquarium

It’s astonishing how much attention BeyondJava’s AngularFaces project gets. It has been mentioned in the November issue of the JSF central postcast – at a time when AngularFaces was a far cry from being mature. Last Thursday Reza Rahman mentioned AngularFaces in Oracle’s Aquarium (JSF + AngularJS = AngularFaces?).

I’m very pleased by your tremendous feedback. It’s a great motivation to carry on.

Just in case anyone of you is puzzled by the apparent lack of progress in the repository: progress is there, it just happens in another repository. When I wrote BabbageFaces – which basically was meant to be a small exercise – I noticed many folks in the JSF community want to reduce network traffic. BabbageFaces is nice, but it isn’t compatible to AngularFaces, and it won’t be.

So I decided to tackle the challenge from another angle.
Continue reading

Announcement: AngularPrime/Dart

Fork me on GitHubLast week I have begun to port Rudy de Busscher’s Javascript widget library, AngularPrime, to Dart. AngularPrime/Dart aims to take PrimeUI and AngularJS to another level. It’s going to simplify Single Page Applications considerably. The applications have the same look and feel as PrimeFaces or PrimeUI applications, have the simplicity of AngularPrime and of course the wealth of features of AngularJS. Or rather, the wealth of features of AngularDart, the Dart port of AngularJS that’s currently slightly more advanced than AngularJS itself.

At the time of writing I’ve finished half a dozen components.
Continue reading

BabbageFaces Now Supports Full Page Submits

Fork me on GitHubBabbageFaces – the framework I’m currently developing to reduce the size of AJAX responses – has learned a couple of new tricks during the last weeks. Now it supports and optimized full page submits. This is good news to JSF programmers because it allows to simplify programming even further. You can safely use update=”@all” with <p:commandButton> and <p:commandLink> without sacrifying performance.

Continue reading

Inside JSF: Understanding and Optimizing the AJAX Response

Fork me on GitHubDid you ever look at your JSF applications AJAX responses? Closely?

I didn’t expect them to be interesting. After all, AJAX responses simply bring HTML code to the client, and we all know what HTML code looks like. That’s what I thought when I started the BabbageFaces project optimizing JSF AJAX. But then I found some inner structure I didn’t expect.

Actually, even the PrimeFaces team didn’t expect the full richness of this inner structure. Strictly speaking PrimeFaces 4 isn’t fully compatible to the JSF 2.2 specification. That doesn’t affect most PrimeFaces applications. But it does affect my project: BabbageFaces doesn’t require PrimeFaces at all, but if you use it with PrimeFaces, you have to use the upcoming version 5 of PrimeFaces.

This article serves two purposes. The major part of this article explains the features of JSF 2.2 AJAX responses. It also explains how BabbageFaces works and how it uses advanced JSF 2.2 features to optimize the AJAX client, both improving the user experience and reducing network load.
Continue reading

BabbagesFaces: Fast and Efficient JSF AJAX Made Simple

Fork me on GitHubJSF is a great framework. However, it could be a whole lot simpler. That’s what BabbageFaces does for you: it’s a JSF 2.2 plugin addressing a particularly nasty issue. It allows you to reduce the complexity of JSF views, making JSF more efficient along the way. Every once in a while it even fixes an AJAX error.

Continue reading

Using Javassist To Implement Mixins or Traits in Java

Many components of the AngularFaces library share common properties and methods. Some of these methods are simple, some of them are complex. I’d like to move them to another class instead of implementing them multiple times. Unfortunately the component classes don’t derive from a common base class. That’s nothing I can fix. That’s just the way PrimeFaces and Mojarra are designed. So I can’t factor out the common traits using inheritance.

The second common approach, the delegation pattern, certainly works. However, it amounts to writing a lot of boiler plate code. At first glance, this isn’t much of a problem since most modern IDEs offer a refactoring tool to implement the boiler plate code. Eclipse is going to help you. But as Venkat Subramaniam points out in his Java One 2013 talk (roughly at 31:30), this approach has severe disadvantages. Adding a method to the base class forces you to add it to every class using the base class as a delegate. The same applies to removing a method or changing a methods signature.

So what we really want to have is something like Scala’s trait or Groovy’s @delegate annotation. This is often referred to as “mixin”.1 Basically, it’s a kind of multiple inheritance, but typically mixins or traits are defined in a slightly less anarchic way. For instance, the famous diamond inheritance problem of C++ simply can’t occur.

However, porting AngularFaces to another JVM language might reduce the library’s attractiveness to other developers, not to mention it’s versatility. Virtually every JVM language features nice integration with Java, but few JVM languages play nicely with other JVM languages other than Java.

Some time ago I’ve seen a surprising approach to implement mixins using AspectJ. But again, AspectJ might repel some Java developers and adds to the tool stack.

Another possibility is to wait for Java 8. Defender methods deliver most of the functionality I’m missing. But I don’t know how long it takes until OpenShift – where I host the AngularFaces showcase – is going to support Java 8, so this isn’t an attractive option, either.

So it’s tempting to abandon all hope. But wait – what about Javassist?
Continue reading

  1. There are subtle differences between the terms “mixin” and “trait”. However, the differences aren’t that big, so I’m using both terms as synonims in this article.

AngularFaces: Synchronize Angular Models With JSF Beans

Fork me on GitHubThis component is different.

Thus far every AngularFaces component was essentially a JSF component with some AngularJS sugar on top of it. <a:sync> works the other way round. It enables a pure AngularJS application to benefit from the JSF engine. Every time a JSF request is submitted, <a:sync> moves parts of the AngularJS model to the JSF bean’s attributes. A little later, when the response is send to the client, <a:sync> injects JSF bean attributes into the model of AngularJS.

Strictly speaking, the “a” prefix of the library makes <a:sync> sort of a misnomer. It’s not about doing thing in an asynchronous way. It’s about synchronizing AngularJS models with JSF beans.

Update Sept 16, 2014
AngularFaces 2.0 takes a different – and better – approach to adding fuctionality to JSF. This article describes the older version AngularFaces 1.0. However, <a:sync> is also part of the new version. Now it’s called <ngsync>, and synchronizing data from the client back to the server has been postponed to version 2.1 of AngularFaces. Have a look at the tutorial at AngularFaces.com if you’re interested in AngularFaces 2.0 and above.

Continue reading

PrimeFaces 4.0 Search Expressions – And How to Extend Them

While I like JSF as a component framework, I always feel JSF becomes a less attractive once IDs come into play. The most common playground for IDs are AJAX requests, but they’re also used in watermarks, sliders and even simple labels and error messages.

The problem with IDs is they aren’t really flexible. They frequently don’t survive simple operations such as refactoring the JSF code and copying fields. That’s one of the reasons why I began to develop my AngularFaces library. But you don’t have to go as far as to change your framework. The PrimeFaces JSF library has been offering improved search expressions for some time now, and they are even going to improve them with the upcoming version 4.0.

Yet still, you can even go further. This article shows you how it’s done.
Continue reading