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

Back from ApacheCon NA 2014

April 15, 2014 in Apache Cordova, Conference

IMG_6797

I just get back from ApacheCon North America that was held in Denver, CO, USA 07-09 April 2014. The conference organization was fantastic and there were a lot of attendees in the conference sessions.

IMG_6843

IMG_6796

I had the chance to present “Developing Native Mobile Apps using JavaScript” in 07 April, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.
hazem1

hazem2

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:

Attached below the Sound Recording of my session:

One of the most interesting things that happened with me in ApacheCon is that I had the chance to meet the wonderful Apache Cordova team in ApacheCon:
IMG_6849

[OT] Denver is a wonderful modern city, if you plan to go there then do not miss visiting 16th street Mall, attached below some photos from there.
IMG_6863

IMG_6839

IMG_6868

IMG_6871

IMG_6872

IMG_6865

Boosting Performance of jQuery Mobile with Apache Cordova

March 12, 2014 in Apache Cordova, JavaScript, jQuery Mobile

If you use jQuery Mobile with Apache Cordova, you may find a little bit slowness in the transitions between pages of your mobile application. Actually, I had this issue with one of my Apache Cordova applications, and after spending sometime investigating the problem, I found that the solution is to disable jQuery mobile transition effects as follows:

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

Disabling transition effects will dramatically boost your app’s transition performance. I hope that this advice can be helpful to you in order to enjoy developing your cross-mobile apps using the wonderful Apache Cordova library.

Note: This advice targets jQuery mobile 1.4 (and older versions), I wish that this slowness issue will be fixed in the future versions of jQuery mobile.

Speaking in ApacheCon North America 2014

March 6, 2014 in Conference

ApacheCon Conference
@Monday, April 7 4:00 PM, I will be speaking in ApacheCon North America conference (that will be held from 07 April to 09 April @Denver, USA) about “Developing Native mobile applications using JavaScript”. My session will be a practical one, I will discuss how to develop native mobile applications using JavaScript and Apache Cordova. I hope it will be an interesting session for all the mobile development passionates :) :
http://apacheconnorthamerica2014.sched.org/speaker/hazems

Personally, it is my first time to visit Denver, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :D ?

I really wish to see all of you there in ApacheCon North America 2014!

Running Tizen Emulator in Mac OS X Mavericks

February 28, 2014 in mobile, Tizen

Your MacBook may hang if you try to run Tizen emulator in Mac OS X Mavericks. The reason behind this problem is that Mavericks is currently not supported by HAXM so running the Tizen emulator will result in a crash.

In order to resolve this issue, you can do one the following two way:

1. [Not recommended] Disable CPU-VT and GPU from the emulator manager as shown below. However, you have to know that doing this will make your emulator very slow but it will run peacefully.
Tizen Emulator Manager

2. [Recommended] Install hotfix for Mavericks available to download from the HAXM website:
http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement-macos-hotfix

Speaking in Geecon 2014

February 24, 2014 in Conference, JavaScript

Geecon
I will be speaking in Geecon conference (From 14 May to 16 May @Krakow, Poland) about “Jasmine Automated Tests for JavaScript”. My session will be a practical one, I will discuss how to develop unit tests for the JavaScript code of the applications using Jasmine as a powerful descriptive JavaScript unit testing tool and how to “automate” running Jasmine tests on the web browsers. The session also discusses how to generate Jasmine reports from the build management tools:
http://2014.geecon.org/speakers/hazem-saleh

Personally, it is my first time to visit Poland, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :) ?

I really wish to see all of you there in Geecon Poland 2014!

Sharing Xcode 5 projects on SVN with no issues

January 2, 2014 in iOS

In order to share Xcode 5 project on SVN, you can do it by doing the following:
1. Choose Xcode -> Preferences.
2. Choose “Accounts” tab.
3. In the “Accounts” tab, click “+” -> “Add Repository”.
4. Enter the SVN Repository information as shown in the screenshot below:
SVN Information Window

P.S. You may face the following error while trying to add SVN repo to Xcode as follows:
xcode cannot verify the identity of the server

In order to resolve this issue, just click "Show Certificate", unfold the disclosure arrow and set the “Trust” option menu to “Always Trust”.

5. After doing these steps, you can choose the local folder ("iOSProjects" for example) in which you want to do svn checkout. You can do this from "Source code" -> "Checkout".

6. Finally, you can create (or place) your Xcode project under your local folder "iOSProjects" to add and commit the project files to SVN.

[jQuery Mobile] Avoiding multiple pageinit executions for separate pages

December 24, 2013 in jQuery, jQuery Mobile, mobile

One of the common problems in jQuery mobile when navigating to a separate page in a separate HTML file is that he “pageinit” event will be triggered each time page is visited. The problem becomes severe when you find that each time you visit the separate page, your “pageinit” event handler is registered +1 more time which makes a great hassle because of the multiple event binding.

Let’s see an example to understand the problem, assume that we have a separate page called “pageA” which includes a JavaScript file that defines “pageinit” event handler as follows:

$(document).on("pageinit", "#pageA", function(e) {
    e.preventDefault();
	
    //Initialization can be done here ...
});

If you navigate from any page to “pageA”, you will find that in everytime you visit this page, your “pageinit” event handler will be registered and executed, which means that if you visit the page for the second time, you will find “pageinit” event handler executed twice and for the third time, you will find it executed 3 times and so on.

In order to resolve this issue, you will need to un-register the “pageinit” event as follows using $(document).off().

$(document).on("pageinit", "#subscriptionView", function(e) {
    e.preventDefault();
	
    //Initialization can be done here ...
	
    $(document).off("pageinit", "#subscriptionView");
});

Doing this workaround makes “pageinit” event handler executing only once each time the page is loaded.

P.S. This behavior does not happen in jQuery mobile when you follow the single HTML file approach which includes all the application pages.

JavaScript Quiz #12

December 17, 2013 in JavaScript

Assume that we have the following short JavaScript code:

<script>
    var number = 50;
    var obj = {
        number: 60,
        getNum: function () {
	    var number = 70;
	    return this.number;
	}
    }; 

    alert(obj.getNum());
    alert(obj.getNum.call());
    alert(obj.getNum.call({number:20}));
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alerts?

Read the complete answer