Created
July 25, 2010 21:47
-
-
Save paulosuzart/489922 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) |
Method being generated as a instance method, not static.
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 :)
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
;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)