Created
March 27, 2013 14:27
-
-
Save anonymous/5254565 to your computer and use it in GitHub Desktop.
Using scala Try around configurations read from file to open a MongoDB connection
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
import scala.util._ | |
import java.util.Properties | |
import java.io.FileInputStream | |
val config = Try { | |
val prop = new Properties() | |
prop.load(new FileInputStream("config.properties")) | |
( | |
prop.getProperty("mongo.host"), | |
new Integer(prop.getProperty("mongo.port")), | |
prop.getProperty("mongo.db"), | |
prop.getProperty("mongo.coll.docs") | |
) | |
} | |
//now config is of type Try, and you can play with that. you can: | |
//match the result | |
config match { | |
case Success((host, port, dbName, docsCollName)) => | |
//do what you need with the single properties | |
case Failure(ex) => | |
//do what you need with the exception | |
} | |
//get the value if it's a success or else use a default | |
val (host, port, dbName, docsCollName) = config.getOrElse(("127.0.0.1", 27017, "defaultDB", "defaultDocs")) | |
//convert the success to an option | |
val optConfig: Option[(String, Integer, String, String))] = config.toOption | |
//recover with a function | |
val Success((host, port, dbName, docsCollName)) = config recover { | |
t: Throwable => | |
//based on the error you can create the new configuration parameters | |
} | |
/* | |
* map the configuration to a Try of MongoCollection with Casbah (scala library for mongo) | |
* you have the same operations available with the returned mongo collection as for config, | |
* until you eventually decide to handle the error or end the program successfully | |
*/ | |
import com.mongodb.casbah._ | |
import Imports._ | |
val collection: Try[MongoCollection] = config map { | |
(host, port, dbName, docsCollName) => | |
val client = MongoClient(host, port) | |
client(dbName)(docsCollName) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment