summaryrefslogtreecommitdiff
path: root/src/utils.clj
blob: 3f2f4e403ef6a8563561ac7eb61091f1a8364923 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(ns utils
  (:import java.text.SimpleDateFormat
           java.util.Date
           java.net.URLDecoder)
  (:use clojure.contrib.json.write
        clojure.contrib.sql))

(let [db-host "localhost"
      db-port 5432
      db-name "dumpfm"]
  (def *db* {:classname "org.postgresql.Driver"
             :subprotocol "postgresql"
             :subname (str "//" db-host ":" db-port "/" db-name)
             :user "postgres"
             :password "root"}))

;;  moved this to here which doesn't seem right... maybe a 'settings.clj' or something?
(def *dumps-per-page* 20)

;; Misc

(defn ms-in-future [ms]
  (+ ms (System/currentTimeMillis)))

(defn swap [f]
  (fn [& more] (apply f (reverse more))))

(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))

(defn seconds [t] (* t 1000))
(defn minutes [t] (* t 60 1000))

(defn kbytes [b] (* b 1024))
(defn mbytes [b] (* b 1024 1024))

;; JSON responses

(def yyyy-mm-dd-formatter (new SimpleDateFormat "yyyy-MM-dd"))

(defmethod print-json Date
  [d]
  (print-json (.format yyyy-mm-dd-formatter d)))

(defn resp-error [message]
  {:status 400 :headers {} :body message})

(defn resp-success [message]
  {:status 200 :headers {} :body (json-str message)})

;; Database

(defn do-select [query]
  (with-connection *db*
    (with-query-results rs query
      (doall rs))))

(defn do-count [query]
  ((first (with-connection *db*
	    (with-query-results rs query
	      (doall rs))))
   :count))

(defn do-delete [table query]
  (with-connection *db*
    (delete-rows table query)))

(defn do-insert [table cols values]
  (with-connection *db*
    (insert-values table cols values)))

;; Parsing

(defn maybe-parse-int 
  ([s] (Integer/parseInt s))
  ([s default]
     (try (Integer/parseInt s)
          (catch NumberFormatException _ default))))

(defn maybe-parse-long [s f]
  (if s (Long/parseLong s) f))

(defn url-decode [text]
  (URLDecoder/decode text "UTF-8"))

(defn #^String lower-case
  "Converts string to all lower-case."
  [#^String s]
  (.toLowerCase s))