/scalate-util/src/main/scala/org/fusesource/scalate/util/URIs.scala

http://github.com/scalate/scalate · Scala · 63 lines · 22 code · 7 blank · 34 comment · 10 complexity · 3d387c5e5ed793afc55348af1948f2f0 MD5 · raw file

  1. /**
  2. * Copyright (C) 2009-2011 the original author or authors.
  3. * See the notice.md file distributed with this work for additional
  4. * information regarding copyright ownership.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. package org.fusesource.scalate.util
  19. /**
  20. * Some helper methods for working with URIs and query strings
  21. *
  22. * @version $Revision: 1.1 $
  23. */
  24. object URIs {
  25. /**
  26. * Creates a URI using a path and optional query string
  27. */
  28. def uri(path: String, query: String = "") = {
  29. if (query != null && query.length > 0) {
  30. val separator = if (path.contains("?")) "&" else "?"
  31. path + separator + query
  32. } else {
  33. path
  34. }
  35. }
  36. /**
  37. * Combines the URI path, query string with additional query terms which will avoid duplicates
  38. */
  39. def uriPlus(path: String, query: String, addQuery: String) = {
  40. val newQuery = (splitQuery(query) ++ splitQuery(addQuery)).distinct
  41. uri(path, joinQuery(newQuery))
  42. }
  43. /**
  44. * Removes the given query terms from the query string if they are there
  45. */
  46. def uriMinus(path: String, query: String, removeQuery: String) = {
  47. val remove = splitQuery(removeQuery)
  48. val newQuery = splitQuery(query).filter(!remove.contains(_))
  49. uri(path, joinQuery(newQuery))
  50. }
  51. /**
  52. * Split a query expression into separate clauses
  53. */
  54. protected def splitQuery(query: String): Seq[String] = if (query != null && query.length > 0) query.split("&").toSeq else Nil
  55. protected def joinQuery(queryArgs: Seq[String]) = queryArgs.mkString("&")
  56. }