/server/src/main/scala/store.scala

https://github.com/softprops/hush · Scala · 82 lines · 73 code · 9 blank · 0 comment · 2 complexity · f4faa5e23458b3969d245f6b60412fec MD5 · raw file

  1. package hush
  2. import com.mongodb.casbah._
  3. import com.mongodb.MongoURI
  4. import java.net.URI
  5. object Store {
  6. import com.mongodb.casbah.commons.Imports.ObjectId
  7. import com.mongodb.casbah.commons.{MongoDBObject => Obj, MongoDBList => ObjList}
  8. import com.mongodb.casbah.{MongoCollection}
  9. import com.mongodb.{BasicDBList, DBObject}
  10. import com.mongodb.casbah.query.{GeoCoords}
  11. import com.mongodb.casbah.Implicits._
  12. import com.mongodb.casbah.query.Imports._
  13. import java.util.Date
  14. lazy val db = {
  15. val uri = new URI(Props.get("MONGOLAB_URI"))
  16. try {
  17. val conn = MongoConnection(uri.getHost, uri.getPort)
  18. val name = uri.getPath.drop(1)
  19. val mongo = conn(name)
  20. val Array(user, pass) = uri.getUserInfo.split(":")
  21. mongo.authenticate(user, pass)
  22. mongo
  23. } catch {
  24. case e:java.io.IOException => println(
  25. "Error occured whilst connecting to mongo (%s): %s" format(
  26. uri, e.getMessage), Some(e)
  27. )
  28. throw e
  29. }
  30. }
  31. def collection[T](name: String)(f: MongoCollection => T): T = f(db(name))
  32. private def toDbObjects(places: Seq[Place]) =
  33. for(p <- places) yield {
  34. Obj(
  35. "id" -> p.id,
  36. "loc" -> ObjList(p.lat, p.lon),
  37. "name" -> p.name,
  38. "kind" -> p.kind
  39. )
  40. }
  41. private def toPlace(m:Obj) =
  42. try {
  43. val (lat, lon) = m.getAs[BasicDBList]("loc").get match {
  44. case bdbl: BasicDBList =>
  45. val l: ObjList = bdbl
  46. (l(0).asInstanceOf[Double], l(1).asInstanceOf[Double])
  47. }
  48. Place(
  49. m.getAs[String]("id").get,
  50. lat, lon,
  51. m.getAs[String]("name").get,
  52. m.getAs[String]("kind").get
  53. )
  54. } catch {
  55. case e =>
  56. println("failed to parse %s" format m)
  57. throw e
  58. }
  59. implicit val toPlaces: Iterator[DBObject] => Iterable[Place] =
  60. (m) => (for(p <- m) yield toPlace(p)).toSeq
  61. def save(places: Seq[Place]) = {
  62. collection("quiet_places") { c =>
  63. for(dbo <- toDbObjects(places)) c.insert(dbo)
  64. }
  65. }
  66. def quietPlaces[T](ll: (Double, Double))(f: Iterable[Place] => T) =
  67. collection("quiet_places") { c =>
  68. val (lat, lon) = ll
  69. val query = "loc".$within $center ((lat, lon), 0.01)
  70. println(query)
  71. f(toPlaces(c.find( query )))
  72. }
  73. }