Created
December 3, 2012 21:11
-
-
Save louismrose/4198081 to your computer and use it in GitHub Desktop.
ENAR - MongoDB on Heroku
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.net.UnknownHostException; | |
import java.util.Set; | |
import java.util.logging.Logger; | |
import javax.servlet.ServletConfig; | |
import javax.servlet.ServletException; | |
import javax.servlet.ServletOutputStream; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import com.mongodb.BasicDBObject; | |
import com.mongodb.DB; | |
import com.mongodb.DBCollection; | |
import com.mongodb.DBCursor; | |
import com.mongodb.MongoURI; | |
public class HelloServlet extends HttpServlet { | |
@Override | |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) | |
throws ServletException, IOException { | |
ServletOutputStream out = resp.getOutputStream(); | |
DB db = openConnection(); | |
// write | |
DBCollection coll = db.getCollection("test"); | |
coll.insert(new BasicDBObject().append("changenum", "third")); | |
// read all | |
DBCursor cursor = coll.find(); | |
out.write(("This is my " + cursor.next().get("changenum") + " change").getBytes()); | |
out.flush(); | |
out.close(); | |
} | |
private DB openConnection() throws UnknownHostException { | |
MongoURI mongoURI = new MongoURI(System.getenv("MONGOHQ_URL")); | |
DB db = mongoURI.connectDB(); | |
db.authenticate(mongoURI.getUsername(), mongoURI.getPassword()); | |
return db; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<dependency> | |
<groupId>org.mongodb</groupId> | |
<artifactId>mongo-java-driver</artifactId> | |
<version>2.9.1</version> | |
</dependency> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to add a MongoDB add-on to your Heroku app! I used the Mongo HQ add-on.