Sunday, December 1, 2013

Creating a Web Service from Apache Axis2

Apache Axis2 is a SOAP engine or a Web Service engine. It provides simple ways to create web services and / or web service clients. Same web service can be invoked using a SOAP message or a REST call. Axis2 uses Axiom as the method of data transferring. So from all the different ways you can create a web service using Axis2, using Axiom is the most flexible way. But it may sometimes be bit difficult and time consuming compared to some other methods like using POJO (Plain Old Java Objects) or ADB (Axis2 Data Binding). Here I'm going explain how to create a simple web service using Axiom.
First of all you have to download Axis2 binary distribution and the Axis2 WAR distribution. You can find it from here.
http://axis.apache.org/axis2/java/core/download.cgi

Then you have to install a java servlet engine like Apache Tomcat7. Here I'm going to use a Eclipse java EE version (Eclipse Indigo will be fine) as the IDE. A basic knowledge about the XML will be needed to proceed with writing a web service from Axiom. After having all these pre-requisites, now you are ready to start writing your web service.

Extract the WAR distribution zip file and copy it to the webapps folder in the tomcat7. (if you are using ubuntu your path will be "/var/lib/tomcat7/webapps" and you have to copy it with a sudo cp.) Then restart the server. This will create a folder named axis2 in the webapps folder.

Here I'm going to write a simple order processing system.

First create a java project in the Eclipse. Then in the src directory create a package named service. Inside that create a java file named OrderProcessor. Then right click on the project and go to Properties > Java Build Path > Libraries. Then click Add External JARs and add all the jars in the lib folder of the Axis2 binary distribution.
My web service has 2 methods. One is to create the order and the other is to get the details of the order later. You can add more methods to the web service. In this example I'm using just a Hash Map to store the data. Of course you have to store the data in a database if you are actually creating such a web service. So OrderProcessor class has 3 private variables to store the data.

      private HashMap<String, Double> itemPrice = new HashMap<>();
      private HashMap<String, HashMap<String, Integer>> order = new HashMap<>();
      private int ordercount = 0;

First method will be like this.

 public OMElement createOrder(OMElement element) {
element.build();
element.detach();

HashMap<String, Integer> orderItemTemp = new HashMap<>();
OMElement orderItem = (OMElement) element.getFirstElement();
OMElement itemElement = (OMElement) orderItem.getFirstOMChild();
OMElement quantityElement = (OMElement) itemElement.getNextOMSibling();
orderItemTemp.put(itemElement.getText(),
Integer.parseInt(quantityElement.getText()));

while ((orderItem = (OMElement) orderItem.getNextOMSibling()) != null) {
itemElement = (OMElement) orderItem.getFirstOMChild();
quantityElement = (OMElement) itemElement.getNextOMSibling();
orderItemTemp.put(itemElement.getText(),
Integer.parseInt(quantityElement.getText()));
}

ordercount++;
String orderId = ordercount + "";

order.put(orderId, orderItemTemp);

OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("orderprocessorns", "ns");
OMElement method = fac.createOMElement("createOrderResponse", omNs);
OMElement value = fac.createOMElement("orderId", omNs);
value.addChild(fac.createOMText(value, orderId));
method.addChild(value);

return method;
}

Data comes to the web service in the format of XML. To identify which method to call, the outer tag of the XML is the same as the name of the method. So the XML that comes to this method has a outer element with the name createOrder. We are writing the web service assuming that the XML which comes to web service has the bellow format.

<createOrder>
<item>
<itemId>A</itemId>
<quantity>1</quantity>
</item>
        <item>
<itemId>B</itemId>
<quantity>5</quantity>
</item>
</createOrder>

So the element is the object used to store the above XML data. So if you get the first element of the of the element, you will have a object having a XML of
  <item>
<itemId>A</itemId>
<quantity>1</quantity>
</item>

if you get the first child of orderItem you will get the itemId element. If you get the next sibling of that you will get the quantity element. You have to get the next sibling of the orderItem until you get a null object to get all the items of the order. You can create a HashMap and store the item and quantity in a HashMap. Then add the HashMap to the order HashMap with the generated key. The You have to generate a XML to send back the id of the order. It will have the bellow format.

<createOrderResponse>
<orderId>1</orderId>
</createOrderResponse>

Second method will be like this. You can get the details of the order when you send the id of the order.

  public OMElement getOrderDetails(OMElement element) {
element.build();
element.detach();

OMElement orderIdElement = element.getFirstElement();
String orderId = orderIdElement.getText();

HashMap<String, Integer> orderDetails = order.get(orderId);

OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("orderprocessor", "ns");
OMElement method = fac.createOMElement("getOrderDetails", omNs);

if (orderDetails != null) {
for (String key : orderDetails.keySet()) {
OMElement item = fac.createOMElement("item", omNs);

OMElement itemId = fac.createOMElement("itemId", omNs);
itemId.addChild(fac.createOMText(itemId, key));
item.addChild(itemId);

OMElement quantity = fac.createOMElement("quantity", omNs);
quantity.addChild(fac.createOMText(quantity,
"" + orderDetails.get(key)));
item.addChild(quantity);

method.addChild(item);
}
}

return method;
}

If you have the basic understanding of XML you can certainly understand what happens in the code.
Now you are finished with writing the business logic of the web service. Create a folder named META-INF in the root folder of the project and services.xml in that folder.
Add the bellow code to the services.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<service name="OrderProcessor" scope="application">
    <description>
        Order Processor
    </description>
    <operation name="createOrder">
        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
    </operation>
    <operation name="getOrderDetails">
        <messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
    <parameter name="ServiceClass">service.OrderProcessor</parameter>
</service>

If you carefully read this you can understand what each of this means. You have to be very careful when creating the services.xml file. Web service will not work properly with errors in this file.

Then right click on the project and click Export. Select JAR file as the format and give name OrderProcessor.aar as the file name. Then export the .aar file to a desired location. Then copy the .aar file to "tomcat7/webapps/axis2/WEB-INF/services". Then restart the server. If you go to the "http://localhost:8080/axis2/services/listServices" you will be able to see the web service you created is listed there. If you click on the web service name you will be able to see the wsdl file of the web service. This file is created automatically according to the method signatures of your web service. If you want to have a wsdl file different from that you can manually create the wsdl file. Normally wsdl file is used to get the details about web service and then create a client. But as you know the details about the web service you don't want to read the wsdl file. But when you actually create a web service client, you may not know the implementation details about the web service. So you have to go through the wsdl file and get the knowledge about what methods are there and how the data must be formatted and so on.

Now we are going to create sample client to invoke the web service. It is a ordinary java project and for this also you have to import the JARs imported when you created the web service.

import java.util.HashMap;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;

public class OrderProcessClient {
private static EndpointReference targetEPR = new EndpointReference(
"http://localhost:8080/axis2/services/OrderProcessor");

public static void main(String[] args) {
try {
Options options = new Options();
options.setTo(targetEPR);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);

ServiceClient sender;
sender = new ServiceClient();
sender.setOptions(options);

String orderId = createOrder(sender);
OMElement orderResult = getOrderDetails(sender, orderId);

System.out.print("Order id - ");
System.out.println(orderId);
System.out.println("Order items");
printOrder(orderResult);

} catch (AxisFault e) {
e.printStackTrace();
}

}

public static OMElement createOrderPayload(HashMap<String, Integer> order) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("orderprocessorns", "ns");
OMElement method = fac.createOMElement("createOrder", omNs);

for (String key : order.keySet()) {
OMElement item = fac.createOMElement("item", omNs);

OMElement itemId = fac.createOMElement("itemId", omNs);
itemId.addChild(fac.createOMText(itemId, key));
item.addChild(itemId);

OMElement quantity = fac.createOMElement("quantity", omNs);
quantity.addChild(fac.createOMText(quantity, "" + order.get(key)));
item.addChild(quantity);

method.addChild(item);
}

return method;
}

public static OMElement getOrderDetailsPayload(String id) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("orderprocessorns", "ns");

OMElement method = fac.createOMElement("getOrderDetails", omNs);
OMElement orderId = fac.createOMElement("orderId", omNs);
orderId.addChild(fac.createOMText(orderId, id));
method.addChild(orderId);
return method;
}

public static String createOrder(ServiceClient sender) {
HashMap<String, Integer> order = new HashMap<>();
order.put("a", 3);
order.put("f", 2);
order.put("e", 1);
order.put("c", 5);

String orderId = "";

OMElement orderPayload = createOrderPayload(order);
OMElement result;
try {
result = sender.sendReceive(orderPayload);
orderId = result.getFirstElement().getText();
} catch (AxisFault e) {
e.printStackTrace();
}

return orderId;

}

public static OMElement getOrderDetails(ServiceClient sender, String orderId) {
OMElement orderDetails = getOrderDetailsPayload(orderId);
OMElement orderResult;
try {
orderResult = sender.sendReceive(orderDetails);
} catch (AxisFault e) {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("orderprocessorns", "ns");
orderResult = fac.createOMElement("wrong", omNs);
orderResult.addChild(fac.createOMText(orderResult, "wrong"));
e.printStackTrace();
}

return orderResult;
}

public static void printOrder(OMElement element) {
element.build();

if (((OMElement) element.getFirstElement()) != null) {

element.detach();

OMElement orderItem = (OMElement) element.getFirstElement();
OMElement itemElement;
OMElement quantityElement;

do {
itemElement = (OMElement) orderItem.getFirstOMChild();
quantityElement = (OMElement) itemElement.getNextOMSibling();
System.out.println(itemElement.getText() + " - "
+ Integer.parseInt(quantityElement.getText()));
} while ((orderItem = (OMElement) orderItem.getNextOMSibling()) != null);
} else {
System.out.println("No such order");
}

}

}

Now you have created the client. You can run the project to invoke the web service. You can add more methods to the web service and call them using the client.

Wednesday, August 7, 2013

Avoiding "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated" in HttpClient

When developing an application that uses https, your test server doesn't have a valid SSL certificate. Or sometimes the web site is using a self-signed certificate or the web site is using free SSL certificate. So if you try to connect to the server using Apache HttpClient, you will get a exception telling that the "peer not authenticated". Though it is not a good practice to trust all the certificates in a production software, you may have to do so according to the situation.
This solution resolves the exception caused by "peer not authenticated".

But before we go to the solution, I must warn you that this is not a good idea for a production application. This will violate the purpose of using a security certificate. So unless you have a good reason or if you are sure that this will not cause any problem, don't use this solution.

Normally you create a HttpClient like this.
HttpClient httpclient = new DefaultHttpClient();

But you have to change the way you create the HttpClient.

First you have to create a class extending org.apache.http.conn.ssl.SSLSocketFactory.

import org.apache.http.conn.ssl.SSLSocketFactory;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MySSLSocketFactory extends SSLSocketFactory {
         SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}


Then create a method like this.
public HttpClient getNewHttpClient() {
   try {
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
       trustStore.load(null, null);

       SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

       HttpParams params = new BasicHttpParams();
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

       SchemeRegistry registry = new SchemeRegistry();
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
       registry.register(new Scheme("https", sf, 443));

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

       return new DefaultHttpClient(ccm, params);
   } catch (Exception e) {
       return new DefaultHttpClient();
   }
}

Then you can create the HttpClient.
HttpClient httpclient = getNewHttpClient();

If you are trying to send a post request to a login page the rest of the code would be like this.
private URI url = new URI("url of the action of the form");
HttpPost httppost =  new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
nameValuePairs.add(new BasicNameValuePair("username", "user"));  
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You get the html page to the InputStream. Then you can do whatever you want with the returned html page.

But here you will face a problem. If you want to manage a session using cookies, you will not be able to do it with this method. If you want to get the cookies, you will have to do it via a browser. Then only you will receive cookies.

Sunday, August 4, 2013

3D in Your Web Browser

Rendering a 3D image was a difficult task in early days. But now you can render a 3D image even in your web browser. Using HTML 5 with CSS 3 you can make 3D images in your web browser. But if you use JavaScript with HTML 5 you can do amazing things. But if you choose a proper JavaScript framework you will be amazed what it can do in a web browser. One such framework is three.js
three.js allows you to choose how you  render the image on your web browser. You can choose from WebGL of Canvas. WebGL uses graphics processor of your computer. So it gives you a good experience. But to use WebGL, you must use Windows operating system and Google chrome or Firefox. But Google chrome guarantees you the best user experience. But you can use Canvas in most of the operating systems and most of the web browsers which support HTML 5. But I must say that Canvas is bit slow when rendering the image. If you are using complex shapes you are advised to use WebGL renderer.
You can download three.js framework from http://threejs.org/ All you need to do is import three.js JavaScript file to your HTML page. If you need custom functionality, you have to add relevant JavaScript files that is needed.
Then you have to add a JavaScript to your HTML page. This may include two functions. init for initialization and animation for custom animations like handling the keyboard inputs.
In your HTML code add
<div id="output"></div>
Then in the JavaScript add this code.(You have to add jQuery to ease some implementations)

var scene = new THREE.Scene();
var container = $('#output');

Then get the detector.js from https://github.com/mrdoob/three.js/blob/master/examples/js/Detector.js and import it also to the page. Then,

var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var renderer;
if (Detector.webgl)
       renderer = new THREE.WebGLRenderer({antialias: true});
else
       renderer = new THREE.CanvasRenderer();
renderer.setClearColorHex(0xffffff, 1);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
container.append(renderer.domElement);
will detect whether you have WebGL renderer or not and create the necessary renderer for you will add it to the div you have previously created.

Then create the camera like this
var VIEW_ANGLE = 80, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 50, FAR = 200000;
camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
camera.position.y = 0;
camera.position.z = RACK_THICKNESS*RACKS*3;
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene.add(camera);

Now you have done the basic initialization. Then you have to add the objects you need to the scene. If you need to a box with a hole in the middle,

var object = new THREE.Object3D();
var shape1 = new THREE.Shape();
shape1.moveTo(50, 50);
shape1.lineTo(-50, 50);
shape1.lineTo(-50, -50);
shape1.lineTo(50, -50);
shape1.lineTo(50, 50);

var hole1 = new THREE.Path();
hole1.moveTo(40, 40);
hole1.lineTo(-40, 40);
hole1.lineTo(-40, -40);
hole1.lineTo(40, -40);
hole1.lineTo(40, 40);
shape1.holes.push(hole1);

 var extrusionSettings = {
         amount: 100,
         bevelEnabled: true,
         bevelThickness: 0.5,
         bevelSize: 0.5,
         bevelSegments: 8,
         material: 0,
         extrudeMaterial: 1
};
var geometry1 = new THREE.ExtrudeGeometry(shape1, extrusionSettings);
var materialFront = new THREE.MeshLambertMaterial({
        color: 0xffff00,
        ambient: 0xffff00
});
var materialSide = new THREE.MeshLambertMaterial({
        color: 0xff8800,
        ambient: 0xff8800
});
var materials = [materialFront, materialSide];
var material = new THREE.MeshFaceMaterial(materials);
var mesh1 = new THREE.Mesh(geometry1, material);
mesh1.position.set(0, 50, 0);
object.add(mesh1);
scene.add(object);

This will create the object and add it to the scene. All this have to be done in the init function. Then in the animate function,

function animate() {
                requestAnimationFrame(animate);

                var delta = clock.getDelta();
                var moveDistance = 200 * delta;
                var rotateAngle = Math.PI / 2 * delta;

                if (keyboard.pressed("right")) {
                    object.position.x -= moveDistance;
                }
                if (keyboard.pressed("left")) {
                    object.position.x += moveDistance;
                }
                if (keyboard.pressed("up")) {
                    object.position.y -= moveDistance;
                }
                if (keyboard.pressed("down")) {
                    object.position.y += moveDistance;
                }

                var rotation_matrix_object = new THREE.Matrix4().identity();
                if (keyboard.pressed("A")) {
                    rotation_matrix_object = new THREE.Matrix4().makeRotationY(rotateAngle);
                }
                if (keyboard.pressed("D")) {
                    rotation_matrix_object = new THREE.Matrix4().makeRotationY(-rotateAngle);
                }
                if (keyboard.pressed("W")) {
                    rotation_matrix_object = new THREE.Matrix4().makeRotationX(rotateAngle);
                }
                if (keyboard.pressed("S")) {
                    rotation_matrix_object = new THREE.Matrix4().makeRotationX(-rotateAngle);
                }
                if (keyboard.pressed("A") || keyboard.pressed("D") || keyboard.pressed("W") || keyboard.pressed("S"))
                {
                    object.matrix.multiply(rotation_matrix_object);
                    object.rotation.setEulerFromRotationMatrix(object.matrix);
                }
}

This will repeatedly render the scene and add the basic keyboard functionality. You have to import THREEx.KeyboardState.js to the page. As you have created the 2 functions, all you have to do is to call these 2 functions at the start of the JavaScript.

Most of these are self explanatory. So if you know the basics of programming, you will find it easy to understand what is happening in the code.



This a sample image created using three.js framework. Combining these simple shapes you can create lot more complex shapes.


You can find more examples from http://stemkoski.github.io/Three.js/

Friday, April 19, 2013

Connecting to mongoDB from node.js

Current trend in creating websites is use JavaScript for both back end and front end. If you choose to make your website in this way, you will probably need to host your website in a node.js server. If you decide to use mongoDB as your database, which is also a very fast growing technology, you will definitely need a REST API to connect to the database from your node.js server.
I assume by now you have installed node.js and mongoDB to your localhost to develop your web app.
So first open a command prompt and go to a folder you would like install some node.js modules(most probably to a folder you are creating your application.)

now type

npm install express
and then
npm install mongodb
to install express and mongodb driver for node.js (type 1st and let it download the files and then the 2nd). This downloads some files to a folder named node_modules.

Then create a server.js file in your root directory and paste the code bellow.


var express = require('express'),
    apis = require('./routes/apis');

var app = express();

app.configure(function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
});

app.get('/:table', apis.findAll);
app.get('/:table/:id', apis.findById);
app.post('/:table', apis.addEntry);
app.put('/:table/:id', apis.updateEntry);
app.delete('/:table/:id', apis.deleteEntry);

app.listen(3000);
console.log('Listening on port 3000...');


This will create a web server listening on the port 3000.

Now create a folder named routes and create apis.js file in the folder and add the code bellow.


var mongo = require('mongodb');
var Server = mongo.Server,
        Db = mongo.Db,
        BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('cvstore', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to database");
    }
});

exports.findById = function(req, res) {
    console.log("asked3");
    var id = req.params.id;
    var table = req.params.table;
    console.log('Retrieving wine: ' + id);
    db.collection(table, function(err, collection) {
        collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
            res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Content-Type', 'application/json');
            console.log(item);
            res.send(item);

        });
    });
};

exports.findAll = function(req, res) {
    var table = req.params.table;
    console.log("asked");
    db.collection(table, function(err, collection) {
        console.log("asked1");
        collection.find().toArray(function(err, items) {
            res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Content-Type', 'application/json');
            res.send(items);
        });
    });
};

exports.addEntry = function(req, res) {
    var table = req.params.table;
    console.log(table);
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection(table, function(err, collection) {
        collection.insert(wine, {safe: true}, function(err, result) {
            if (err) {
                console.log("error insert");
                res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Content-Type', 'application/json');
                res.send({'result': 'error'});
            } else {
                var id = JSON.stringify(result[0]._id);
                res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Content-Type', 'application/json');
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send({'result': 'success', 'id': id});
            }
        });
    });
}

Now go to the root folder where you saved the server.js file from command prompt and type
node server.js
this run the web server.
Now you can go to your web browser and type localhost:27017/tablename
Replace the tablename with what ever the collection name in the database. You will be able to see all the documents in that collection in the JSON format.
I haven't included the code for updateEntry and deleteEntry here. They will be like the other methods.
If you want to access the database from the application all you have to do is make a ajax call from the application.


$.ajax({
        url: 'http://localhost:3000/' + table,
        type: 'GET',
        'content-Type': "application/json",
        async: false,
        success: function(data) {
        },
        error: function(err) {
        }
    });

Replace 'table' with collection name you want to get the documents. By calling this function you will get a JSON object from the server we created. By making 'POST' request you can add JSON objects to the database.


If you are using a remote database you probably have a username and a password. In that case you will have to change the apis.js file a bit. Replace the relevant lines with this. In the mongolab database server you will have to use a url like 'ds035557.mongolab.com'. First part of the url will change according to your database. 'user' and 'pwd' are user name and password of the database respectively


var server = new Server('ds035557.mongolab.com', 35557, {auto_reconnect: true});
db = new Db('cvsubmit', server);

db.open(function(err, client) {
    if (!err) {
        client.authenticate('user', 'pwd', function(authErr, success) {
            if (authErr) {
                return console.dir(authErr);
            }
            var stream = client.collection('myCollection').find({}).stream();
            stream.on('data', function(item) {
                console.log("Do something with item");
            });
            stream.on('end', function() {
                console.log("Empty!");
            });
        });

    }
});