|
| 1 | +/* |
| 2 | + * Copyright (C) 2011 RandomCoder <randomcoder@randomcoding.co.uk> |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as |
| 6 | + * published by the Free Software Foundation, either version 3 of the |
| 7 | + * License, or (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU Affero General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU Affero General Public License |
| 15 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 | + * |
| 17 | + * Contributors: |
| 18 | + * RandomCoder - initial API and implementation and/or initial documentation |
| 19 | + */ |
| 20 | +package uk.co.randomcoding.scala.util.lift.mongodb |
| 21 | + |
| 22 | +import com.mongodb.Mongo |
| 23 | + |
| 24 | +import net.liftweb._ |
| 25 | +import json._ |
| 26 | +import mongodb._ |
| 27 | +import common._ |
| 28 | + |
| 29 | +/** |
| 30 | + * Initialisation for Mongo DB |
| 31 | + * |
| 32 | + * @author RandomCoder |
| 33 | + * |
| 34 | + * Created On: 19 Aug 2011 |
| 35 | + * |
| 36 | + */ |
| 37 | +object MongoConfig extends Logger { |
| 38 | + |
| 39 | + private implicit val formats = DefaultFormats |
| 40 | + |
| 41 | + private var usingCloudfoundry = false |
| 42 | + private var cloudfoundryDbName = "" |
| 43 | + |
| 44 | + // Case classes required to parse CloudFoundry JSON |
| 45 | + case class CloudFoundryMongo(name: String, label: String, plan: String, credentials: CloudFoundryMongoCredentials) |
| 46 | + case class CloudFoundryMongoCredentials(hostname: String, port: String, username: String, password: String, name: String, db: String) |
| 47 | + |
| 48 | + /** |
| 49 | + * Initialise a named MongoDB database |
| 50 | + * |
| 51 | + * This checks to see if the connection is to a [[http://cloudfoundry.org|CloudFoundry]] instance or not. |
| 52 | + * If the connection is local such as in an offline installation or for testing then will connect to the database called '''dbName''' otherwise |
| 53 | + * it will connect to the CF database specified in the connection settings that are provided by CloudFoundry |
| 54 | + * |
| 55 | + * Furthermore, a local connection assumes that MongoDB is running on port 27017 and is accessible via `127.0.0.1` |
| 56 | + * |
| 57 | + * This will use the `DefaultMongoIdentifier` to identify the named database, so (I think) only one database can be used at a time. |
| 58 | + * |
| 59 | + * @param dbName The name of the local database to connect to. If connecting to a CloudFoundry database then this parameters is ignored and can be empty. |
| 60 | + * |
| 61 | + */ |
| 62 | + def init(dbName: String): Unit = { |
| 63 | + mongoConnectionDetails(dbName) match { |
| 64 | + case Some(x) => x match { |
| 65 | + case config: MongoConnectionConfig => { |
| 66 | + debug("Received config details: %s".format(config)) |
| 67 | + config match { |
| 68 | + case MongoConnectionConfig(host, port, user, pass, db, true) => { |
| 69 | + debug("Got Mongo Config for CloudFoundry") |
| 70 | + MongoDB.defineDbAuth(DefaultMongoIdentifier, new Mongo(host, port), db, user, pass) |
| 71 | + } |
| 72 | + case MongoConnectionConfig(_, _, _, _, db, false) => { |
| 73 | + debug("Unsing local Mongo Config") |
| 74 | + MongoDB.defineDb(DefaultMongoIdentifier, new Mongo, db) |
| 75 | + } |
| 76 | + case _ => error("Failed To initialise mongo DB Connection!") |
| 77 | + } |
| 78 | + } |
| 79 | + case _ => error("Failed To initialise mongo DB Connection!") |
| 80 | + } |
| 81 | + case _ => error("Failed To initialise mongo DB Connection!") |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private implicit def hostToMongo(host: (String, Int)): Mongo = new Mongo(host._1, host._2) |
| 86 | + |
| 87 | + private def mongoConnectionDetails(dbName: String): Option[MongoConnectionConfig] = { |
| 88 | + debug("Env: VCAP_SERVICES: %s".format(Option(System.getenv("VCAP_SERVICES")))) |
| 89 | + |
| 90 | + try { |
| 91 | + Option(System.getenv("VCAP_SERVICES")) match { |
| 92 | + case Some(s) => { |
| 93 | + debug("We seems to be running on Cloud Foundry. Attempting to extract connection details") |
| 94 | + debug("Received JSON: %s".format(s)) |
| 95 | + parse(s) \\ "mongodb-1.8" match { |
| 96 | + case JArray(ary) => extractConfigFromCfJson(ary) |
| 97 | + case x => { |
| 98 | + warn("Json parse error: %s".format(x)) |
| 99 | + None |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + case _ => { |
| 104 | + debug("Not running on Cloud Foundry, assuming localhost connection on port 27017") |
| 105 | + Some(MongoConnectionConfig("127.0.0.1", 27017, "", "", dbName, false)) |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + catch { |
| 110 | + case e: MatchError => { |
| 111 | + error("Match Error: %s\n%s\n%s.\n\nAssuming a service is running locally on port 27017".format(e.getMessage(), e.getCause(), e.getStackTrace().mkString("", "\n", ""))) |
| 112 | + None |
| 113 | + } |
| 114 | + case e: Exception => { |
| 115 | + error("Encountered an exception when attempting to initialise connection to MongoDB: %s. Cannot connect!".format(e.getMessage)) |
| 116 | + None |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + private[this] def extractConfigFromCfJson(ary: Seq[JValue]) = { |
| 122 | + // TODO: This loop could/should be made to identify the element it wants and then use just that one |
| 123 | + var config: Option[MongoConnectionConfig] = None |
| 124 | + |
| 125 | + ary foreach { mongoJson => |
| 126 | + val mongo = mongoJson.extract[CloudFoundryMongo] |
| 127 | + val credentials = mongo.credentials |
| 128 | + debug("Extracted CloudFoundry MongoDB: %s\nWith Credentials: %s".format(mongo, credentials)) |
| 129 | + config = Some(MongoConnectionConfig(credentials.hostname, credentials.port.toInt, credentials.username, credentials.password, credentials.db, true)) |
| 130 | + } |
| 131 | + |
| 132 | + debug("Using mongodb cloudfoundry config: %s".format(config)) |
| 133 | + config |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +/** |
| 138 | + * Container for the connection details |
| 139 | + * |
| 140 | + * @constructor Creates a new instance of the connection config |
| 141 | + * @param host The host name or ip to connect to |
| 142 | + * @param port The port to connect to on the host |
| 143 | + * @param user The username to use for authentication |
| 144 | + * @param password The password to use for authentication |
| 145 | + * @param onCloudFoundry A flag to indicate whether or not this is a connection to a CloudFoundry instance. |
| 146 | + * |
| 147 | + * @throws IllegalArgumentException if the `dbName` parameter is empty |
| 148 | + */ |
| 149 | +case class MongoConnectionConfig(host: String, port: Int, user: String, password: String, dbName: String, onCloudFoundry: Boolean) { |
| 150 | + require(dbName.trim nonEmpty, "DB Name Cannot be empty") |
| 151 | +} |
0 commit comments