Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 58 lines (52 sloc) 2.251 kb
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
(ns fleetdb.client
  (:require [clj-json.core :as json])
  (:import (java.net Socket URI))
  (:import (java.io OutputStreamWriter BufferedWriter
                    InputStreamReader BufferedReader
                    Closeable))
  (:import (clojure.lang IFn ILookup)))

(defn- doquery [#^BufferedWriter writer #^BufferedReader reader q]
  (let [#^String req (json/generate-string q)]
    (if-let [resp (do (.write writer req)
                      (.write writer "\r\n")
                      (.flush writer)
                      (.readLine reader))]
      (let [[status result] (json/parse-string resp)]
        (if (zero? status)
          result
          (throw (Exception. #^String result))))
      (throw (Exception. "No response from server.")))))

(defn query [client q]
  (doquery (:writer client) (:reader client) q))

(defn close [client]
  (.close #^BufferedReader (:reader client))
  (.close #^BufferedWriter (:writer client))
  (.close #^Socket (:socket client)))

(defn- apply-url [url options]
  (let [url-parsed (URI. url)]
    (-> options
      (dissoc :url)
      (assoc :host (.getHost url-parsed))
      (assoc :port (.getPort url-parsed))
      (assoc :password (if-let [ui (.getUserInfo url-parsed)]
                         (second (re-find #":(.+)" ui)))))))

(defn connect [& [options]]
  (if-let [url (:url options)]
    (connect (apply-url url options))
    (let [host (get options :host "127.0.0.1")
          port (get options :port 3400)
          timeout (get options :timeout)
          password (get options :password)
          socket (Socket. #^String host #^Integer port)
          writer (BufferedWriter. (OutputStreamWriter. (.getOutputStream socket)))
          reader (BufferedReader. (InputStreamReader. (.getInputStream socket)))
          attrs {:writer writer :reader reader :socket socket
                    :host host :port port :password password :timeout timeout}]
      (when timeout
        (.setSoTimeout socket (int (* timeout 1000))))
      (when password
        (doquery writer reader ["auth" password]))
      (proxy [IFn ILookup Closeable] []
        (invoke [q] (doquery writer reader q))
        (valAt [k] (attrs k))
        (close [] (close attrs))))))
Something went wrong with that request. Please try again.