Thursday, September 18, 2014

Brand new JSF components in PrimeFaces Extensions

The PrimeFaces Extensions team is glad to announce several new components for the upcoming 3.0.0 main release. Our new committer Francesco Strazzullo gave a "Turbo Boost" for the project and brought at least 6 JSF components which have been successfully intergrated! The current development state is deployet on OpenShift - please look the showcase Below is a short overview about added components with screenshots.

Analog Clock. This is a component similar to digital PrimeFaces Clock, but as an analog variant, enhanced with advanced settings.


Countdown. It simulates a countdown and fires an JSF listener after an customizable interval. You can start, stop and pause the countdown.


DocumentViewer. This is JSF wrapper of Mozilla Foundation project PDF.js - a full HTML PDF reader.


GChart. This is a JSF wrapper of Google Charts API. It's the same chart library used by Google Analytics and other Google services. Please look at Organizational Chart and Geo Chart.


A small note from me: charts can be built completely by model in Java. There is only one GChartModel which allows to add any options you want programmatically. I have used the same approach for my Chart library based on Flotcharts (thinking right now about adding it to the PF Extensions). There is only one generic model with generic setters to set options (options are serialized to JSON then). Advantage: you can export a chart on the server-side, e.g. with PhantomJS. This is a different approach to PrimeFaces' charts where each chart type has a separate model class and hard-coded fix methods for options settings.

Gravatar. This is a component for Gravatar services.


Knob. This is a nice theme-aware component to insert numeric values in a range. It has many settings for visual customization, AJAX listener and more.


Last but not least: we plan to deploy current SNAPSHOTs on the OpenShift in the future. More new components are coming soon. I intend to bring a component called pe:typeahead to the 3.0.0 too. It is based on Twitter's Typeahed. In the next post, I will explain how I have added an excellent WAI ARIA support to this great autocomplete widget. Stay tuned!

Friday, August 22, 2014

PrimeFaces Extensions 2.1.0 released

Today, we released the PrimeFaces Extensions 2.1.0. This is a maintenance release with many fixed issues and some new features for the existing components. The full issue list is on the GitHub.

As usually, you will find all infos on the homepage. The release is available in the Maven central repo.

Good news:
  • New snapshots and releases seem to be uploaded perodically to the public Sonatype's repository again, so that everybody can download them from there.
  • We will have new "sexy" components in the next main release because we could win a new commiter for us. His name is Francesco Strazzullo and he is a creator of StrazzFaces. The plan is to adopt his components for the PrimeFaces Extensions. Furthermore, I plan to bring cool components too (although I have less free time due to my current work).
  • PrimeFaces Extensions will go PRO! Thanks to Cagatay for this idea and his support. Please follow his announcement soon.

Have fun!

Sunday, July 13, 2014

How to get JSON response from JSF?

Many JavaScript widgets expect data and options in JSON format. Nowadays, it is really easy to choose a cool widget and wrap it in a composite component. But the first question is how to send an AJAX request and to recieve a response in a proper JSON format. This question is often raised by JSF users. All what you need is a XHTML facelet like this one
<f:view encoding="UTF-8" contentType="text/html"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core">
  <h:outputText value="#{stationView.getClosestStations(param.longitude, param.latitude)}" escape="false"/>
</f:view>
Please consider the contentType="text/html" (application/json will not work here) and escape="false" in the h:outputText. The method getClosestStations() in the bean StationView produces an JSON output for a list of special Java objects. I advise to use the Gson library in order to serialize any Java object to JSON. Short example:
String[] strings = {"abc", "def", "ghi"};
Gson gson = new Gson();
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]
The XHTML file above is located under the web context. Say, under the path /rest/stations.xhtml. Ajax call in your JavaScript code should look like this one:
$.ajax({
    url: requestContextPath + '/rest/stations.xhtml',
    type: "GET",
    data: {
        "longitude": x,
        "latitude": y
    },
    dataType: "json",
    success: function (data) {
        $.each(data, function (i, station) {
            ...
        });
    },
    error: function () {
        ...
    }
});
Please refer the jQuery docu for more information regarding $.ajax. Note: if you omit dataType: "json", you have to parse the JSON string manually.
success: function (data) {
    $.each($.parseJSON(data), function (i, station) {
        ...
    });
}
The response is a pure JSON string (no HTML tags) like this one:
[{"latitude":46.947045,"longitude":7.443922,"distanz":110,"name":"Bern, Bundesplatz"},{....},...]
Need more examples for JSON response in JSF? In one of my next post I will probably explain how to implement a cool autocomplete component without writing too much code.

Monday, July 7, 2014

How to implement a custom password strength indicator in JSF

Verifying password strength using JavaScript is a common task. In this post, I will show how to add a password strength indicator to an JSF based web application. The password component in PrimeFaces already has a feedback indicator of the password strength, but it has two major shortcomings:
  • Feedback indicator is not responsive (fix width, not mobile friendly, etc.)
  • Rules for the password strength verification are hard coded in JavaScript. No customization is possible.
What we need is a good looking, easy customizable and responsive password strength indicator / meter. Fortunately, PrimeFaces has another component - progress bar which we can use for our purpose. This is not a misusage. The end result is actually impressive.

Let's start with XHTML. First, define a quite normal passwort field.
 
<p:password id="passwort" value="#{mybean.password}" label="Password" required="true" autocomplete="off"/>
 
Second, define a progress bar with displayOnly="true" and some messages for the passwort strength (weak, medium, strong).
<div style="white-space:nowrap;">
    <h:outputText value="Password strength "/>
    <h:outputText id="pwdWeak" value="weak" style="display:none" styleClass="bold weakMsg"/>
    <h:outputText id="pwdMedium" value="medium" style="display:none" styleClass="bold mediumMsg"/>
    <h:outputText id="pwdStrong" value="strong" style="display:none" styleClass="bold strongMsg"/>
</div>
<p:progressBar id="pwdStrength" value="0" styleClass="pwdStrength" displayOnly="true"/>
Let's go to the JavaScript part. We need a script block (placed somewhere after the p:progressBar) where we intend to invoke a custom JS function setupPasswordStrength().
<script type="text/javascript">
    $(document).ready(function () {
        setupPasswordStrength("passwort", "pwdStrength");
    });
</script>
The JS function has two arguments: an Id of the password field and an Id of the progress bar. In the function, we will register a callback for the namespaced keyup event. In the callback, we will check the current input value by means of reg. expressions. We would like to take the following rules (rules are up to you):
  • Password length is less than 8 characters or doesn't contain at least one digit ==> weak password
  • Password length is equal or greater than 8 characters, contains at least one digit, but doesn't have at least one lower and one upper case letter OR one special char: ==> medium password
  • Password length is equal or greater than 8 characters, contains at least one digit AND has at least one lower and one upper case letter OR one special char: ==> strong password
These are good rules I have often seen across the internet. Let's me show the JS function.
function setupPasswordStrength(pwdid, pbarid) {
    // reg. exp. for a weak password
    var weak = XRegExp("^(?=.*\\d{1,}).{8,}$");
    // reg. exp. for a strong password
    var strong = XRegExp("^(?=.*[a-z])(?=.*[A-Z]).+|(?=.*[!,%,&,@,#,$,^,*,?,_,~,\\-]).+$");

    var $this = $("#" + pwdid);
    var pbar = $("#" + pbarid).find(".ui-progressbar-value");

    // visualize on keyup
    $this.off('keyup.' + pwdid).on('keyup.' + pwdid, function(e) {
        visualizePasswordStrength($(this).val(), pbar, weak, strong);
    });

    // fix chrome issue with autofill fields
    setTimeout(function(){$this.triggerHandler('keyup.' + pwdid);}, 150);
}

function visualizePasswordStrength(pwd, pbar, weak, strong) {
    var pparent = pbar.parent().parent().parent();
    var weakMsg = pparent.find(".weakMsg");
    var mediumMsg = pparent.find(".mediumMsg");
    var strongMsg = pparent.find(".strongMsg");

    if (pwd == null || pwd.length < 1) {
        pbar.removeClass("weak medium strong");
        weakMsg.hide();
        mediumMsg.hide();
        strongMsg.hide();
        return;
    }

    if (!weak.test(pwd)) {
        // weak
        pbar.removeClass("medium strong").addClass("weak");
        mediumMsg.hide();
        strongMsg.hide();
        weakMsg.show();
        return;
    }

    if (!strong.test(pwd)) {
        // medium
        pbar.removeClass("weak strong").addClass("medium");
        weakMsg.hide();
        strongMsg.hide();
        mediumMsg.show();
        return;
    }

    // strong
    pbar.removeClass("weak medium").addClass("strong");
    weakMsg.hide();
    mediumMsg.hide();
    strongMsg.show();
}
In the function visualizePasswordStrength(), we remove and add style classes to the progress bar dependent on the password strength (when user is typing his password). They are
.weak {
    background-color: #F88E7D !important;
    border: 1px solid #F95D24 !important;
    width: 33.33% !important;
}

.medium {
    background-color: #FEE379 !important;
    border: 1px solid #EDB605 !important;
    width: 66.66% !important;
}

.strong {
    background-color: #81FF6C !important;
    border: 1px solid #05E428 !important;
    width: 101% !important;
}
The weak indicator reserves one-third of the progress bar's length. The medium and strong indicators reserve respectively two-thirds and all available space. The styling of the progress bar looks as follows:
.pwdStaerke.ui-progressbar {
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    margin-top: 8px;
    height: 18px !important;
    border: solid 1px #c2c2c2 !important;
}

.pwdStaerke.ui-progressbar .ui-progressbar-value {
    display: block !important;
    margin-left: -2px !important;
    -moz-border-radius: 6px !important;
    -webkit-border-radius: 6px !important;
    border-radius: 6px !important;
}

Monday, May 5, 2014

PrimeFaces Extensions 2.0.0 released

A brand new release of PrimeFaces Extensions 2.0.0 is available in the Maven central repo. This release is built on top of PrimeFaces 5.0. Here are some links as usually:
The next release 2.1.0 will bring new components and new stuff. The best is yet to come.

Have fun!