Category Archives: simpliying JSF

What’s New in BootsFaces 1.0?

BootsFaces 1.0 has been released. Actually, we’ve already published the first bugfix release, BootsFaces 1.0.1. I was a bit shy to proudly announce the 1.0.0 version because we had so many obstacles to overcome. Apart from the usual obstacles like exhausting projects at work (and they were exhausting this time!), there were also the earthquakes in Italy, which kept at least one of our team members busy, although they didn’t suffer any physical harm.

Be that as it may, BootsFaces 1.0 (and 1.0.1 in particular) is a great step to maturity. It’s the first version we officially call “production-ready”. Truth to tell, we were always convinced you can safely use BootsFaces in production. But most versions we’ve published in the past focused on features. This time we tried to focus on stability instead of new features when we prepared the 1.0 version. I counted 26 bugfixes that were important enough to open a bug ticket. Plus, almost twenty minor enhancements and three new components. However, we also added one or two major improvements, such as adding support for both horizontal and inline forms.

Download coordinates

Before starting the long list of details, let me provide you with the download coordinates:

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

<dependency>
    <groupId>net.bootsfaces</groupId>
    <artifactId>bootsfaces</artifactId>
    <version>1.0.1</version>
    <scope>compile</scope>
</dependency>

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

compile 'net.bootsfaces:bootsfaces:1.0.1'

The BootsFaces project comes with both a Gradle build file and a Maven build file. The Maven pom.xml is the easy way to get started and should suffice for most purposes. Only if you want to tweak and optimize BootsFaces, you need the Gradle build. In particular, the Maven build doesn’t generate the CSS and JS files itself, but relies on the output of the Gradle build. By the way, that’s the reason why we keep the generated file in GitHub.

In any case, the URL of the repository is https://github.com/TheCoder4eu/BootsFaces-OSP.

Update Dec 27, 2016: Bugs

During the last couple of days, we’ve found and fixed a couple of bugs. If you happen to run into a bug, check our bug tracker if we’ve already solved the bug, and check out the sneak preview version of BootsFaces 1.1.0-SNAPSHOT. Strictly speaking, this version is not intended to use productively. Use at own risk. Of course, BootsFaces is published under an Apache V2 license, so every version of BootsFaces is published on an “as-is” basis, without any warranties. The difference between the snapshot and the final version is that we’ve tested the final version more intensively.

Continue reading

How to Use Advanced Search Expressions with Mojarra, MyFaces or OmniFaces

I consider the advanced search expressions of PrimeFaces and BootsFaces tremendously useful. In particular, @next and @previous make it a lot easier to move input fields around on the screen or from one screen to another during the prototype phase of your project. The only problem with the search expressions is that they only work with PrimeFaces and BootsFaces components. If you also use the base components like <h:inputText />, you back to using ids and the four search expressions defined by the JSF standard (@form, @this, @all and @none).

JSF 2.3 may change that. It’s not settled yet, but there an ongoing discussion to include a similar search expression framework in JSF 2.3.

But what about now?

That’s a bright look-out. Problem is, most of us live don’t live in the future. Quite the contrary, from a technical point of view, most of us developer live in the past. I know many projects currently developed with JavaEE 6, a technology presented seven years ago. In other words: even if Oracle is going to accept our proposal in JSF 2.3, that doesn’t help many developers before 2020. So the challenge is to find a way to add the search expressions to JSF 2.0, 2.1, and 2.2.

How to do it

Cutting a long story short: I’ve found such a solution. It’s not exactly elegant, but it does the trick. The nice thing about my solution is that you don’t need to add the BootsFaces library to your project just to use the search expressions. You only need a single package of BootsFaces. Most likely I’m going to publish this package on Maven Central after running some more tests.

Actually, it’s fairly simple to use the search expressions in non-BootsFaces components. Every attribute of a JSF component supports EL expressions. This includes the attributes for, render and execute. So I’ve defined a JSF bean allowing you to resolve the advanced search expressions:

<h:message for=
 "#{searchExpressionResolverBean.resolve(component, '@previous')}" />

Of course, that’s a far cry from what we really want:

<h:message for="@previous" />

Luckily, there’s a second option we can use to simplify things. JSF allows us to register a “facelets decorator”. This class is called when the XHTML file is loaded and parsed. The facelet decorator can modify each facelet and replace it with another facelets. That’s how the HTML5 friendly markup of JSF 2.2 has been implemented. The JSF 2.2 recognizes an HTML input tag and replaces it with a JSF h:inputText if there’s an JSF attribute. We can use the same trick to replace the string "@previous" by "#{searchExpressionResolverBean.resolve(component, '@previous')}"". In other words, our decorator translates the search expressions to something core JSF can understand at load time.

How to activate the search expressions

Unless you’re already using BootsFaces, copy the folder https://github.com/TheCoder4eu/BootsFaces-OSP/tree/master/src/main/java/net/bootsfaces/expressions to your project. This folders contains the entire search expression resolver library, and it also contains the decorator in a subfolder.

If you want to benefit from the simplified syntax of the decorator, you have to activate it by adding a few lines to your project’s web.xml. If you don’t use BootsFaces, that’s:

    <context-param>
      <param-name>javax.faces.FACELETS_DECORATORS</param-name>
      <param-value>
          net.bootsfaces.expressions.decorator.SearchExpressionsTagDecorator
      </param-value>
    </context-param>

If you use BootsFaces, chances are you also want to benefit from the full power of the relaxed HTML5-like coding style of BootsFaces. If so, you have to register a different, more powerful decorator:

    <context-param>
      <param-name>javax.faces.FACELETS_DECORATORS</param-name>
      <param-value>
          net.bootsfaces.decorator.BootsFacesTagDecorator
      </param-value>
    </context-param>

Limits of the decorator

I encountered a surprising limitation of the decorator when I tried to use it with f:ajax. Both the render and the execute attribute are translated by the decorator, but they are ignored – at least by Mojarra (I didn’t try MyFaces yet). That’s fairly annoying because it forces you to use my first, verbose proposal. You can abbreviate the long name of the JSF bean SearchExpressionResolverBean by deriving a bean with a shorter name, but there’s no way to reach the simple syntax we really want.

Still, being able to use advanced search expressions with frameworks like Mojarra, MyFaces, RichFaces, or ButterFaces that haven’t been designed to be extended that way is nice.

Benefits for users of BootsFaces and PrimeFaces

Every once in a while, even users of such huge libraries like PrimeFaces (157 components) and BootsFaces (68 components) need a component that’s not part of the library. A popular way to build components is to build them from scratch using the base libraries. Another popular way is to add a library like OmniFaces, that’s not aware of the search expressions, either. But it does contain components like <o:commandScript /> that may benefit from the search expression.

By the way, if you prefer PrimeFaces over BootsFaces, you can also use their search expression framework. I didn’t prepare code to use it, but it’s fairly simple. The source code is at https://github.com/primefaces/primefaces/tree/master/src/main/java/org/primefaces/expression. The key class is the SearchExpressionFacade. There’s no facelets decorator, but I’m sure you’ll be able to migrate the BootsFaces facelets decorator to PrimeFaces within a few hours.

Benefits for the rest of the JSF world

Well, that’s fairly obvious: you couldn’t use the advanced search expression before. Now you can. More likely than not, you don’t see the use case use. But that shouldn’t stop you. Just give @next, @previous, @parent, @after, and @styleClass(.) a try. Before you know, you’ll be addicted. Using fixed ids may be the most efficient way with respect to CPU usage, but at the same time, it’s very inflexible and limited if your JSF views are changed frequently. The advanced search expressions of PrimeFaces and BootsFaces make moving fields from one panel to another or from one view to another a breeze.

Wrapping it up

JSF is very flexible. So it’s possible to add search expressions to JSF using a couple of tricks. However, the f:ajax facet of JSF seems to ignore the changes of the facelet decorators, so the result isn’t as nice as it’s intended to be. But still, it’s nice to able to use the advanced search expressions in JSF 2.2 or below.

What’s New in BootsFaces 0.8.5?

Fork me on GitHubWhat started as a small bugfix release, ended as a full-blown feature release. If the sheer number of commits is an indicator, the new release is awesome: the previous release counted 599 commits. In the meantime, 240 commits went into the 0.8.5 version, give or take a few. Needless to say, this amounts to a lot of added functionality: 11 new components, countless improvements and – of course – bugfixes. Plus, we’ve migrated the relaxed HTML-like markup style from AngularFaces to BootsFaces.

Continue reading

Type-safe Navigation in JSF

What to make of this? In general, I eagerly embrace everything offering type safety. However, in this particular case, I’m not entirely convinced. Probably I won’t use this feature in my projects any time soon. On the other hands, this stuff has so many options that it may easily pay off in larger projects. Especially, if some of the JSF views of your applications require authorization.

I’m talking about the “type-safe navigation” offered by the JSF module of Deltaspike. Basically, that’s a Java file describing every JSF page of your application.

Back to the future!

In a way, it’s funny that Deltaspike, which aims to improve JavaEE in general and JSF in particular, adds such a feature. One of the key advantages of JSF 2 was to get rid of the navigation rules file of JSF 1.x. Deltaspike brings it back, albeit in a different way.
Continue reading

What’s New in BootsFaces 0.8.1?

The open source branch of BootsFaces is still young. Only 14 months went by since the first release on Halloween 2014. But it’s already an impressive success story. In November, we’ve seen more than 1.000 downloads from Maven Central and Bintray. Ed Burns mentioned BootsFaces in one of his talks at JavaOne. JSFCentral and Jaxenter.de have asked us to write articles about BootsFaces. Obviously, BootsFaces has stirred a lot of attention, and many projects use it for their daily work.

Since the Halloween 2014 release, we’ve published five releases. That’s roughly a release every three months. The latest release took quite bit longer to finish. But it’s loaded with a host of new features, so it has surely been worth the wait. Personally, I call it the AJAX release, because that’s my big ticket. But there’s more in store four you. Other big tickets are the advanced search expressions inspired by PrimeFaces and the theme support. Plus, BootsFaces 0.8.1 has six new components. Seven, if you count the experimental <b:dataTable />. But that not a finished component yet. However, I felt it already is useful enough to include it with BootsFaces, even if it still requires polishing and “sugaring”.

But let’s talk about first things first.

Download coordinates

BootsFaces is available in two different flavors. There’s the regular version at Maven Central, and there’s a highly-optimized version at GitHub. The optimized version is 50 KB smaller, requires Java 7 or higher and should be a bit faster. The version hosted a Maven Central is targeted at a broader audience. It only requires Java 6. Alternatively, you can check out the repository from GitHub and build BootsFaces from source.

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

<dependency>
    <groupId>net.bootsfaces</groupId>
    <artifactId>bootsfaces</artifactId>
    <version>0.8.1</version>
    <scope>runtime</scope>
</dependency>

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

runtime 'net.bootsfaces:bootsfaces:0.8.1'

The BootsFaces project comes with both a Gradle build file and a Maven build file. The Maven pom.xml is the easy way to get started and should suffice for most purposes. Only if you want to tweak and optimize BootsFaces, you need the Gradle build. In particular, the Maven build doesn’t generate the CSS and JS files itself, but relies on the output of the Gradle build. By the way, that’s the reason why we keep the generated file in GitHub.

In any case, the URL of the repository is https://github.com/TheCoder4eu/BootsFaces-OSP.


Continue reading

A Comprehensive Guide to JSF AJAX

These days I analyzed the AJAX implementation of Mojarra. My goal was to learn enough about it to implement an improved version of the original AJAX implementation in our BootsFaces libraries. Along the way I learned that I had chosen quite a chunk to swallow. The JSF AJAX specification has many, many options, most of which I wasn’t even aware of. Time to write an exhaustive guide. Apart from the JSF specification we’ll also have a look at it’s PrimeFaces counterpart and – of course – what BootsFaces 0.8.0 will bring to you.

Source code of the examples

You can find the source code of the examples on GitHub. There’s a second project on GitHub covering the BootsFaces AJAX examples.
Continue reading

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

An Alternative API to JSF AJAX

As BootsFaces gains traction, people start to ask for AJAX capabilities. We’ve implemented some rudimentary AJAX support, but obviously that’s not enough. Developers need the full power of JSF 2.2 AJAX.

Funny thing is they demand it precisely the way JSF 2.0 defines it. It was a really clever approach when it was introduced. But I think in 2015 we can do better. I was always puzzled by the slightly counter-intuitive approach of JSF AJAX. Why do we have to use a facet to activate AJAX? Why do we need so many ids? And what does the attribute name execute mean, for that matter? For execute doesn’t execute anything. Instead, it defines which data to send.

The tradional JSF approach to AJAX

<h:form>
   <h:inputText id="name" value="#{helloBean.name}">
   <h:commandButton value="Welcome Me">
      <f:ajax execute="name" render="output" />
   </h:commandButton>
   <h:outputText id="output" value="#{helloBean.sayWelcome}" />	
</h:form>

The PrimeFaces approach

PrimeFaces shows us how to do thing better and more concise. Actually, AJAX and the superior search expressions are the two top reasons why I’m so fond of PrimeFaces. PrimeFaces allows for a very compact definition of AJAXified command buttons:

<h:form>
   <h:inputText value="#{helloBean.name}" />
   <p:commandButton value="Welcome Me" 
                    process="@previous" update="@next" >
   <h:outputText value="#{helloBean.sayWelcome}" />
</h:form>

We’ve got rid of the facet, we’ve got a powerful expression language allowing us to get rid of the ids and we’ve got much more intuitive keywords to define which inputs fields to send and which region of the DOM is to be updated.

Unfortunately, even PrimeFaces uses verbose event facets for almost every other AJAX event:

<p:inputText value="#{userBean.firstname}">
     <p:ajax event="keyup" 
             update="@next" listener="#{userBean.onKeyUp}"  />
</p:inputText>
<h:outputText value="#{userBean.firstname}" />
 
<p:inputText value="#{userBean.lastname}">
     <p:ajax event="blur" 
             update="@next" listener="#{userBean.onBlur}"   />
</p:inputText>
<h:outputText value="#{userView.lastname}"/>

The BootsFaces approach: a proposal

Now, let’s go one step further. Most interactive BootsFaces components already have quite a few JavaScript callbacks: onclick, onchange, onblur and so on. Why don’t we use precisely these callback attributes to define AJAX behaviour?

<b:inputText value="#{userBean.firstname}" 
             onkeyup="#{userBean.onKeyUp}" update="@next" />
<b:outputText value="#{userBean.firstname}" />

<b:inputText value="#{userBean.lastname}" 
             onblur="#{userBean.onBlur}" update="@next" />
<b:outputText value="#{userView.lastname}"/>

Note there’s a double use of the JavaScript callbacks. The general idea is to act differently according to the type of the onblur and onkeyup methods. If it evaluates to a string, it’s a Javascript method. If it evaluates to a method, it’s a JSF method.

This way, you’ve got a simple, intuitive API allowing for very concise code. Using the callbacks you even veto (i.e. prevent) the default action from taking place – a feature that’s lacking in the JSF world for some reason, but has always been possible in the Javascript world by simply returning false.

Update April 9, 2016

In the meantime I’ve implemented my proposal. Now it’s part of the current BootsFaces releases. But my proposal didn’t make it into the productive code without changes. Using the EL syntax for JSF calls is a nice idea, but it simply doesn’t work. For one, this approach would prevent you from defining the JavaScript code in the bean. No matter how unusual this use case may seem: it’s a valid use case, so BootsFaces should support it. Second, there’s simply no way to distinguish between a simple string and an EL expression. So I’ve decided to modify the syntax of my proposal. In the early days, developers used to prefix their JavaScript code with “javascript:”. So why don’t we follow this tradition and prefix our AJAX code with “ajax:”? Hence, the current syntax looks like so:

<b:inputText value="#{userBean.firstname}" 
             onkeyup="console.log('before the AJAX call');
                      ajax:userBean.onKeyUp;
                      javascript:console.log('after the AJAX call');" 
                      update="@next" />

Note that the second log is called after submitting the AJAX request, but it is executed almost always before the AJAX response is processed. That’s the nature of AJAX: it’s asynchronous.

What about you?

If the majority of you, dear readers, doesn’t feel comfortable with the double use of the callback methods, we could also introduce additional callback methods. For instance, we could call the callback methods onClickJava, onBlurJava, onChangeJava, onDragStartJava and onDropJava. Personally, I don’t think that’s necessary, but it’s you who count, so I’d like to hear from you. How do you like the idea? Which implementation would you like to see in implementation? Do you prefer the standard JSF way using event facets? If so, why? Or why not, for that matter?


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

BootsFaces 0.6.5 Published on Maven Central

After a while, our team is finally proud to publish the new v0.6.5 release.
This time we added more examples, a couple of handy components and exciting features. Here’s a short summary of the highlights:

  • Font Awesome Support ( #23 , #39 , #53 )
  • compatibility to both Oracle Mojarra and Apache MyFaces
  • improved AngularFaces Integration
  • Primefaces integration
  • Omnifaces integration
  • and better documentation.

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

BootsFaces 0.6.0 Now Available on Maven Central

Maven coordinates

BootsFaces – the JSF framework that makes Bootstrap much more accessible to JSF programmers – is now available on Maven Central. To use it, add a dependency to your Maven pom.xml file:

<dependency>
    <groupId>net.bootsfaces</groupId>
    <artifactId>bootsfaces</artifactId>
    <version>0.6.0</version>
</dependency>

Gradle users activate BootsFaces by adding this line to their .gradle build file:

compile 'net.bootsfaces:bootsfaces:0.6.0'

Minified version and debug-friendly version

The version I’ve uploaded to Maven Central is a developer-friendly version containing minified Javascript and CSS code, but non-minified Java class files. In other words: you can debug it, and you can easily identify the offending line if you find an error in your production log.

There’s also a version of BootsFaces that has been minified more aggressively. Currently, the smaller and slightly faster version hasn’t made it to Maven Central yet. You can download it at our project showcase and the project GitHub repository.

License

BootsFaces 0.6.0 is available both under a GPL 3 and a LGPL 3 license.

But I’m already using another JSF framework!

BootsFaces coexists peacefully with PrimeFaces, AngularFaces and probably most other JSF frameworks. For example, you can use the layout components of BootsFaces (<b:row>, <b:column>, <b:panelGrid>, <b:panel>, <b:tabView> / <b:tab> and <b:navBar>) together with the powerful input and datatable widgets of PrimeFaces.

Of course you can also use BootsFaces as a full-blown JSF component framework, providing responsive design and native Bootstrap GUIs. It’s up to you.

Kudos

BootsFaces is an open source framework initiated and led by Riccardo Massera. Thanks to Riccardo, Emanuele Nocentelli and everybody else who contributed! This includes everybody who gave us feedback by reporting errors or feature requests by opening an issue on the GitHub repository. Your feedback matters!

Wrapping it up

Visit our project showcase and enjoy!

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.

JSF 2.2 HTML5 Cheat Sheet

I’ve read a lot about the new JSF 2.2 HTML5 input fields, but until today I didn’t realize I hadn’t read a comprehensive introduction about this feature. I used to be happy with the short examples I was presented at conferences. However, there’s more than just <input type="text" jsf:value="#{my.favoriteBean.attribute}" />. As it happens, the documentation hides in plain sight. The JavaEE Javadoc tells you everything you have to know about the Mapping between HTML tags and JSF components. For the sake of convenience, this article summarizes the key points.

The general idea is to enable a web designer to design your JSF page without running a server. So it’s native HTML, and it should display nicely in a browser if opened as a simple HMTL file. Putting it in a nutshell, renaming a JSF file from *.xhtml to *.html doesn’t modify the design of the page.
Continue reading

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

BabbageFaces 1.0 RC2 Now Available for Download

Fork me on GitHubMy guts tell me BabbageFaces is ready to be released into the wild. Most of the time that’s a reliable measure. Today I’ve tested it with the new PrimeFaces 5 showcase. BabbageFaces passed the test without problems. There’s also a decent showcase example containing most of the elements of a typical business application, running both on Apache MyFaces and Mojarra. I’m optimistic all that’s missing is a couple of source code comments, tidying and documentation to call it a final version.

The showcase demo also shows BabbageFaces allows you to stop scattering ids all around your JSF code just to make AJAX efficient. BabbageFaces compares the response with the current DOM tree and sends only the minimum set of changes to the clients. If network load is giving you headaches, BabbageFaces may be your tool of choice. It reduces network traffic. At the same time it simplifies the programming model.
Continue reading