Wednesday 27 February 2013

Persist Data in GWT



Persist Data in GWT
Using Data nucleus and JDO
In this post we are going to describe how to manage DB in GWT project using Data-Nucleus and JDO services, which may help you to store data and retrieve it from DB. I am going to demonstrate it with a simple class.
Complete work flow of database management will go through following steps:
1.       Collect information from client side.
2.       Call RPC call to server side
3.       Save data in server side.
4.       Propagate retrieve request from client.
5.       Retrieve data and return to client side.
We can start coding from server side:
By default, when you create a Web Project using Eclipse and GPE, a jdoconfig.xml file is created for you. By default, this file defines connection parameters for BigTable on Google App Engine. You can run this locally and a local file will be created. In order to save information using JDO, do the following
Create a singleton to get a persistence manager, in server side:
public final class PMF {
  private static final PersistenceManagerFactory pmfInstance =  JDOHelper.getPersistenceManagerFactory("transactions-    optional");
  private PMF() {}
 public static PersistenceManagerFactory get() {
   return pmfInstance;
 }
}

Now create a server side implementation of RPC service
@SuppressWarnings("serial")
public class DataNucleusServiceImpl extends RemoteServiceServlet implements
              DataNucleusService {
       public String getData() throws IllegalArgumentException {
              PersistenceManager pm = null;
              try {
                     pm = PMF.get().getPersistenceManager();
                     javax.jdo.Transaction transaction = pm.currentTransaction();
                     Extent e = pm.getExtent(User.classtrue);
                     Iterator iter = e.iterator();
                     String returns = "";
                     while(iter.hasNext()){
                           User user  =  (User)iter.next();
                           returns = returns +  user.getName() + "\n" ;
                     }
                     return returns;
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     if (null != pm)
                           pm.close();
              }
              return "no names";
       }
       public String addData(String input) throws IllegalArgumentException {
              PersistenceManager pm = null;
              try {
                     pm = PMF.get().getPersistenceManager();
                     javax.jdo.Transaction transaction = pm.currentTransaction();
                     transaction.begin();
                     User guest = new User("guste:" + input);
                     pm.makePersistent(guest);
                     transaction.commit();
              } catch (Exception e) {
                     e.printStackTrace();
              } finally {
                     if (null != pm)
                           pm.close();
              }
              return "RETURNING FROM SERVER";
       }
}
Now we can go to client side:
First create interfaces to call the RPC services:
·         DataNucleusService.java
·         DataNucleusServiceAsync.java
There implementations are given below:
@RemoteServiceRelativePath("greet")
public interface DataNucleusService extends RemoteService {
       String addData(String name) throws IllegalArgumentException;
       String getData() throws IllegalArgumentException;
}
public interface DataNucleusServiceAsync {
       void addData(String input, AsyncCallback<String> callback)
                     throws IllegalArgumentException;
      
       void getData( AsyncCallback<String> callback) throws IllegalArgumentException;
}
Now in Entry point class, on module load:
Add these codes:
       private final DataNucleusServiceAsync dataNucleusService = GWT
                     .create(DataNucleusService.class);
TextBox td = new TextBox();
       Button add = new Button("add");
       Button read = new Button("read");
       public void onModuleLoad() {
add.addClickHandler(new ClickHandler() {
                     @Override
                     public void onClick(ClickEvent event) {
                           dataNucleusService. addData (td.getText(),
                                         new AsyncCallback<String>() {
                                                public void onFailure(Throwable caught) {
                                                       Window.alert("failed");
                                                }
                                                public void onSuccess(String result) {
                                                       Window.alert("success ");
                                                }
                                         });
                     }
              });
             
              read.addClickHandler(new ClickHandler() {
                     @Override
                     public void onClick(ClickEvent event) {
                           dataNucleusService.getData(new AsyncCallback<String>() {
                                                public void onFailure(Throwable caught) {
                                                       Window.alert("failed");
                                                }
                                                public void onSuccess(String result) {
                                                       Window.alert(result);
                                                }
                                         });
                     }
              });
             
              RootPanel.get().add(td);
              RootPanel.get().add(add);
              RootPanel.get().add(read);
       }
Last one point more about the Entity design:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Player {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
String Id;
String myName;
        //getter and setter
}

That's it :)
Ready.
:)
Run the project add text to db, and retrieve it using buttons add and retrieve.
Hope you enjoyed it, don’t hesitate to query on it. Thanks.

No comments:

Post a Comment