JSF 2.3 Part2, Using @inject for FacesContext

December 21, 2014 in JSF

One of the wonderful features of the upcoming JSF 2.3 is the ability to inject many JSF objects such as UIViewRoot, ViewMap, ApplicationMap, ExternalContext and FacesContext. In this post, I will show you how to simply inject FacesContext without having to use the old way FacesContext.getCurrentInstance().

Continuing working on the sample that was introduced in the previous post, let’s modify User managed bean to get FacesContext in order to display an information message to the user once the operation is done. The following code snippet shows the modified User managed bean.

package beans;

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class User implements Serializable {
    private static final long serialVersionUID = 4629817047379532658L;
    private static final String INFO_MESSAGE = "Operation is done ...";
        
    private String name;
    
    @Inject
    FacesContext facesContext;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String greet() {
        facesContext.addMessage("form1", new FacesMessage(FacesMessage.SEVERITY_INFO, INFO_MESSAGE, INFO_MESSAGE));
        
        return null;
    }
}

As shown, all what you need to inject FacesContext in your managed bean is to annotate its declared instance with @inject annotation.

Running Application on GlassFish 4.1

In order to run our JSF application this time on GlassFish, we need to build Mojarra jars for GlassFish and then configure them on the server as follows:

  1. First of all, you need to make sure that you have both SVN and Apache Ant installed and configured in your operating system.
  2. Check out Mojarra 2.3 source code using the following SVN command:
    svn checkout https://svn.java.net/svn/mojarra~svn/trunk

    In order to build the JSF Mojarra jars for GlassFish then create a new file called build.properties under trunk. Then copy build.properties.glassfish file (which is located directly under trunk) content into it. Do not forget to set jsf.build.home property to the directory in which the sources were checked out into as follows for example.

    # --------------------------------------------------
    # Set this to the directory in which the sources
    # were checked out into
    # --------------------------------------------------
    jsf.build.home=/Users/hazems/projects/mojarra23/trunk
  3. CD to the jsf.build.home path, and then execute the following ant command:
    ant clean main
  4. After the successful execution of the previous command, you can get Mojarra jars from:
    1. jsf-api-intermediate.jar from trunk/jsf-api/build/lib directory.
    2. javax.faces.jar from trunk/jsf-ri/build/lib directory.
  5. Finally, overwrite the default javax.faces.jar file under glassfish-4.1/glassfish/modules with the new built javax.faces.jar file, and deploy our JSF application to GlassFish. After running our JSF application, you can see the information message after clicking "Greet" button as shown below.
    Screen Shot 2014-12-21 at 4.03.07 AM

Getting the JSF sample source code:

The sample source code is available in GitHub:
https://github.com/hazems/jsf2.3-work/tree/master/sampleJSF2

JSF 2.3 Part1, Getting Started

December 19, 2014 in JSF

It is really not so early to start working with the upcoming JSF 2.3 and testing it. In this post, I will show you how to get started in JSF 2.3 by building JSF (Mojarra) jars from its source then use them for your JSF 2.3 application which will run in Tomcat 7.

Building JSF Jars from SVN:

  1. First of all, you need to make sure that you have both SVN and Apache Ant installed and configured in your operating system.
  2. Check out the source code using the following SVN command:
    svn checkout https://svn.java.net/svn/mojarra~svn/trunk
    
  3. In order to build the JSF Mojarra jars for Apache Tomcat then create a new file called build.properties under trunk. Then copy build.properties.tomcat file (which is located directly under trunk) content into it. Do not forget to set jsf.build.home property to the directory in which the sources were checked out into as follows for example.
    # --------------------------------------------------
    # Set this to the directory in which the sources
    # were checked out into
    # --------------------------------------------------
    jsf.build.home=/Users/hazems/projects/mojarra23/trunk
    
  4. CD to the jsf.build.home path, and then execute the following ant command:
    ant clean main
    
  5. After the successful execution of the previous command, you can get Mojarra jars from:
    1. jsf-api-intermediate.jar from trunk/jsf-api/build/lib directory.
    2. javax.faces.jar from trunk/jsf-ri/build/lib directory.

Configuring your first JSF 2.3 application:

Simply all what you need to work with JSF 2.3 in Tomcat 7 is to do the following:

  • Place the two Mojarra jars in step 4 in your web application WEB-INF/lib folder.
  • Set the JSF version in the faces-config.xml to 2.3 as follows.
    <?xml version='1.0' encoding='UTF-8'?>
    <faces-config version="2.3"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_3.xsd"> 
    </faces-config>
    
  • Then now, you can write your JSF application and it will be powered by the upcoming JSF 2.3. I made a very basic JSF 2.3 sample which you can reach its code in the following GitHub URL:
    https://github.com/hazems/jsf2.3-work/tree/master/sampleJSF1
  • Screen Shot 2014-12-20 at 1.07.36 AM

    In my next JSF 2.3 posts, I will show you some of the JSF 2.3 implemented features “so far” in order to allow you to start working with them so stay tuned.

    Tip #4: Storing Media Files Properly in Cordova iOS apps

    December 15, 2014 in Apache Cordova, iOS

    In order to avoid being surprised by the loss of your recorded audio file in iOS, you should be aware of how to properly record and store a media file in Cordova iOS.
    Generally, in order to record an audio file in Apache Cordova, you can use the Cordova Media object as follows:

    var recordingMedia = new Media(mediaFilePath, recordingSuccess, recordingError);
    
    // Start Recording Audio
    recordingMedia.startRecord();
    
    // Stop Recording Audio
    recordingMedia.stopRecord();
    
    // Release Media resource
    recordingMedia.release();
    

    As shown in the code above, in order to record an audio file in Apache Cordova, you need to do the following:

    1. Create a Media object (recordingMedia) and specify mediaFilePath (the path of the audio file), recordingSuccess (the success callback which will be called if the media operation succeeds), recordingError (the error callback which will be called if the media operation fails).
    2. Start recording the audio by calling recordingMedia.startRecord().
    3. After completing the audio recording, call recordingMedia.stopRecord() and then release the used Media object by calling recordingMedia.release()

    In iOS, if you set mediaFilePath to the audio file name only without specifying any path (e.g "test.wav"), you may be surprised to find your audio file stored under the iOS app’s tmp directory (which is located under the iOS app’s sandbox directory). It is very important to be aware that the iOS app’s tmp directory content can be deleted automatically by iOS at anytime by iOS.

    In order to avoid losing your app’s recorded files, just place the "documents://" prefix before the audio file name as follows.

    var recordingMedia = new Media("documents://test.wav", recordingSuccess, recordingError);
    

    Doing this will make the recorded audio file stored under the iOS app’s Documents directory. The iOS app’s Documents directory is located under the app’s sandbox directory and is suitable for storing the app files.

    Reference:

    “JavaScript Mobile Application Development” Book:

    Tip #3: Implementing the Back button behavior for Android and Windows Phone 8 Apps

    December 9, 2014 in Apache Cordova, Book, JavaScript

    If you use Apache Cordova for developing your Android and Windows Phone 8 mobile apps, you may need to exit the app when the user clicks on the back button on the app’s home page, and to navigate back when the user clicks the back button and the current page is not the home page.

    Note that back button usually exists in Android and Windows Phone 8 devices.

    In order to do implement this behavior, you can implement the “backbutton” event handler after the “deviceready” event is triggered. This is an example to implement this in jQuery mobile.

        var homePage = "appHome";
       
        //Handle back buttons decently for Android and Windows Phone 8 ...
        function onDeviceReady() {
            document.addEventListener("backbutton", function(e){
                if ($.mobile.activePage.is('#' + homePage)){
                    e.preventDefault();
                    navigator.app.exitApp();
                } else {
                    history.back();
                }
            }, false);
        }
    
        $(document).ready(function() {
            document.addEventListener("deviceready", onDeviceReady, false); 
        });
    

    Using navigator.app.exitApp(), you can exit your mobile app when the app user is in the home page. And using history.back(), you can navigate back to the previous page when the app user is in other pages.

    Reference:

    “JavaScript Mobile Application Development” Book:

    Tip #2: Boosting Cordova’s jQuery Mobile Apps Performance

    November 21, 2014 in Apache Cordova, JavaScript, jQuery Mobile

    One of the common issues when you use jQuery Mobile with Apache Cordova in many of the platforms especially in the old versions Android platform is that you feel that the transitions between the app pages are slow.

    The solution for this problem is to disable jQuery mobile transition effects as follows when the jQuery mobile is loaded as follows.

        $.mobile.defaultPageTransition   = 'none';
        $.mobile.defaultDialogTransition = 'none';
    

    Disabling transition effects will dramatically boost your Cordova’s jQuery mobile app’s transition performance.

    Do not believe people who say jQuery Mobile is slow with Apache Cordova.

    Reference:

    “JavaScript Mobile Application Development” Book:

    Back from JMaghreb 2014

    November 9, 2014 in Apache Cordova, Conference, JavaScript

    JMaghreb 2014
    I just get back from JMaghreb 2014 that was held in Casablanca, Morocco 05-06 November 2014. The conference organization was fantastic and there were a lot of attendees in the conference sessions.
    Picture1
    I had the chance to present “Developing JavaScript Mobile Apps Using Apache Cordova” in 06 November, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.
    Picture2
    Picture3
    Picture3

    The session went great and I was glad to give a copy of my “JavaScript Mobile Application Development” book to one of the attendees who answered a JavaScript quiz at the end of my session.
    Books


    I uploaded my session below:

    Tip #1: Cordova Integration with jQuery Mobile in Windows Phone 8

    November 5, 2014 in Apache Cordova, JavaScript, jQuery Mobile

    One of the common issues when you use jQuery Mobile with Apache Cordova in Windows Phone 8 is the following:

    • Trimmed header title.
    • Footer is not aligned to bottom.

    The following figure shows this problem in details:

    Windows Phone 8 Bug

    Windows Phone 8 Bug

    In order to fix the “Trimmed header title” problem, you need to override ui-header and ui-title css classes as shown in the following code snippet:

    .ui-header .ui-title {
        overflow: visible !important; 
    }
    

    In order to fix the “Footer is not aligned to bottom” problem, you need to hide the System Tray by editing MainPage.xaml file as shown in the following code snippet:

    &lt;phone:PhoneApplicationPage 
        ...
        shell:SystemTray.IsVisible="False"&gt;
        ...
    &lt;/phone:PhoneApplicationPage&gt;
    

    After applying these two fixes, you will find your Cordova app properly displayed in your Windows Phone 8 device.

    Reference:

    “JavaScript Mobile Application Development” Book:

    “JavaScript Mobile Application Development” book is published

    October 27, 2014 in Apache Cordova, JavaScript, jQuery Mobile

    I’m pleased to announce the release of my new Book “JavaScript Mobile Application Development” using Apache Cordova:
    http://www.amazon.com/JavaScript-Native-Mobile-Apps-Development/dp/1783554177

    Book Cover

    What this book is about

    Mobile development is one of the hottest trends and a staple in today’s software industry. Almost every popular website today has its own equivalent mobile application version to allow its current users to access its functions from a mobile device. However, developing mobile applications requires a lot of effort and a wide skill set from mobile developers. Whether you are developing a mobile app for an iPad or on a Windows Phone, there is a requirement to learn the specific languages and technologies for that device. This is where the glory of Apache Cordova shines. As a set of device APIs for building cross-platform mobile applications using HTML, CSS, and JavaScript, the apps developed using JavaScript APIs are easily portable to other device platforms, as well as being consistent across devices and built on web standards. As a result of this, you will find that your development costs and efforts are sharply reduced, whilst increasing the readability and maintainability of your code, as you make use of only one popular programming language: JavaScript.

    This is the learning resource to use when you want to efficiently develop your own native mobile applications using Apache Cordorva as the platform that uses HTML, CSS, and JavaScript. In order to develop neat-looking mobile applications, this book also utilizes jQuery mobile. jQuery mobile is one of the best mobile web application frameworks that allows web developers to develop web applications that are mobile friendly.

    We start by developing a simple sound recorder mobile app. We then configure this app to work on Android, Windows, and iOS. Then you will learn how to use the different APIs provided by Apache Cordova and how to develop your Apache Cordova custom plugins.

    You will then learn how to develop, run, and automate tests using Jasmine. At the end, you develop a “Mega App” where you will learn in details how to design, develop, and deploy a real cross-platform Apache Cordova application that works in Android, iOS, and Windows Phone 8.

    After finishing this book, you should be able to develop your mobile application on the different mobile platforms, using only JavaScript, without having to learn the native programming languages of every mobile platform.

    What this book covers

    Chapter 1, An Introduction to Apache Cordova, teaches what Apache Cordova is and the differences between mobile web, mobile hybrid, and mobile native applications. You will also know why we should use Apache Cordova, along with the current Apache Cordova architecture, and finally, the chapter offers an overview of Apache Cordova APIs.

    Chapter 2, Developing Your First Cordova Application, explains how to develop, build, and deploy your first Sound Recorder mobile application on the Android platform.

    Chapter 3, Apache Cordova Development Tools, explains how to configure your Android, iOS, and Windows Phone development environments. You will also learn how to support and run your Sound Recorder mobile application on both iOS and Windows Phone 8 platforms.

    Chapter 4, Cordova API in Action, dives deep into Apache Cordova API, and you will see it in action. You will learn how to work with the Cordova accelerometer, camera, compass, connection, contacts, device, Geolocation, globalization, and InAppBrowser API by exploring the code of the Cordova Exhibition app. The Cordova Exhibition app is designed and developed to show complete usage examples of the Apache Cordova core plugins. The Cordova Exhibition app supports Android, iOS, and Windows Phone 8.

    Chapter 5, Diving Deeper into the Cordova API, continues to dive into Apache Cordova API by exploring the remaining main features of the Cordova Exhibition app. You will learn how to work with Cordova media, file, capture, notification, and storage API. You will also learn how to utilize the Apache Cordova events in your Cordova mobile app.

    Chapter 6, Developing Custom Cordova Plugins, dives deep into Apache Cordova and lets you create your own custom Apache Cordova plugin on the three most popular mobile platforms: Android, which uses the Java programming language, iOS, which uses the Objective-C programming language, and Windows Phone 8, which uses the C# programming language.

    Chapter 7, Unit Testing Cordova Apps Logic, explains how to develop JavaScript unit tests for your Cordova app logic. You will learn the basics of the Jasmine JavaScript unit testing framework and understand how to use Jasmine in order to test both the synchronous and asynchronous JavaScript code. You will learn how to utilize Karma as a powerful JavaScript test runner in order to automate the running of your developed Jasmine tests. You will also learn how to generate the test and code coverage reports from your developed tests. Finally, you will learn how to fully automate your JavaScript tests by integrating your developed tests with Continuous Integration tools.

    Chapter 8, Applying it All – the Mega Application, explores how to design and develop a complete app (Mega App) using Apache Cordova and jQuery Mobile API. Mega App is a memo utility that allows users to create, save, and view audible and visual memos on the three most popular mobile platforms (Android, iOS, and Windows Phone 8). In order to create this utility, Mega App uses jQuery Mobile to build the user interface and Apache Cordova to access the device information, camera, audio (microphone and speaker), and filesystem. In this chapter, you will learn how to create a portable app that respects the differences between Android, iOS, and Windows Phone 8.

    Where to buy this book

    You can buy JavaScript Mobile Application Development Book from:

    JAX-RS + Cloudant in Bluemix as a service and Worklight App as a client

    August 3, 2014 in Bluemix, Cloudant, JavaScript, Worklight

    In the service side, I developed a very simple JAX-RS service which retrieve JSON documents of a Cloudant Database using ektrop over Bluemix.

    Below is the JAX-RS service code:

    package com.test.todos.service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.naming.InitialContext;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import org.ektorp.CouchDbConnector;
    import org.ektorp.CouchDbInstance;
    
    @Path("/todo")
    public class TodoService {
        protected static CouchDbInstance _db;      
        
        static {
            try {
                _db = (CouchDbInstance) new InitialContext().lookup("couchdb/todos-cloudant");
            } catch (Exception e) {
                e.printStackTrace();
                
                //Handle error nicely here ...
            }
        }
        
        @GET
        @Produces(MediaType.APPLICATION_JSON)
        public List<Todo> getAllTodos() {
            List<Todo> todos = new ArrayList<>();
    
            try {            
                CouchDbConnector dbc = _db.createConnector("todos_db", false);
    
                List<String> ids = dbc.getAllDocIds();
    
                for (String id : ids) {
                    Todo todo = dbc.get(Todo.class, id);
    
                    todos.add(todo);
                }
            } catch (Exception e) {
                todos = new ArrayList<>();
                e.printStackTrace();
                //Handle error nicely here ...
            }
    
            return todos;
        }
        
        static class Todo {
            String _id;
            String _rev;
            String title;
            String description;
            
            public Todo() {
            }        
            
            public Todo(String id, String title, String description) {
                super();
                
                this._id = id;
                this.title = title;
                this.description = description;
            }
            
            public String get_id() {
                return _id;
            }
    
            public void set_id(String _id) {
                this._id = _id;
            }
    
            public String get_rev() {
                return _rev;
            }
            public void set_rev(String _rev) {
                this._rev = _rev;
            }
    
            public String getTitle() {
                return title;
            }
            public void setTitle(String title) {
                this.title = title;
            }
            
            public String getDescription() {
                return description;
            }
            public void setDescription(String description) {
                this.description = description;
            }
        }
    }
    

    As you notice here, the Cloudant DB connector resource name follows "couchdb/[service_name]" naming which is ("couchdb/todos-cloudant" in our case). Note that all of the Cloudant DB connector resources have the prefix "couchdb/". _db connector variable is used to access the Cloudant Database which is created in Bluemix as shown below.
    Bluemix config

    As you see we have a Liberty for Java app called ("todos") and a Cloudant Database service which is bound to it. Do not forget to make sure your Cloudant service name matches the last part of the Cloudant DB connector name after “/”.

    In order to allow the service to be accessed using Ajax without facing cross domain boundaries issues from the Worklight mobile client, I created a simple Filter servlet that wraps the JSON response in a JSONP format as shown here:
    https://github.com/hazems/bluemix-java-cloudant-worklight-sample/blob/master/todos/src/com/test/todos/filter/JSONPRequestFilter.java

    Finally, in order to deploy our WAR file, just do the following:
    1. Make sure to install Cloud Foundry CLI from https://github.com/cloudfoundry/cli.

    2. After this, type the following cf login command as follows:

    cmd> cf login
    

    3. You will be introduced to the API endpoint prompt then enter "https://api.ng.bluemix.net" and your email and password as shown follows:

    API endpoint> https://api.ng.bluemix.net
    
    Email> yourRegisteredEmail@email.com
    Password> yourPassword
    

    4. After this, you can go ahead and install our WAR as follows:

    cmd> cf push <unique_app_name> -m 512M -p <path_to_your_war_file> 
    

    which is in our case:

    cmd> cf push todos -m 512M -p todos.war
    

    5. Finally, you can access the working application using simply:

    [APP_URL]/todo
    

    In the Worklight project, a call to the TODO service is done using jQuery $.ajax as follows to get the list of TODOs as follows:

    $.ajax({
    	url: "http://hs-todos.mybluemix.net/todo",
    	jsonp: "callback",
    	dataType: "jsonp", 
    	success: function(todos) {
    	    //Display TODOs here ...
    	},
    	error: function(jqXHR, textStatus, errorThrown) {
    	    console.log("An error occurs");            	
    	}
    });  
    

    The final result of the WL project in iPhone is displayed as shown below:
    iPhone screenshot

    Finally, it worth mentioning that you can directly call Cloudant from your JavaScript client, Cloudant offers a powerful REST API over the database as indicated in the links below:
    https://docs.cloudant.com/api/documents.html#crud-operations-on-documents
    https://docs.cloudant.com/api/index.html

    The mentioned example above introduces JAX-RS with Cloudant to show you how you can use them together with Bluemix and to give you the ability to decouple the REST client JavaScript code from the underlying Cloudant Database structure which will give you the ability to change Cloudant DB JSON structure in the future without affecting your REST API clients code.

    I placed the working sample (JAX RS project and Worklight project) in GitHub for reference:
    https://github.com/hazems/bluemix-java-cloudant-worklight-sample

    Enjoy!

    Back from GeeCON Poland 2014

    May 25, 2014 in Conference, Continuous Integration, Jasmine, JavaScript, Unit Testing

    Main

    I just get back from GeeCON that was held in Krakow, Poland 14-16 May 2014. The conference organization was fantastic and there were a lot of attendees in the conference sessions. IMO, GeeCON is really the biggest Java Conferences in the Central-Eastern Europe as it had 1100+ attendees.

    Big_Session

    I had the chance to present “Jasmine Automated Tests for JavaScript” in 15 May, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.

    1

    3

    The session went great and I was glad to give a free copy of my JavaScript Unit Testing book to one of the attendees who answered a JavaScript quiz at the end of my session.
    IMG_6801

    I uploaded my session below:

    Finally, I would like to thank all the organizers of this conference, especially Adrian Nowak (@adrno), Adam Dudczak (@maneo), Marcin Gadamer (@marcingadamer), and certainly all of the wonderful guys behind this conference.

    [OT] Krakow is a wonderful modern city, if you plan to go there then do not miss visiting Ojców Garden Krakow, Wawel Royal Castle, and generally Old Krakow city. I attached below some of the photos below:

    1. Krakow, The Old City, 16 March 2014:
    https://plus.google.com/photos/105100477384124159138/albums/6014103071265602913

    2. Wawel Royal Castle, Krakow, 16 May 2014:
    https://plus.google.com/photos/105100477384124159138/albums/6014128282375540177