8000 Added utility classes used in parts db app. · randomcoding/scala-utilities@fa92cad · GitHub
[go: up one dir, main page]

Skip to content

Commit fa92cad

Browse files
committed
Added utility classes used in parts db app.
1 parent 717eefd commit fa92cad

File tree

6 files changed

+647
-0
lines changed

6 files changed

+647
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
* Copyright (C) 2012 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.core.datatime.joda
21+
22+
import org.joda.time.DateTime
23+
import org.joda.time.format.DateTimeFormat
24+
25+
/**
26+
* Methods to work with Dates & Times
27+
*
28+
* These mainly use the `JodaTime` classes and provide an implicit conversion from a `java.util.Date` to a `org.joda.time.DateTime`
29+
*
30+
* @author RandomCoder <randomcoder@randomcoding.co.uk>
31+
*/
32+
object DateHelpers {
33+
34+
/**
35+
* Default date format for use with to string calls.
36+
*
37+
* This will render a date as 05/12/2012 for Dec. 5th 2012
38+
*/
39+
final val shortDateFormat = "dd/MM/yyyy"
40+
41+
/**
42+
* Get a date as a string, using the default [[uk.co.randomcoding.partsdb.lift.util.DateHelpers#dateFormat]]
43+
*/
44+
def dateString(date: DateTime) = date.toString(shortDateFormat)
45+
46+
def date(dateString: String, format: String = shortDateFormat): DateTime = {
47+
val formatter = DateTimeFormat.forPattern(format)
48+
formatter.parseDateTime(dateString).toDate()
49+
}
50+
51+
/**
52+
* Implicit conversion from a `java.util.Date` to a `org.joda.time.DateTime`
53+
*/
54+
implicit def dateToJoda(date: java.util.Date): DateTime = new DateTime(date)
55+
56+
implicit def jodaToDate(dateTime: DateTime): java.util.Date = dateTime.toDate()
57+
}
Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
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+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
* Copyright (C) 2012 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 net.liftweb.record.field._
23+
import net.liftweb.mongodb.record.field.ObjectIdRefField
24+
import org.bson.types.ObjectId
25+
import net.liftweb.mongodb.record.field.ObjectIdRefListField
26+
27+
/**
28+
* Contains implicit conversions for basic field types to their values. This avoids the continual use of `.get`
29+
*
30+
* @author RandomCoder <randomcoder@randomcoding.co.uk>
31+
*/
32+
object MongoFieldHelpers {
33+
34+
implicit def doubleFieldToDouble(field: DoubleField[_]): Double = field.get
35+
36+
implicit def intFieldToDouble(field: IntField[_]): Int = field.get
37+
38+
implicit def stringFieldToString(field: StringField[_]): String = field.get
39+
40+
implicit def typedIdFieldToId(field: ObjectIdRefField[_, _]): ObjectId = field.get
41+
42+
implicit def typedListIdFieldToId(field: ObjectIdRefListField[_, _]): List[ObjectId] = field.get
43+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* Copyright (C) 2012 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 org.bson.types.ObjectId
23+
24+
/**
25+
* Helper functions and implicit conversions to make Mongo DB a little easier to use with the PDWA API
26+
*
27+
* @author RandomCoder <randomcoder@randomcoding.co.uk>
28+
*/
29+
object MongoHelpers {
30+
31+
/**
32+
* Convert a String to a BSON `ObjectId`. If the String is not a valid `ObjectId` this implicit conversion will fail at runtime
33+
*/
34+
implicit def stringToObjectId(oid: String): ObjectId = new ObjectId(oid)
35+
36+
implicit def objectIdToString(oid: ObjectId): String = oid.toString
37+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Copyright (C) 2012 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.snippet
21+
22+
import net.liftweb.http.SHtml._
23+
24+
/**
25+
* Contains definitions of commonly used `ElemAttr`s.
26+
*
27+
* @author RandomCoder <randomcoder@randomcoding.co.uk>
28+
*/
29+
object StyleAttributes {
30+
31+
/**
32+
* Applies the required class styles to a widget to be styled by JQueryUI's css
33+
*/
34+
val jqueryUiTextStyled: ElemAttr = "class" -> "ui-widget ui-state-default ui-corner-all"
35+
}

0 commit comments

Comments
 (0)
0