Book Store Application with mongo DB
code: https://github.com/gnurmatova/jersey_simple_Mongo_
If you are going to use Mongo as your DB, you need to get comfortable with it, so please install it locally - follow instructions here: https://docs.mongodb.org/manual/installation/
You cannot use your local Mongo to power your heroku application, because your mongo has to be available on the internet, so we can look for SaaS Mongo solutions
It looks like Mongo HQ was acquired by another company and requires a credit card to use now, I could still continue to use it, likely because I created the account previously.
It was suggested to try https://mongolab.com/
That seem to have worked, so here it is, if you want to use Mongo for your DB, sign up for the account at https://mongolab.com/
After email verification, you should be able to create your DB:
On the Home screen, click "Create New"
You cannot use your local Mongo to power your heroku application, because your mongo has to be available on the internet, so we can look for SaaS Mongo solutions
It looks like Mongo HQ was acquired by another company and requires a credit card to use now, I could still continue to use it, likely because I created the account previously.
It was suggested to try https://mongolab.com/
That seem to have worked, so here it is, if you want to use Mongo for your DB, sign up for the account at https://mongolab.com/
After email verification, you should be able to create your DB:
On the Home screen, click "Create New"
Then select "Amazon Web Services" for the cloud provider, Single Node Plan and Sanbox instance for FREE
Once the database is created, you should be able to see the entry on the home screen and that would give you the connection parameters: To connect using the mongo shell: mongo ds047040.mlab.com:47040/unhedu -u <dbuser> -p <dbpassword> To connect using a driver via the standard MongoDB URI : mongodb://<dbuser>:<dbpassword>@ds047040.mlab.com:47040/unhedu |
Create a new user:
Click on Users -> Add database user ->provide username and password as prompted
Click on Users -> Add database user ->provide username and password as prompted
mongo Shell
if your Mongo installation was successful, you should be able to run mongo command in your terminal, like this:
$ mongo ds047040.mlab.com:47040/unhedu MongoDB shell version: 2.6.1 connecting to: ds047040.mlab.com:47040/unhedu Error while trying to show server startup warnings: not authorized on admin to execute command { getLog: "startupWarnings" } rs-ds047040:PRIMARY>
To get out of Mongo shell, just type exit
connecting to mongo and basic commands
Connect to Mongo
$ mongo ds053764.mlab.com:53764/unhedu -u unh -p unh MongoDB shell version: 3.2.3 connecting to: ds053764.mlab.com:53764/unhedu
Show collections
rs-ds053764:PRIMARY> show collections books system.indexes system.profile rs-ds053764:PRIMARY>
Create collection
rs-ds053764:PRIMARY> db.createCollection("users") { "ok" : 1 } rs-ds053764:PRIMARY> show collections books system.indexes system.profile users
or use GUI:
Insert document:
rs-ds053764:PRIMARY> db.books.insert( { "book":"Head First Java", "isbn":"1234", "author":"Kathy Sierra", "genre":"technology" } )
List all documents in a specific collection:
db.books.find({})
Find a document that matches a criteria:
rs-ds053764:PRIMARY> db.books.find({"book":"Head First Java"}) { "_id" : ObjectId("56d732ad71ca927d9090adc6"), "book" : "Head First Java", "isbn" : "1234", "author" : "Kathy Sierra", "genre" : "technology" }
It's case sensitive:
rs-ds053764:PRIMARY> db.books.find({"book":"Head First java"}) rs-ds053764:PRIMARY>
Matching by two items
rs-ds053764:PRIMARY> db.books.find({"book":"Head First Java", "isbn" : "1234"}) { "_id" : ObjectId("56d732ad71ca927d9090adc6"), "book" : "Head First Java", "isbn" : "1234", "author" : "Kathy Sierra", "genre" : "technology" }
Using regular expressions
rs-ds053764:PRIMARY> db.books.find({"isbn" :{ $regex:'1.*'}}) { "_id" : ObjectId("56d732ad71ca927d9090adc6"), "book" : "Head First Java", "isbn" : "1234", "author" : "Kathy Sierra", "genre" : "technology" }
Delete document
rs-ds053764:PRIMARY> db.books.remove({"isbn" :{ $regex:'1.*'}}) WriteResult({ "nRemoved" : 1 }) rs-ds053764:PRIMARY> db.books.find({"isbn" :{ $regex:'1.*'}}) rs-ds053764:PRIMARY>
Please note, I uploaded the code along with the host name and password, this is for you to learn, however, you have to be extremely careful uploading such info to public git repositories
Connecting to Database:
Connecting to Database:
package com.luckypants.mongo; import java.util.Arrays; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.MongoException; import com.mongodb.ServerAddress; public class ConnectionProvider { public MongoClient getConnection() { try { MongoCredential credential = MongoCredential.createCredential("unh", "unhedu", "unh".toCharArray()); MongoClient client = new MongoClient(new ServerAddress("ds053764.mlab.com", Integer.valueOf("53764")), Arrays.asList(credential)); return client; } catch (MongoException e) { e.printStackTrace(); } return null; } }
Book (Model)
package com.luckypants.model; import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @JsonIgnoreProperties(ignoreUnknown = true) public class Book { private String title; private String author; private String ISBN; @JsonDeserialize(as=ArrayList.class, contentAs=String.class) private ArrayList<String> genres; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getISBN() { return ISBN; } public void setISBN(String iSBN) { ISBN = iSBN; } public ArrayList<String> getGenres() { return genres; } @JsonDeserialize(as=ArrayList.class, contentAs=String.class) public void setGenres(ArrayList<String> genres) { this.genres = genres; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
Services:
package com.luckypants.books; import java.util.ArrayList; import java.util.HashMap; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.fasterxml.jackson.databind.ObjectMapper; import com.luckypants.command.CreateBookCommand; import com.luckypants.command.DeleteBookCommand; import com.luckypants.command.GetBookCommand; import com.luckypants.command.ListAllBooksCommand; import com.luckypants.model.Book; @Path("/books") public class BookService { ObjectMapper mapper = new ObjectMapper(); @GET @Produces(MediaType.APPLICATION_JSON) public Response listBooks() { ListAllBooksCommand listBooks = new ListAllBooksCommand(); ArrayList<Book> list = listBooks.execute(); String booksString = null; try { booksString = mapper.writeValueAsString(list); } catch (Exception e) { e.printStackTrace(); } return Response.status(200).entity(booksString).build(); } @GET @Path("/{key}/{value}") @Produces(MediaType.APPLICATION_JSON) public Response getBook(@PathParam("key") String key, @PathParam("value") String value) { GetBookCommand getBookCommand = new GetBookCommand(); Book book = getBookCommand.execute(key, value); String bookString = null; try { bookString = mapper.writeValueAsString(book); } catch (Exception e) { e.printStackTrace(); } return Response.status(200).entity(bookString).build(); } @POST @Produces(MediaType.APPLICATION_JSON) @Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN }) public Response createBook(String bookStr) { try { CreateBookCommand create = new CreateBookCommand(); Book book = mapper.readValue(bookStr, Book.class); boolean success = create.execute(book); if (success) { return Response.status(201).build(); } else return Response.status(400).build(); } catch (Exception e) { return Response.status(400).entity(e.toString()).build(); } } @GET @Path("/search") @Produces(MediaType.APPLICATION_JSON) public Response searchBook( @DefaultValue("*") @QueryParam("query") String query, @DefaultValue("author") @QueryParam("sortby") String sortby) { HashMap<String, String> responseMap = new HashMap<String, String>(); responseMap.put("query", query); responseMap.put("sortby", sortby); String rString = ""; try { rString = mapper.writeValueAsString(responseMap); } catch (Exception e) { e.printStackTrace(); return Response.status(500).entity(e.toString()).build(); } return Response.status(200).entity(rString).build(); } @DELETE @Path("/{isbn}") public Response deleteBook(@PathParam("isbn") String isbn) { DeleteBookCommand delete = new DeleteBookCommand(); delete.execute(isbn); return Response.status(200).build(); } }
Commands:
package com.luckypants.command; import org.bson.Document; import org.bson.types.ObjectId; import com.fasterxml.jackson.databind.ObjectMapper; import com.luckypants.model.Book; import com.luckypants.mongo.ConnectionProvider; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class GetBookCommand { ObjectMapper mapper = new ObjectMapper(); public Book execute(String key, String value) { MongoClient client = (new ConnectionProvider()).getConnection(); MongoDatabase mdb = client.getDatabase("unhedu"); MongoCollection<Document> booksColl = mdb.getCollection("books"); BasicDBObject searchQuery = new BasicDBObject(); if (key.equals("_id")) { searchQuery.put(key, new ObjectId(value)); } else { searchQuery.put(key, value); } FindIterable<Document> book = booksColl.find(searchQuery); client.close(); return mapper.convertValue(book.first(), Book.class); } }
package com.luckypants.command; import java.util.ArrayList; import org.bson.Document; import com.fasterxml.jackson.databind.ObjectMapper; import com.luckypants.model.Book; import com.luckypants.mongo.ConnectionProvider; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class ListAllBooksCommand { ObjectMapper mapper = new ObjectMapper(); public ArrayList<Book> execute() { MongoClient client = (new ConnectionProvider()).getConnection(); MongoDatabase mdb = client.getDatabase("unhedu"); MongoCollection<Document> booksColl = mdb.getCollection("books"); ArrayList<Book> books = new ArrayList<Book>(); try { FindIterable<Document> cursor = booksColl.find(); for (Document c : cursor) { Book b = mapper.convertValue(c, Book.class); books.add(b); } } catch (Exception e) { e.printStackTrace(); } finally{ client.close(); } return books; } }
package com.luckypants.command; import org.bson.Document; import com.fasterxml.jackson.databind.ObjectMapper; import com.luckypants.model.Book; import com.luckypants.mongo.ConnectionProvider; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class CreateBookCommand { public boolean execute(Book book) { MongoClient client = (new ConnectionProvider()).getConnection(); MongoDatabase mdb = client.getDatabase("unhedu"); MongoCollection<Document> booksColl = mdb.getCollection("books"); ObjectMapper mapper = new ObjectMapper(); try { Document dbObject = new Document(Document.parse(mapper.writeValueAsString(book))); booksColl.insertOne(dbObject); } catch (Exception e) { System.out.println("ERROR during mapping book to Mongo Object"); return false; } finally{ client.close(); } return true; } }
package com.luckypants.command; import org.bson.Document; import com.luckypants.mongo.ConnectionProvider; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; public class DeleteBookCommand { public boolean execute(String isbn) { MongoClient client = (new ConnectionProvider()).getConnection(); MongoDatabase mdb = client.getDatabase("unhedu"); MongoCollection<Document> booksColl = mdb.getCollection("books"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("isbn", isbn); booksColl.deleteOne(searchQuery); client.close(); return true; } }