Advertisement
Guest User

Untitled

a guest
Apr 21st, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. object SystemPropertyClosure {
  2. trait PropertyProxy {
  3. def setProperty(key: String, value: String): String
  4. def clearProperty(key: String): String
  5.  
  6. def setProperty(key: String, value: Option[String]): Option[String] = value match {
  7. case Some(value) => Option { setProperty(key, value) }
  8. case None => Option { clearProperty(key) }
  9. }
  10. }
  11.  
  12. private def restoreProperties(history: Seq[(String, Option[String])]) {
  13. for {
  14. // get the FIRST value of each property set to restore it
  15. (key, value) <- history.groupBy(_._1).mapValues(_.head)
  16. } {
  17. value match {
  18. case Some(value) => System.setProperty(key, value)
  19. case None => System.clearProperty(key)
  20. }
  21. }
  22. }
  23.  
  24. def apply[T](body: PropertyProxy => T) = {
  25. val history = Seq.newBuilder[(String, Option[String])]
  26.  
  27. object propertyProxy extends PropertyProxy {
  28. private def wrapInteraction(key: String, action: => String) = {
  29. val last = action
  30. history += key -> Option(last)
  31. last
  32. }
  33.  
  34. def setProperty(key: String, value: String) = wrapInteraction(key, System.setProperty(key, value))
  35. def clearProperty(key: String) = wrapInteraction(key, System.clearProperty(key))
  36. }
  37.  
  38. val res = body(propertyProxy)
  39. restoreProperties(history.result)
  40. res
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement