Skip to content

Instantly share code, notes, and snippets.

@paulosuzart
Created July 25, 2010 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paulosuzart/489922 to your computer and use it in GitHub Desktop.
Save paulosuzart/489922 to your computer and use it in GitHub Desktop.
(ns org.jtornadoweb.cljhttputils
(:gen-class
:name org.jtornadoweb.CljHttpUtils
:methods [[parseQueryString [String] java.util.HashMap]]
:main false))
(defn #^:static
-parseQueryString
"Return all parameters in a HashMap. Same as python cgi.pase_qs. If no parameters are
found , returns an empty Map of parameters (not null)."
[this uri]
(def mp (java.util.HashMap.))
(let [q (.split (.replaceAll uri "[\\?/]" "") "[&]")]
(if (not= (aget q 0) "")
(doseq [i q]
(let [pair (.split i "=")]
(.put mp (first pair) (second pair))))))
mp)
@paulosuzart
Copy link
Author

;version for compilation and using hashmap
(ns org.jtornadoweb.cljhttputils
(:gen-class
:name org.jtornadoweb.CljHttpUtils
:methods [[parseQueryString [String] java.util.HashMap]]
:main false))

(defn #^:static
-parseQueryString
"Return all parameters in a HashMap. Same as python cgi.pase_qs. If no parameters are
found , returns an empty Map of parameters (not null)."
[this uri](def mp %28java.util.HashMap.%29)
(let [q (.split (.replaceAll uri "[?/]" "") "[&]")](if %28not= %28aget q 0%29)
(doseq [i q](let [pair %28.split i)]
(.put mp (first pair) (second pair))))))
mp)

@paulosuzart
Copy link
Author

Method being generated as a instance method, not static.

@alandipert
Copy link

Nice! Note that 'def' on line 12 puts 'mp' in the namespace, so you'd probably want a 'let' for that. Also, in most cases you can use Clojure data types for your actual work, and turn them into Java ones at the last minute. This is an interesting problem, Gist forthcoming. Happy Clojuring :)

@paulosuzart
Copy link
Author

Thanks Alan. As you can see I'm new to clj :P I'll try to use a clojure map instead. One point that made me use a HashMap directly was mutability. Using a Ref for a simple task like this sounds a bit overwhelming. Let see!
The previous version uses a Ref to a Clj Map, would that code slower than this last version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment