Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.73 KB | None | 0 0
  1. package se.osten.paths
  2.  
  3. import com.google.common.collect.Lists
  4. import com.google.gson.Gson
  5. import com.google.gson.reflect.TypeToken
  6. import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree
  7. import com.googlecode.concurrenttrees.radix.RadixTree
  8. import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharArrayNodeFactory
  9. import se.osten.beans.City
  10. import se.osten.utils.log
  11. import spark.Spark.get
  12. import spark.Spark.path
  13. import java.nio.charset.Charset
  14.  
  15. class CityPath() {
  16.  
  17.     val gson = Gson()
  18.     val rawCitiesString: String = this.javaClass.getResource("cities.json").readText(Charset.forName("UTF-8"));
  19.     val cityType = object : TypeToken<ArrayList<City>>() {}.type
  20.     val citiesList = gson.fromJson<ArrayList<City>>(rawCitiesString, cityType);
  21.     val MINIMUM_QUERY_LENGTH = 2;
  22.     val tree: RadixTree<City> = ConcurrentRadixTree(DefaultCharArrayNodeFactory())
  23.  
  24.     init {
  25.         citiesList.forEach { city ->
  26.             tree.putIfAbsent(city.name, city.copy());
  27.         }
  28.     }
  29.  
  30.     fun enableResource() {
  31.         path("/city") {
  32.             get("/:id") { req, res ->
  33.                 val capitalizedKeyword = req.params(":id").substring(0, 1).toUpperCase() + req.params(":id").substring(1);
  34.                 if(capitalizedKeyword.length <= MINIMUM_QUERY_LENGTH){
  35.                     res.type("text/html")
  36.                     "<h1>You should be more specific</h1>"
  37.                 }else{
  38.                     res.type("application/json")
  39.                     val cities = tree.getValuesForKeysStartingWith(capitalizedKeyword);
  40.                     log(req, " ${cities.count()} results delivered")
  41.                     gson.toJson(Lists.newArrayList(cities))
  42.                 }
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement