Create a GWT, morphia, mongoDB app in 1 minute
- rakeshnbr
- Mar 6, 2012
- 4 min read
Ever wished you could get out of Google app engine dependency and deploy your app somewhere else??? But still finding yourself tied up with app engine data store?
I think the following tutorial would help you to migrate or kick start your new project with right combination.
Please note that this is not a GWT+ MongoDB sample, but this will give you some inputs to start your coding.
Front end: GWT
Back end: Morphia + MongoDB
This is going to be a bottom up approach on developing a prototype.
Step 1) Download mongo db:
http://www.mongodb.org/downloads
Step 2)Let’s get familiar with mongo db first.
Extract it and you will get a folder with name similar to "mongodb-linux-i686-2.0.0"
Start mongo db: ./bin/mongod --port=27017 --dbpath=/home/{yourhome}/{an existing
directory} &
Get the admin console: ./bin/mongo mytestdb
(this command will automatically create mytestdb for you)
To create a collection called user
> db.createCollection("user", {capped:true, size:100000})
insert some stuffs into user
> input = {name: 'rakesh', password: 'rakesh'}
> db.user.insert(input)
Step 3) Now Let us write some code
Morphia gives us the domain persistence, hope you have downloaded morphia and the jar is
in your classpath
I want to define couple of entities first, Let say UserEntity
package com.mongotest.entities; import com.google.code.morphia.annotations.Embedded; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Indexed; /** * The (base) UserEntity, so we don't have to duplicate code for full blown entities. * It's using @Indexed, @Indexed(unique=true), @Reference, @Transient, and @Embedded. * Additionally making use of @PrePersist and @PostLoad. */ @Entity(value="user", noClassnameStored=true) public class UserEntity extends BaseEntity { @Indexed private String username; @Indexed(unique=true) private String email; private String password; @Embedded private CompanyEntity company; private boolean active; public UserEntity() { super(); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword(){ return password; } public void setPassword(String password){ this.password = password; } public CompanyEntity getCompany() { return company; } public void setCompany(CompanyEntity company) { this.company = company; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (( id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; UserEntity other = (UserEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return String.format("UserEntity [id=%s, username=%s, email=%s, company=%s]", id, username, email, company); } public void setActive(boolean b) { this.active = b; } public boolean isActivated() { return active; } }
Step 4)We are going to create a db and store some users and retrieve it.
Create a class called JustTestMongo.java
public class JustTestMongo{ private final Datastore datastore; public static final String DB_NAME = "mydbname"; private JustTestMongo() { try { Mongo mongo = new Mongo("127.0.0.1", 27017); datastore = new Morphia().mapPackage("com.mongotest.entities").createDatastore(mongo, DB_NAME); datastore.ensureIndexes(); } catch (Exception e) { throw new RuntimeException("Error initializing MongoDB", e); } } public static void main(String[] arg){ UserEntity userEntity = new UserEntity(); userEntity.setUsername("administrator"); userEntity.setEmail("administrator@mycompany.com"); userEntity.setPassword("password-123"); new MongoDB().getDatabase().save(userEntity); getAndAuthorize("administrator", "password-123"); } private static void getAndAuthorize(String name, String password) { List userList = new MongoDB().getDatabase().find(UserEntity.class).filter("username", name).asList(); if(userList.size() == 1){ if(password.equals(userList.get(0).getPassword())){ System.out.println("done....You have successfuly completed the sample"); } } } }
When you create the instance you mention the package name of entities and the db
name...That’s it.
It will create the collection in db corresponding to each entity.
Look at the main. We are creating an entity and saving that as a collection into mongodb.
getAndAuthorize method gets back all the user entities and just does validation.
Run the main and see. You should get the message "done....You have successfuly
completed the sample", if you have done everything properly. Or Some real weird
exceptions, which even I don’t know.
Step 5) Now let’s re-factor the stuff.
Of course I don’t like JustTestMongo.java, and want to change that, neither do
I want multiple instance of my db connection..
Let me create a new class MongodbPersistence
public class MongodbPersistence { private Datastore mongoDatastore; public MongodbPersistence() { mongoDatastore = MongoDB.instance().getDatabase(); } public void createUser(UserEntity user){ new MongoDB().getDatabase().save(user); } public boolean authorizeMe(String name, String password){ List userList = new MongoDB().getDatabase().find(UserEntity.class).filter("username", name).asList(); if(userList.size() == 1){ if(password.equals(userList.get(0).getPassword())){ System.out.println("done....You have successfuly completed the sample"); }else{ return false; } }else{ return false; } } }
JustTestMongo.java has been renamed to MongoDB.java and the re-factored code is as
follows.
public class MongoDB { private static final MongoDB INSTANCE = new MongoDB(); private final Datastore datastore; public static final String DB_NAME = "mydbname"; private MongoDB() { try { Mongo mongo = new Mongo("127.0.0.1", 27017); datastore = new Morphia().mapPackage("com.mongotest.entities").createDatastore(mongo, DB_NAME); datastore.ensureIndexes(); } catch (Exception e) { throw new RuntimeException("Error initializing MongoDB", e); } } public static MongoDB instance() { return INSTANCE; } public Datastore getDatabase() { return datastore; } }
Step 6) Your baby is Ready…Write a GWT RPC service with
registerUser(String username, String password,......blah blah)
authorizeUser(String username, String password)
Let the service impl say like this.... new MongodbPersistence().createUser(user)
oh...I missed one part. If we are using GWT RPC, we need to define a Data Transfer Object.
One of the integration strategy which is same like gwt+hibernet: http://code.google.com/webtoolkit/articles/using_gwt_with_hibernate.html
Step 7) Create UI in gwt
Create a new gwt project and create the UI widgets for registration and login.
I think steps 6, 7 are straight forward if you have prior experience in GWT.

Comments