Sunday, August 17, 2014

Working with Node.js and PostgreSQL

In this post I create a simple Webserver with Node.js which uses PostgreSQL database in the backend. This post shows how to perform simple database operations of insert, select, update and delete using REST APIs (POST, GET, PUT & DELETE).
Assuming that you already have Node.js installed here are the steps to create this CRUD (Create, Remove Update & Delete) Webserver.
  1. Install Node.js if you already haven’t from Nodejs.org
  2. Create a test directory pg for this PostgreSQL based Node.js Webserver
  3. Open a command prompt and run
npm install pg
4.You will also need to install the PostgreSQL Enterprise DB with installer. Choose the appropriate OS and CPU
5.For this example I create a simple Employee Database.
6. In Windows Click Start->All Programs->PostgreSQL 9.3->pgAdmin III
7. Right click Databases-> New Database and Enter employees
1
8. The next step is to create Node.js Webserver and connect to this Database. PostgreSQL accepts DB connections through port 5432.
9.In this post The Webserver accepts connections from port 5433. Here is the shell of the Node.js Webserver
var pg = require("pg")
var http = require("http")
var port = 5433;
var host = '127.0.0.1';
http.createServer(function(req, res) {
if(req.method == 'POST') {
insert_records(req,res);
}
else if(req.method == 'GET') {
list_records(req,res);
}
else if(req.method == 'PUT') {
update_record(req,res);
}
else if(req.method == 'DELETE') {
delete_record(req,res);
}
}).listen(port,host);
console.log("Connected to " + port + "   " + host);

The Webserver accepts the usual 4 REST API calls – POST, GET, UPDATE, and DELETE for which there are 4 separate function calls.  The REST API calls correspond to the database operations insert, select, update and delete respectively.
10. Prior to performing each operation the  a client connects to the database as follows
var conString = "pg://postgres:postgres@localhost:5432/employees";
var client = new pg.Client(conString);
client.connect();
11. The POST operation is performed as follows
var insert_records = function(req, res) {
…
…
//Drop table if it exists
client.query("DROP TABLE IF EXISTS emps");
// Creat table and insert 2 records into it
client.query("CREATE TABLE IF NOT EXISTS emps(firstname varchar(64), lastname varchar(64))");
client.query("INSERT INTO emps(firstname, lastname) values($1, $2)", ['Tinniam', 'Ganesh']);
client.query("INSERT INTO emps(firstname, lastname) values($1, $2)", ['Anand', 'Karthik']);
12. To display the contents of the database the list_records function is used as follows
var list_records = function(req, res) {
console.log("In listing records");
// Select all rows in the table
var query = client.query("SELECT firstname, lastname FROM emps ORDER BY lastname, firstname");
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
13. The REST API Update is performed as below
var update_record = function(req, res) {
// Update the record where the firstname is Anand
query = client.query("UPDATE emps set firstname = 'Kumar' WHERE firstname='Anand' AND lastname='Karthik'");

14.Finally a delete is performed using a delete_record method
var delete_record = function(req, res) {
// Delete the record where the lastname is Karthik
client.query("DELETE FROM  emps WHERE lastname = 'Karthik'");
15.The output of each operation is sent back as HTML  as
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
// On end JSONify and write the results to console and to HTML output
console.log(JSON.stringify(result.rows, null, "    "));
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(result.rows) + "\n");
res.end();
});
16.To test the Webserver you need to install a REST API client for the browser you use. I installed the SureUtils-.REST API Client. his is a Chrome extension nand can be installed from Chrome Web Store (search for REST API client). You could choose any REST API client of your choice for the browser you intend to use (Chrome, Firefox)
17.Here are the tests I performed
18.The POST API call
2
19. The GET API call
3
20.The PUT  call followed by GET call
4
5
The PUT API updates Anand Karthik to Kumar Karthik. This is shown in the GET API call.
21. The DELETE call followed by the GET call
Here the DELETE API call deletes the Kumar Karthik record. The GET API call now displays only 1 record.
6
7
22. The console.log output for the operations above  is shown below
8
The code for the Node.js- PostgreSQL can be cloned from GitHub at node-pg

Saturday, August 16, 2014

Getting started with Node.js and Mongodb

Here is a post in which I try to get my arms around Node.js & MongoDB. This is first encounter with Web programming. There is a veritable universe of frameworks, languages, libraries and modules out there.
There are a gazillion blogs already on this topic so here is one more. When I came across Node.js recently,  I have been  impressed mightily with its ability to quickly cook up Webservers, TCP based server side programming and the like with really brief code. Another alluring fact was that it is based on Javascript which itself smacks of plain C, added to its charm. The experience with Node.js is difficult for a beginner. Also I must add that the Node.js'es callback functions takes a bit of getting used and I have had my share of pain with it.
MongoDB is an open-source document database, and one of the  leading NoSQL databases out there.
First things first - Install Node.js from Nodejs.org. Next install MongoDB for your OS and machine type. You will also need to install the mongodb module for use with Node.js. You can this by opening a command prompt and typing
npm install mongodb -g
This will allow you to access the mongodb module for use within your program. Now you should be good to go and create some basic code to manipulate MongoDB through Node.js.  This code is based on the commands from the following MongoDB wiki
Here are the steps for a basic CRUD (Create,Remove,Update & Delete) operations on MongoDB with Node.js
1. Create a folder c:\node\mongotest
2. Go to the directory where you have extracted the mongodb files and type in
mongod --dbpath c:\node\mongotest
This  will  start the database.
3. Here are the main functions of the code.
Connect to the mongodb database
var MongoClient = require('mongodb').MongoClient;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(!err) {
console.log("We are connected");
}
4. Create a collection of documents
//Create a collection test
console.log("Creating a collection test");
var collection = db.collection('test');
5. Insert documents into the collection
//Create documents to insert
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
//Insert the docs
console.log("Inserting the docs");
collection.insert(doc1,function(err,result){});
collection.insert(doc2, {w:1}, function(err, result) {});
6. Update the inserted documents as follows
//Updating
var doc3 = {key:1,value:1};
collection.insert(doc3,{w:1},function(err,result) {
if(err) {
console.log('Could not insert');
}
collection.update({key:1},{$set:{value:2}},{w:1},function(err,result) {});
});
7. Delete specific  documents from the database. Note: The remove() command requires a callback which I have included separately instead of the standard anonymous callback style
var mycallback = function(err,results) {
console.log("mycallback");
if(err) throw err;
}
//Deleting documents
console.log("The delete operation");
var doc4=[{key1:1},{key2:2},{key3:3}];
//Insert the document and then remove
collection.insert(doc4,{w:1},function(err,result) {
collection.remove({key1:1},mycallback);
collection.remove({key4:4},{w:1},mycallback);
});
8. Finally retrieve the inserted/updated records from the database
var stream = collection.find({mykey:{$ne:2}}).stream();
console.log("Printing values...");
stream.on("data", function(item) {
console.log(item);
});
stream.on("end", function() {});
The stream.on("data",) retrieves all the data till it encounters a stream.on("end").
So if I execute the above code I get the following output
C:\test \mongotest>node app3.js
We are connected
Creating a collection test
Inserting the docs
The delete operation
Printing values...
{ _id: 53c27ecbd5f4c59c1a2a5d39, hello: 'doc1' }
{ _id: 53c27ecbd5f4c59c1a2a5d3a, hello: 'doc2' }
{ _id: 53c27ecbd5f4c59c1a2a5d3b, key: 1, value: 1 }
{ _id: 53c27ecbd5f4c59c1a2a5d3c, key1: 1 }
{ _id: 53c27ecbd5f4c59c1a2a5d3d, key2: 2 }
{ _id: 53c27ecbd5f4c59c1a2a5d3e, key3: 3 }
mycallback
mycallback
The code can be cloned from Github at node-mongo

Wednesday, August 13, 2014

Mixing Twilio with IBM Bluemix

This post walks you through the steps to get started with Twilio on IBM's Bluemix. Twilio comes as a service that you can add  to your Mobile Cloud or Node.js app. Here's a quick look at Twilio. Twilio, is a cloud communications IaaS organization which  allows you use standard web languages to build voice, SMS and VOIP applications via a Web API.
Twilio provides the  ability to build VOIP applications using APIs. Twilio itself resides in the cloud and is always available. It also provides SIP integration which means that it can be integrated with Soft switches. Twilio looks really  interesting with its ability to combine the  cloud, Web and VOIP, SMS  and  the like.
This post barely scratches the surface of Twilio & Blue mix. This article provides aa hands-on experience for integration of Twilio with Bluemix and is based on this Twilio blog post. It enables you to send a SMS to your mobile phone by typing in a URL.
As in my earlier post the steps are
1) Fire-up a Node.js  Webstarter application from the  Bluemix dashboard.  In my case I have named the application websms. Once this is up and running
2) Click Add a Service and under 'Web and Application' choose Twilio.
3) Enter a  name for the Twilio service. You will also need the Account SID and Authorization token
4) For this go to http://www.twilio.com and sign up2
5) Once you have registered, go to your Dashboard for the Account SID and Auth Token. If the Auth token is encrypted, you can click the 'lock' symbol to display the Auth token in plain text.
6) Enter the Accout SID and Auth Token in the Twilio service in Bluemix
7)  To get started you can simply  fork my Twilio  websms code from devops.
8) Now clone the code into a folder you create as follows
git clone https://hub.jazz.net/git/tvganesh/websms
9) You will need to modify the following files
package.json
manifest.yml
app.js
 
10) You can create package.json by running
npm init. Make sure you enter the name of the application you created in Bluemix. In my case it is "websms' For the rest of the options you can choose the default. Here is the package.json file
"name": "websms",
"version": "0.0.0",
"description": "This README.md file is displayed on your project page. You should edit this \r file to describe your project, including instructions for building and \r running the project, pointers to the license under which you are making the \r project available, and anything else you think would be useful for others to\r know.",
"main": "app.js",
"dependencies": {
"gopher": "^0.0.7",
"express": "^3.12.0",
"twilio": "^1.6.0",
"ejs": "^1.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://hub.jazz.net/git/tvganesh/websms"
},
"author": "",
"license": "ISC"
}
11) In the manifest.yml make sure you enter the name of your application and the host
applications:
- host: websms
disk: 1024M
name: websms
command: node app.js
path: .
domain:
mem: 128M
instances: 1
12) Lastly make changes to your app.js.
// dependencies
var app = require('gopher'),
twilio = require('twilio');
var config = JSON.parse(process.env.VCAP_SERVICES);
var twilioSid, twilioToken;
config['user-provided'].forEach(function(service) {
if (service.name == 'Twilio') {
twilioSid = service.credentials.accountSID;
twilioToken = service.credentials.authToken;
}
});
// URL test
app.get('/', function(request, response) {
var client = new twilio.RestClient(twilioSid, twilioToken);
client.sendMessage({
to:'',
from:'body:'Twilio notification through Bluemix!'
}, function(err, message) {
response.send('Message sent! ID: '+message.sid);
});
});
13) After you have made the changes you will need to push the changes to Bluemix using the command line based 'cf' tool
14) Login into cf with
cf login – a http://api.ng.bluemix.net
15) Push the websms onto bluemix
16) In the folder where you websms files reside entr the following command
cf push websms -p . -m 512M
17) This should push the code to Bluemix.
Note: If you happen to get a
Server error, status code: 400, error code: 170001, message: Staging error: cannot get instances since staging failed
then you need to make sure to check the changes made to  files app.js, package.,json or the manigfest,yml.
18)  If all things went smoothly, go to your Bluemix dashboard and click the link adjacent to the Routes. You should see that an SMS has been sent as shown
3
19) Your mobile should now display the message that was sent as shown below
Screenshot_2014-06-22-13-41-44
20) Check the  analytics in your Twilio dashboard
1
Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions
[polldaddy rating="7295683"]

Saturday, August 9, 2014

Test driving Push notification in Bluemix

This post is a continuation of my earlier post 'Getting started with mobile cloud in Bluemix'. Here I take a test drive of the push service that Bluemix offers based on the article "Extend an Android app using the Push cloud service" from developerWorks.
This post assumes that you have already completed the changes from my earlier post for the mobile cloud. If you haven't,  you could clone the code from "mobile data" which is the official IBM version of this app and includes all the changes needed for persisting data in the cloud through their Android.
The Mobile Cloud App I created on Bluemix is "mobtvg". The main steps to have Push notification service using Bluemix are
  1. GCM services : Get Google API Project number  & GCM API Key
  2. Include the Google Play services library project
  3. Add the jar files to enable Push service
  4. Modify the server side Node.js file to send push notifications to all registered devices
  5. Make necessary code changes
  6. Run the application and test for notification
Here are more details on the above steps
a) GCM services : Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device, and also to receive messages from devices on the same connection. The 1st thing to do is get the Google API Project number & GCM API key.
- Click Create Project. Enter Project name & click Create.
- Note the Project Number on top of the page.
- Click API & Auth on left panel. Click API.
- Scroll down and turn-on Google Messaging for Android
-  Click credentials and click "Create new key". Click server key. Click create
-Copy API key in the Public API access
Now go the Bluemix dashboard and click your application. Click the Push module. In the Configuration tab, scroll down to Google Cloud Messaging and  click 'Edit'
Enter the Google API Project Number & GCM API key for both the Sandbox & Production configuration and click Save.
4
b) In Eclipse click Windows->Android SDK manager. Scroll down to the bottom and under Extras select Google Play services. Click install. Once the installation is successful import the project as follows File-Import->Android->Existing Android  code into Workspace. Click Next. In the next screen Browse to the path where your ADT bundle is installed and choose the folder
\ sdk\extras\google\google_play_services
and Click Ok. Also  check 'Copy project into workspace'. This will copy.
3
Now build the Google Play Services Project. To do this the project. Click Project->Properties->Android and make sure that you select 'Is library project' and then click build.
5
Add a reference to the Google Play services in the Androidmanifest.xml
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
c) Make all the code changes given in Step 4 of "Extend an Android app using the Push cloud service.
d) In MainActivity.java make sure you change the app_name to the name of your app for e.g
public static final String CLASS_NAME = "MainActivity";
public static final String APP_NAME = "mobtvg";
Also ensure that under assets folder you have populated the Application ID in the bluemix.properties file
applicationID=<Application ID from Bluemix>
d) Add ibmcloudcode.jar, ibmpush.jar, android-support-v4.jar (from /extras/android/support/v4)
e) Now the Mobile Push project need to include this library project. To do this select your Mobile App project. Click Project->Properties->Android. Click Add and select google-play-services-lib. Note: Make sure "Is library project" is unchecked otherwise you are in for a lot of grief.
8
f) Now you need to make changes to the Node.js application to push any changes from the server to all registered devices.  The code for this is in bluelist-push-node. Note; Making changes through the GUI results in an error that "manifest.yml is not in root node". So I suggest that you take the 'cf' route as follows.
- Clone the code using Git
git clone https://hub.jazz.net/git/mobilecloud/bluelist-push
Go to bluelist-push-node folder
i) Open the app.js with your favorite editor and enter the Application ID of your Bluemix application
//Data Values
var values = {
version:"0.3.1",
//change this to the actual application id of your mobile backend starter
appID : "",
host : "https://mobile.ng.bluemix.net"
}
ii) Open manifest.yml and change host name & name to the name of your application for e.g.
host: mobtvg
disk: 1024M
name: mobtvg
command: node app.js
path: .
domain: ng.bluemix.net
mem: 128M
instances: 1
iii) Once the changes are complete, open a command propmpt and  login into Bluemix using 'cf' as follows
- cd to the directory in which Node.js & manifest.yml exist, Do
cf login - a http://api.ng.bluemix.net
cf push mobtvg -p . -m 512M
(Note the changes are pushed to the mobile cloud app on Bluemix)
This will run through and finally give the status that the app is running successfully.
f) Now that all changes are complete the Mobile Cloud with Push can be tested..
g) Click Window->Android Virtual Device Manager. Click the Device definitions. You choose Google Nexus, Nexus 7. Click Create AVD.
Note: Make sure you choose Google API Level Y and not Android x.x.x API Y.
6
Let the AVD come up and display the current items in the grocery list.
h) Login to Bluemix. Click Push and select the Notifications tab and enter a test message for e.g. "This is a notification from Bluemix" and click send.
7
This will result in a Push Notification to be sent to the AVD. You should see this popup on you AVD as shown below
1
i) Add another AVD through Windows-Android Virtual Device manager. While one AVD is running go to Run->Run Configurations->Target Device and choose the newly created AVD.
j) This will start a second AVD which will refresh with the contents of the grocery list. Now adda new item in one of AVD devices. This will result in a Push notification to the other device that the Bluelist has been updated.
2
There you have it.
1) A mobile cloud applications in which changes persist in the cloud and are refreshed each time the Android device is restarted.
2) A Push notification that is sent to all registered devices whenever there is a change to the list.
Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions
[polldaddy rating="7295683"]

Friday, August 8, 2014

Getting started with a Mobile Cloud app with Bluemix

This post gives the key steps to get going in building a Mobile Cloud application on IBM's Bluemix. This post focuses on using the Android Platform for building the application. IBM Bluemix'es mobile cloud application includes under its hood mobile services like mobile application security, push and mobile data. A Node.js is also thrown in to provide server-side functions.
The Bluemix Mobile architecture is shown below
BuildingMobile
 
As in the previous post an existing Mobile cloud application IBM's bluelist -base is cloned to get familiarity with the steps involved. The IBM's bluelist-base app enables the user to maintain a grocery list that persists as mobile data in the cloud instance. To get started perform the following
1) Install ADT + Eclipse bundle from the aforementioned link
2) Unzip and install Eclipse and the ADT bundle
3) Make sure you have the Java JDK for Eclipse. If not install from the following site Java SE Development Kit 8 Downloads
4) Since we will be cloning an existing application and using Eclipse to make the changes we need to install EGit.
5) To do this open Eclipse and select Help-> Install New Software and type in http://download.eclipse.org/egit/updates in the Work with text field and hit enter. You should see the following
1
6) Once EGit is installed the IBM's bluelist-base App can be cloned as follows
7) In Eclipse click File->Import->Git->Import from Git and click Next
8) Choose Clone URI and Click Next
9) Enter the URI for IBM's bluelist-base. This shown below
2
10) This will download all the necessary source files and other Android related files and directories into the workspace.
11) After this perform the Steps 2 to Step 6 from the link given Build an Android app using the MobileData cloud service
12) After you make the necessary code changes you are good to go
13) Make sure you right-click and add all the necessary imports required (also Ctrl+Shift + O)
14) Build the Project and make sure that there are no errors
15) You are now ready to run the mobile cloud application. We need to run the mobile app on a Virtual simulator. This can be done as
a) In Eclipse click Window->Android Virtual Device Manager. Click the Device Definitions tab.
b) Choose Nexus 7 (Google) and Click Create AVD.
c) This will open a New Window. Set the following Skin->QVGA and Enter 100 MiB in SD Card size and click OK. This will add this as a AVD.
16) Now run the application.
17) This will bring up the AVD. This takes some time You should see the IBM bluelist showing up as one of the apps.
18) Click on IBM Bluelist. You can add grocery items. These items will persist even if you have to restart your application
3
19) The data is persisted in the IBM's cloud. This can be checked by logging into BlueMix'es dashboard
4
20) Click the Mobile Data and the data entered in the AVD device will show up in Data Classes drop down.
5
21) The Analytics tab will give a graphical output of the API calls
6
So not the mobile app that is cloud enabled is ready.
Clearly the ability to build Android Apps with the data stored at a cloud opens up numerous possibilities for apps like Evernote, Pocket across several devices.
There you have your first Mobile Cloud App.
Watch this space!
Disclaimer: This article represents the author's viewpoint only and doesn't necessarily represent IBM's positions, strategies or opinions
[polldaddy rating="7295683"]