Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object SystemPropertyClosure {
- trait PropertyProxy {
- def setProperty(key: String, value: String): String
- def clearProperty(key: String): String
- def setProperty(key: String, value: Option[String]): Option[String] = value match {
- case Some(value) => Option { setProperty(key, value) }
- case None => Option { clearProperty(key) }
- }
- }
- private def restoreProperties(history: Seq[(String, Option[String])]) {
- for {
- // get the FIRST value of each property set to restore it
- (key, value) <- history.groupBy(_._1).mapValues(_.head)
- } {
- value match {
- case Some(value) => System.setProperty(key, value)
- case None => System.clearProperty(key)
- }
- }
- }
- def apply[T](body: PropertyProxy => T) = {
- val history = Seq.newBuilder[(String, Option[String])]
- object propertyProxy extends PropertyProxy {
- private def wrapInteraction(key: String, action: => String) = {
- val last = action
- history += key -> Option(last)
- last
- }
- def setProperty(key: String, value: String) = wrapInteraction(key, System.setProperty(key, value))
- def clearProperty(key: String) = wrapInteraction(key, System.clearProperty(key))
- }
- val res = body(propertyProxy)
- restoreProperties(history.result)
- res
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement