diff options
Diffstat (limited to 'src/utils.clj')
| -rwxr-xr-x | src/utils.clj | 78 |
1 files changed, 68 insertions, 10 deletions
diff --git a/src/utils.clj b/src/utils.clj index d6a95e5..d2575c6 100755 --- a/src/utils.clj +++ b/src/utils.clj @@ -4,7 +4,8 @@ java.net.URLDecoder org.antlr.stringtemplate.StringTemplateGroup) (:use clojure.contrib.json.write - clojure.contrib.sql)) + clojure.contrib.sql + compojure)) (let [db-host "localhost" db-port 5432 @@ -20,6 +21,20 @@ ;; Misc +(declare stringify-and-escape) +(defn escape-html-deep [o] + (if (map? o) + (stringify-and-escape o) + (if (seq? o) + (map escape-html-deep o) + (escape-html o)))) + +(defn stringify-and-escape [m] + (zipmap (map str* (keys m)) (map escape-html-deep (vals m)))) + +(defn nor [& args] + (not-any? identity args)) + (defn no-args-adaptor [f] (fn [& more] (f))) @@ -32,13 +47,6 @@ (defn join [lst int] (apply str (interpose int lst))) -(def YYYYMMDD-format (new SimpleDateFormat "yyyyMMdd")) - -(defn today [] - (.format YYYYMMDD-format (new Date))) - -(def formatter (new SimpleDateFormat "h:mm a EEE M/d")) - (defn non-empty-string? [s] (cond (string? s) (> (count s) 0) :else s)) @@ -49,13 +57,55 @@ (defn kbytes [b] (* b 1024)) (defn mbytes [b] (* b 1024 1024)) -;; JSON responses +;; Formatters (def yyyy-mm-dd-formatter (new SimpleDateFormat "yyyy-MM-dd")) +(defn format-yyyy-mm-dd [d] + (.format yyyy-mm-dd-formatter d)) + +(def yymmdd-formatter (new SimpleDateFormat "yyyyMMdd")) + +(defn format-yyyymmdd [d] + (.format yymmdd-formatter d)) + +(defn today [] + (format-yyyymmdd (new Date))) + +(def timestamp-formatter (new SimpleDateFormat "h:mm a EEE M/d")) +(def date-first-timestamp-formatter (new SimpleDateFormat "M/d h:mm a")) + +(defn format-timestamp [d] + (.format timestamp-formatter d)) + +(defn format-date-first-timestamp [d] + (.format date-first-timestamp-formatter d)) + +(defn pluralize [word val] + (if (= val 1) word (str word "s"))) + +(defn format-interval [i] + (let [vals [(.getYears i) + (.getMonths i) + (.getDays i) + (.getHours i) + (.getMinutes i)] + labels ["year" "month" "day" "hour" "minute"] + arr (into [] (for [[l v] (map vector labels vals) :when (> v 0)] + (str v " " (pluralize l v))))] + (join arr ", "))) + +(defn apply-formats [formats d] + (into {} (for [[k v] d] + (if-let [f (formats k)] + [k (f v)] + [k v])))) + +;; JSON responses + (defmethod print-json Date [d] - (print-json (.format yyyy-mm-dd-formatter d))) + (print-json (format-yyyy-mm-dd d))) (defn resp-error [message] {:status 400 :headers {} :body message}) @@ -69,6 +119,14 @@ (with-connection *db* (do-commands query))) +(defn do-prepared! [& args] + (with-connection *db* + (apply do-prepared args))) + +(defn do-update [& args] + (with-connection *db* + (apply update-values args))) + (defn do-select [query] (with-connection *db* (with-query-results rs query |
