Showing posts with label GWT example. Show all posts
Showing posts with label GWT example. Show all posts

Tuesday, July 24, 2012

GWT RPC - Server communication with MongoDB

Further to the client tutorial in the previous blog, here i am going to present how client communicates with the server with the help of GWT RPC (Remote Procedure Call).
Using RPC which works asynchronously only specific part of the client components can be updated without updating the complete client.














Pre-Requisite:
Java, Eclipse with GWT plugin, MongoDB.



In this example i have extended the previous client to
  a) save data i.e. user data to database and
  b) authentication user

Client can send/receive serializable objects to/from the server. In this example server is going to use that data and insert in into DB, which is MongoDB in our case.


Create Modal
As the client can send serializable java objects over HTTP. Lets create a modal first.


User.java
package com.example.gwt.client.modal;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
view raw UserModal hosted with ❤ by GitHub



Create Service
Now we need to have a service which a client can use.
In our case we name it as MongoDBService and it implements RemoteService


MongoDBService.java
package com.example.gwt.client;
import java.util.List;
import com.example.gwt.client.modal.User;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("dbservice")
public interface MongoDBService extends RemoteService {
List<String> getAllUsers();
void setUser(User user);
boolean isValidUser(User user);
}
view raw MongoDBService hosted with ❤ by GitHub



@RemoteServiceRelativePath("dbservice") is annotation used for the service identification and calling, which should match with the service path defined in web.xml for servlet-mapping tag.

We need to create Asynchronous service for our MongoDBService, client is actually going to call RPC through MongoDBServiceAsync. All methods of MongoDBService will have extra parameter which is of type AsyncCallback. Client call will be notified when any asynchronous service call completes.

MongoDBServiceAsync.java
package com.example.gwt.client;
import java.util.List;
import com.example.gwt.client.modal.User;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface MongoDBServiceAsync {
void getAllUsers(AsyncCallback<List<String>> callback);
void setUser(User user, AsyncCallback<Void> callback);
void isValidUser(User user, AsyncCallback<Boolean> callback);
}



Implement service at the server side
Create class MongoDBServiceImpl which extends RemoteServiceServlet and implements MongoDBService. Basically MongoDBServiceImpl is a servlet which is extending from RemoteServiceServlet rather than the HttpServlet directly.



Updating web.xml with servlet details
make sure that all the service which are created with the annotation RemoteServiceRelativePath are added properly for each servlet.

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
<welcome-file-list>
<welcome-file>GwtWebAppDemo.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MongoDBServiceImpl</servlet-name>
<servlet-class>com.example.gwt.server.MongoDBServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MongoDBServiceImpl</servlet-name>
<url-pattern>gwtwebappdemo/dbservice</url-pattern>
</servlet-mapping>
</web-app>
view raw web.xml hosted with ❤ by GitHub



url pattern tag path should be formed using module/service.
In this case module name is gwtwebappdemo ( see in GwtWebAppDemo.gwt.xml for rename-to value) and service in dbservice.


Client Service Call
calling service from client

Button btnAdd = new Button("Add");
btnAdd.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
User user = new User();
user.setUserName(nameTextBox.getText());
user.setPassword(passwordTextBox.getText());
MongoDBServiceAsync mongoDBServiceAsync = GWT
.create(MongoDBService.class);
ServiceDefTarget serviceDef = (ServiceDefTarget) mongoDBServiceAsync;
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL()
+ "dbservice");
mongoDBServiceAsync.setUser(user, new AsyncCallback<Void>(){
@Override
public void onFailure(Throwable caught) {
Window.alert("User addition failed, reason: " +caught.getMessage());
}
@Override
public void onSuccess(Void result) {
Window.alert("User addition successful");
}
});
}
});
btnAdd.setText("Add Users");




Running application

1) Start MongoDB
    In this case i have started DB without authentication and on default port.
    Default port is 27017 which we have used to connect to database in the code. See DBUtil.java in the
   example.



2) Add user into database.
    Client calls asynchronous call to server, server starts the processing. Once request processing is finished it calls back with the call back handler provided in the request. Client gets call in onFailure in case of failure and onSuccess in case of request processing successful.


    In the server side, server received the User object and sets the data into User collection which is in the mymongodb database using BasicDBObject.

MongoDBServiceImpl.java
@Override
public void setUser(User user) {
try {
DB dataBase = DBUtil.getDataBase("mymongodb");
DBCollection userCollection = DBUtil
.getCollection(dataBase, "User");
BasicDBObject document = new BasicDBObject();
document.put("username", user.getUserName());
document.put("password", user.getPassword());
// insert into database
userCollection.insert(document);
// commit into database
userCollection.save(document);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
view raw SaveUser hosted with ❤ by GitHub


3) Check the collection ( table) creation in dbs (database)
    In this example mymongodb is the database and User is the collection which we are using.
    Initially both database and collection is not present, when the first save happens. Both gets automatically
    created.



4) Check User Authentication with wrong input.



Download complete example from here in GwtWebAppDemo_server.rar file.

Heroku Custom Trust Store for SSL Handshake

  Working with Heroku for deploying apps (java, nodejs, etc..) is made very easy but while integrating one of the service ho...