PageRenderTime 22ms CodeModel.GetById 13ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/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 */
18package org.fusesource.scalate.util
19
20/**
21 * Some helper methods for working with URIs and query strings
22 *
23 * @version $Revision: 1.1 $
24 */
25object URIs {
26
27  /**
28   * Creates a URI using a path and optional query string
29   */
30  def uri(path: String, query: String = "") = {
31    if (query != null && query.length > 0) {
32      val separator = if (path.contains("?")) "&" else "?"
33      path + separator + query
34    } else {
35      path
36    }
37  }
38
39  /**
40   * Combines the URI path, query string with additional query terms which will avoid duplicates
41   */
42  def uriPlus(path: String, query: String, addQuery: String) = {
43    val newQuery = (splitQuery(query) ++ splitQuery(addQuery)).distinct
44    uri(path, joinQuery(newQuery))
45
46  }
47
48  /**
49   * Removes the given query terms from the query string if they are there
50   */
51  def uriMinus(path: String, query: String, removeQuery: String) = {
52    val remove = splitQuery(removeQuery)
53    val newQuery = splitQuery(query).filter(!remove.contains(_))
54    uri(path, joinQuery(newQuery))
55  }
56
57  /**
58   * Split a query expression into separate clauses
59   */
60  protected def splitQuery(query: String): Seq[String] = if (query != null && query.length > 0) query.split("&").toSeq else Nil
61
62  protected def joinQuery(queryArgs: Seq[String]) = queryArgs.mkString("&")
63}