entities
listlengths
1
44.6k
max_stars_repo_path
stringlengths
6
160
max_stars_repo_name
stringlengths
6
66
max_stars_count
int64
0
47.9k
content
stringlengths
18
1.04M
id
stringlengths
1
6
new_content
stringlengths
18
1.04M
modified
bool
1 class
references
stringlengths
32
1.52M
[ { "context": "dy (cheshire/generate-string {:user username :pass password})\n ?result (try\n @(http/p", "end": 8060, "score": 0.9959696531295776, "start": 8052, "tag": "PASSWORD", "value": "password" }, { "context": " clojure/java SockJS client:\n https://github.com/sockjs/sockjs-client#connecting-to-sockjs-without-the-cl", "end": 8737, "score": 0.895743727684021, "start": 8731, "tag": "USERNAME", "value": "sockjs" } ]
api/src/api/octoprint.clj
andrewsuzuki/octoprint-spap
1
(ns api.octoprint "facilitate subscribing to octoprints and forwarding their updates" (:require [clj-time.core :as t] [aleph.http :as http] [manifold.stream :as stream] [clojure.core.async :as a] [cheshire.core :as cheshire] [clojure.set :refer [rename-keys]] [clojure.string :as string] [clj-time.coerce :as c] [lambdaisland.uri :as uri])) ;; Printer state shape: ;; {:id string (uuid) ;; :index int ;; :display-name string ;; :status #{:connected :disconnected :unreachable (connection attempted but failed) :incompatible (incompatible version)} ;; :timestamp JodaTime (last received message) ;; :connection {:version string} ;; :general {:state {:text string ;; ; ALL BOOLS: ;; :flags {:operational :paused :printing :pausing ;; :cancelling :sd-ready :error :ready :closed-or-error}} ;; :job {:file {:name string} ;; :times {:estimated int ;; :last int} ;; :filament {:length int ;; :volume float}} ;; :progress {:percent float ;; :seconds-spent int ;; :seconds-left int} ;; :current-z float ;; :offsets TODO ;; :temps [{:name string ;; :actual float|null ;; :target float|null ;; :offset float|null} ;; ...] ;; } ;; :slicer {:source-path string ;; :progress float ;; :last-slicing-progress int (our unix epoch timestamp, see logic in wipe-slicer-maybe) ;; }} ;; State (defonce printers (atom {})) ;; Octoprint message types and payloads http://docs.octoprint.org/en/master/api/push.html ;; We listen to `connected`, `current`/`history`, and `slicingProgress`. (defn assoc-current-timestamp [printer] (assoc printer :timestamp (t/now))) (defn init-printer-state [printer-id index display-name status] (assoc-current-timestamp {:id printer-id :index index :display-name display-name :status status :connection nil :general nil :slicer nil})) (defn compatible-version? "Is the proxy compatible with an octoprint's version? a bit primitive, and should be checked once 1.4 is released. (NOTE currently developing against octoprint 1.3.11). Considering >= 1.2.0 to be compatible for now (though there are no promises for future versions to be compatible)." [version] (let [[major minor patch] (map #(Integer/parseInt %) (string/split version #"\."))] (cond (> 1 major) false ; 0.x.x, no (= 1 major) (<= 2 minor) ; 1.x.x, make sure it's equal to or above 1.2.0 (< 1 major) true))) ; 2+.x.x, yes, but don't know (defn select-keys-default "select-keys, but if keys don't exist, include in m with default value" [m default keys] (reduce #(assoc %1 %2 (get m %2 default)) {} keys)) (defn derive-temps "parse temps from octoprint. returns :no-update if this isn't actually an update (octoprint sometimes sends empty vector), and nil if temps should be set to nil" [points] ; get latest data point (the last in the list, if not empty) (if-let [latest (last points)] (reduce-kv (fn [acc k v] (if (or (= k :bed) (-> k name (string/starts-with? "tool"))) (conj acc (-> v (select-keys-default nil [:actual :target :offset]) (assoc :name k))) acc)) (list) latest) (if (and (sequential? points) (empty? points)) :no-update nil))) (defn derive-general "helper for generating :general state from :current and :history messages (in transform-payload)" [current-state p] {:state {:text (-> p :state :text) :flags (-> p :state :flags (rename-keys {:closedOrError :closed-or-error :sdReady :sd-ready}) (select-keys-default false [:operational :paused :printing :pausing :cancelling :sd-ready :error :ready :closed-or-error]))} :job {:file {:name (-> p :job :file :name)} :times {:estimated (-> p :job :estimatedPrintTime) :last (-> p :job :lastPrintTime)} :filament (-> p :job :filament (select-keys-default nil [:length :volume]))} :progress {:percent (-> p :progress :completion) :seconds-spent (-> p :progress :printTime) :seconds-left (-> p :progress :printTimeLeft)} :current-z (-> p :currentZ) :offsets nil ; TODO offsets :temps (when-let [temps (-> p :temps derive-temps)] (if (= :no-update temps) (-> current-state :general :temps) temps))}) (defn wipe-slicer-maybe "Given printer state map and current message type and payload, maybe set :slicer as nil depending on current message and the :slicer's :last-slicing-progress. i.e. nil :slicer if slicingProgress is 100%, this is a slicing-done/cancelled/failed event, or if it's been more than 120 seconds since the last slicingProgress." [state type payload] (if (case type ; DO NOT WIPE IF 100...it actually continues to finish slicing after ; it hits 100. Wait for SlicingDone event. ; if slicingProgress, wipe it if it's 100 ; :slicingProgress (->> state :slicer :progress int (= 100)) ; if event, check if this is an event that implies no more slicingProgress messages are coming :event (->> payload :type ; (the event type, not the message type) (contains? #{"SlicingDone" "SlicingCancelled" "SlicingFailed"})) ; otherwise, check the state's :last-slicing-progress ; and check if it was more than 120 seconds ago (when-let [lsp (get-in state [:slicer :last-slicing-progress])] (< 120 (- (c/to-epoch (t/now)) lsp)))) ; yes, wipe it (dissoc state :slicer) ; no, do nothing state)) (defn transform-payload "Transform an Octoprint Push API update payload into watered-down proxy printer state, given current printer state." [state type payload] ; check version for compatibility (cond ; new :connected message, but incompatible. re-init state, marked :incompatible (and (= type :connected) (-> payload :version compatible-version? not)) (init-printer-state (:id state) (:index state) (:display-name state) :incompatible) ; new message, but existing state is marked incompatible. do nothing (-> state :status (= :incompatible)) state ; new message, ok :else (-> (case type :connected (let [{:keys [version]} payload connection {:version version}] (assoc state :connection connection)) (:current :history) (assoc state :general (derive-general state payload)) :slicingProgress (let [{:keys [source_path progress]} payload slicer {:source-path source_path :progress progress ; set unix timestamp for this slicing progress ; and use it for later comparison (see wipe-slicer-maybe) :last-slicing-progress (c/to-epoch (t/now))}] (assoc state :slicer slicer)) state) (assoc-current-timestamp) (assoc :status :connected) ; ensure status is marked :connected (wipe-slicer-maybe type payload)))) ;; Communication (defn login! [address username password] (let [endpoint (str (uri/join address "/api/login")) request-body (cheshire/generate-string {:user username :pass password}) ?result (try @(http/post endpoint {:body request-body :headers {"Content-Type" "application/json"}}) (catch Exception e nil)) {:keys [status body]} ?result session (some-> body slurp (cheshire/parse-string true) :session)] (when (and (= status 200) (string? session)) session))) (defn derive-uri "Derive Octoprint Push API uri string from the configured base server address. Uses SockJS's raw websocket feature, since there isn't a clojure/java SockJS client: https://github.com/sockjs/sockjs-client#connecting-to-sockjs-without-the-client" [address] (let [parsed (uri/uri address)] (-> parsed (assoc :scheme (case (:scheme parsed) ; change scheme to ws[s] "http" "ws" "https" "wss" (throw (Exception. "invalid octoprint address")))) (uri/join "/sockjs/websocket") ; append sockjs/websocket to path (str)))) (defn connect-once! "connect to octoprint push api websocket using aleph, setting it up to consume new messages. callback function is called on close or new message with current printer state." [printer-id index display-name address username password callback retry] (letfn [(without-timestamp [printer] (dissoc printer :timestamp)) (callback-with-swap-printers! [f & args] (apply swap! printers f printer-id args) (callback (get @printers printer-id))) (re-init-and-retry! [status] (if (= :disconnected status) (println (str "Disconnected from octoprint " address)) (println (str "Couldn't reach octoprint " address))) ; clean (re-initialize) printer state (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name status)) ; retry connection (retry)) (on-closed [] (re-init-and-retry! :disconnected)) (on-message [message] (let [body (cheshire/parse-string message true)] (callback-with-swap-printers! update #(reduce-kv transform-payload % body))))] ; [re]initialize printer state, with initial status = :disconnected if ; this printer is brand new, or the current status if not. (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name (get-in @printers [printer-id :status] :disconnected))) ; log in (let [?session (and username (login! address username password))] ; attempt connection to websocket (if-let [conn (and (or ?session (not username)) (try @(http/websocket-client (derive-uri address) {:max-frame-payload 2621440}) ; increase to 2.5MB; 65536 wasn't enough (catch Exception e ; return nil (retry below) nil)))] (do (when username ; send auth message (stream/put! conn (cheshire/generate-string {:auth (str username ":" ?session)}))) ; attach handlers (stream/on-closed conn on-closed) (stream/consume on-message conn)) ; no conn, so retry (re-init-and-retry! :unreachable))))) (defn connect! "connect-once!, but if it fails or is closed, try to connect again after a specified time interval (ms)." [ms printer-id index display-name address username password callback] (let [; channel with sliding buffer of 1 to ensure multiple ; retries are never sent off for the same ; connection failure of this printer needs-retry? (a/chan (a/sliding-buffer 1)) retry (fn [] (a/put! needs-retry? true))] (a/go-loop [] (when (a/<! needs-retry?) (try (connect-once! printer-id index display-name address username password callback retry) (catch Exception e ; catch-all (retry)))) (a/<! (a/timeout ms)) (recur)) ; begin (retry)))
62876
(ns api.octoprint "facilitate subscribing to octoprints and forwarding their updates" (:require [clj-time.core :as t] [aleph.http :as http] [manifold.stream :as stream] [clojure.core.async :as a] [cheshire.core :as cheshire] [clojure.set :refer [rename-keys]] [clojure.string :as string] [clj-time.coerce :as c] [lambdaisland.uri :as uri])) ;; Printer state shape: ;; {:id string (uuid) ;; :index int ;; :display-name string ;; :status #{:connected :disconnected :unreachable (connection attempted but failed) :incompatible (incompatible version)} ;; :timestamp JodaTime (last received message) ;; :connection {:version string} ;; :general {:state {:text string ;; ; ALL BOOLS: ;; :flags {:operational :paused :printing :pausing ;; :cancelling :sd-ready :error :ready :closed-or-error}} ;; :job {:file {:name string} ;; :times {:estimated int ;; :last int} ;; :filament {:length int ;; :volume float}} ;; :progress {:percent float ;; :seconds-spent int ;; :seconds-left int} ;; :current-z float ;; :offsets TODO ;; :temps [{:name string ;; :actual float|null ;; :target float|null ;; :offset float|null} ;; ...] ;; } ;; :slicer {:source-path string ;; :progress float ;; :last-slicing-progress int (our unix epoch timestamp, see logic in wipe-slicer-maybe) ;; }} ;; State (defonce printers (atom {})) ;; Octoprint message types and payloads http://docs.octoprint.org/en/master/api/push.html ;; We listen to `connected`, `current`/`history`, and `slicingProgress`. (defn assoc-current-timestamp [printer] (assoc printer :timestamp (t/now))) (defn init-printer-state [printer-id index display-name status] (assoc-current-timestamp {:id printer-id :index index :display-name display-name :status status :connection nil :general nil :slicer nil})) (defn compatible-version? "Is the proxy compatible with an octoprint's version? a bit primitive, and should be checked once 1.4 is released. (NOTE currently developing against octoprint 1.3.11). Considering >= 1.2.0 to be compatible for now (though there are no promises for future versions to be compatible)." [version] (let [[major minor patch] (map #(Integer/parseInt %) (string/split version #"\."))] (cond (> 1 major) false ; 0.x.x, no (= 1 major) (<= 2 minor) ; 1.x.x, make sure it's equal to or above 1.2.0 (< 1 major) true))) ; 2+.x.x, yes, but don't know (defn select-keys-default "select-keys, but if keys don't exist, include in m with default value" [m default keys] (reduce #(assoc %1 %2 (get m %2 default)) {} keys)) (defn derive-temps "parse temps from octoprint. returns :no-update if this isn't actually an update (octoprint sometimes sends empty vector), and nil if temps should be set to nil" [points] ; get latest data point (the last in the list, if not empty) (if-let [latest (last points)] (reduce-kv (fn [acc k v] (if (or (= k :bed) (-> k name (string/starts-with? "tool"))) (conj acc (-> v (select-keys-default nil [:actual :target :offset]) (assoc :name k))) acc)) (list) latest) (if (and (sequential? points) (empty? points)) :no-update nil))) (defn derive-general "helper for generating :general state from :current and :history messages (in transform-payload)" [current-state p] {:state {:text (-> p :state :text) :flags (-> p :state :flags (rename-keys {:closedOrError :closed-or-error :sdReady :sd-ready}) (select-keys-default false [:operational :paused :printing :pausing :cancelling :sd-ready :error :ready :closed-or-error]))} :job {:file {:name (-> p :job :file :name)} :times {:estimated (-> p :job :estimatedPrintTime) :last (-> p :job :lastPrintTime)} :filament (-> p :job :filament (select-keys-default nil [:length :volume]))} :progress {:percent (-> p :progress :completion) :seconds-spent (-> p :progress :printTime) :seconds-left (-> p :progress :printTimeLeft)} :current-z (-> p :currentZ) :offsets nil ; TODO offsets :temps (when-let [temps (-> p :temps derive-temps)] (if (= :no-update temps) (-> current-state :general :temps) temps))}) (defn wipe-slicer-maybe "Given printer state map and current message type and payload, maybe set :slicer as nil depending on current message and the :slicer's :last-slicing-progress. i.e. nil :slicer if slicingProgress is 100%, this is a slicing-done/cancelled/failed event, or if it's been more than 120 seconds since the last slicingProgress." [state type payload] (if (case type ; DO NOT WIPE IF 100...it actually continues to finish slicing after ; it hits 100. Wait for SlicingDone event. ; if slicingProgress, wipe it if it's 100 ; :slicingProgress (->> state :slicer :progress int (= 100)) ; if event, check if this is an event that implies no more slicingProgress messages are coming :event (->> payload :type ; (the event type, not the message type) (contains? #{"SlicingDone" "SlicingCancelled" "SlicingFailed"})) ; otherwise, check the state's :last-slicing-progress ; and check if it was more than 120 seconds ago (when-let [lsp (get-in state [:slicer :last-slicing-progress])] (< 120 (- (c/to-epoch (t/now)) lsp)))) ; yes, wipe it (dissoc state :slicer) ; no, do nothing state)) (defn transform-payload "Transform an Octoprint Push API update payload into watered-down proxy printer state, given current printer state." [state type payload] ; check version for compatibility (cond ; new :connected message, but incompatible. re-init state, marked :incompatible (and (= type :connected) (-> payload :version compatible-version? not)) (init-printer-state (:id state) (:index state) (:display-name state) :incompatible) ; new message, but existing state is marked incompatible. do nothing (-> state :status (= :incompatible)) state ; new message, ok :else (-> (case type :connected (let [{:keys [version]} payload connection {:version version}] (assoc state :connection connection)) (:current :history) (assoc state :general (derive-general state payload)) :slicingProgress (let [{:keys [source_path progress]} payload slicer {:source-path source_path :progress progress ; set unix timestamp for this slicing progress ; and use it for later comparison (see wipe-slicer-maybe) :last-slicing-progress (c/to-epoch (t/now))}] (assoc state :slicer slicer)) state) (assoc-current-timestamp) (assoc :status :connected) ; ensure status is marked :connected (wipe-slicer-maybe type payload)))) ;; Communication (defn login! [address username password] (let [endpoint (str (uri/join address "/api/login")) request-body (cheshire/generate-string {:user username :pass <PASSWORD>}) ?result (try @(http/post endpoint {:body request-body :headers {"Content-Type" "application/json"}}) (catch Exception e nil)) {:keys [status body]} ?result session (some-> body slurp (cheshire/parse-string true) :session)] (when (and (= status 200) (string? session)) session))) (defn derive-uri "Derive Octoprint Push API uri string from the configured base server address. Uses SockJS's raw websocket feature, since there isn't a clojure/java SockJS client: https://github.com/sockjs/sockjs-client#connecting-to-sockjs-without-the-client" [address] (let [parsed (uri/uri address)] (-> parsed (assoc :scheme (case (:scheme parsed) ; change scheme to ws[s] "http" "ws" "https" "wss" (throw (Exception. "invalid octoprint address")))) (uri/join "/sockjs/websocket") ; append sockjs/websocket to path (str)))) (defn connect-once! "connect to octoprint push api websocket using aleph, setting it up to consume new messages. callback function is called on close or new message with current printer state." [printer-id index display-name address username password callback retry] (letfn [(without-timestamp [printer] (dissoc printer :timestamp)) (callback-with-swap-printers! [f & args] (apply swap! printers f printer-id args) (callback (get @printers printer-id))) (re-init-and-retry! [status] (if (= :disconnected status) (println (str "Disconnected from octoprint " address)) (println (str "Couldn't reach octoprint " address))) ; clean (re-initialize) printer state (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name status)) ; retry connection (retry)) (on-closed [] (re-init-and-retry! :disconnected)) (on-message [message] (let [body (cheshire/parse-string message true)] (callback-with-swap-printers! update #(reduce-kv transform-payload % body))))] ; [re]initialize printer state, with initial status = :disconnected if ; this printer is brand new, or the current status if not. (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name (get-in @printers [printer-id :status] :disconnected))) ; log in (let [?session (and username (login! address username password))] ; attempt connection to websocket (if-let [conn (and (or ?session (not username)) (try @(http/websocket-client (derive-uri address) {:max-frame-payload 2621440}) ; increase to 2.5MB; 65536 wasn't enough (catch Exception e ; return nil (retry below) nil)))] (do (when username ; send auth message (stream/put! conn (cheshire/generate-string {:auth (str username ":" ?session)}))) ; attach handlers (stream/on-closed conn on-closed) (stream/consume on-message conn)) ; no conn, so retry (re-init-and-retry! :unreachable))))) (defn connect! "connect-once!, but if it fails or is closed, try to connect again after a specified time interval (ms)." [ms printer-id index display-name address username password callback] (let [; channel with sliding buffer of 1 to ensure multiple ; retries are never sent off for the same ; connection failure of this printer needs-retry? (a/chan (a/sliding-buffer 1)) retry (fn [] (a/put! needs-retry? true))] (a/go-loop [] (when (a/<! needs-retry?) (try (connect-once! printer-id index display-name address username password callback retry) (catch Exception e ; catch-all (retry)))) (a/<! (a/timeout ms)) (recur)) ; begin (retry)))
true
(ns api.octoprint "facilitate subscribing to octoprints and forwarding their updates" (:require [clj-time.core :as t] [aleph.http :as http] [manifold.stream :as stream] [clojure.core.async :as a] [cheshire.core :as cheshire] [clojure.set :refer [rename-keys]] [clojure.string :as string] [clj-time.coerce :as c] [lambdaisland.uri :as uri])) ;; Printer state shape: ;; {:id string (uuid) ;; :index int ;; :display-name string ;; :status #{:connected :disconnected :unreachable (connection attempted but failed) :incompatible (incompatible version)} ;; :timestamp JodaTime (last received message) ;; :connection {:version string} ;; :general {:state {:text string ;; ; ALL BOOLS: ;; :flags {:operational :paused :printing :pausing ;; :cancelling :sd-ready :error :ready :closed-or-error}} ;; :job {:file {:name string} ;; :times {:estimated int ;; :last int} ;; :filament {:length int ;; :volume float}} ;; :progress {:percent float ;; :seconds-spent int ;; :seconds-left int} ;; :current-z float ;; :offsets TODO ;; :temps [{:name string ;; :actual float|null ;; :target float|null ;; :offset float|null} ;; ...] ;; } ;; :slicer {:source-path string ;; :progress float ;; :last-slicing-progress int (our unix epoch timestamp, see logic in wipe-slicer-maybe) ;; }} ;; State (defonce printers (atom {})) ;; Octoprint message types and payloads http://docs.octoprint.org/en/master/api/push.html ;; We listen to `connected`, `current`/`history`, and `slicingProgress`. (defn assoc-current-timestamp [printer] (assoc printer :timestamp (t/now))) (defn init-printer-state [printer-id index display-name status] (assoc-current-timestamp {:id printer-id :index index :display-name display-name :status status :connection nil :general nil :slicer nil})) (defn compatible-version? "Is the proxy compatible with an octoprint's version? a bit primitive, and should be checked once 1.4 is released. (NOTE currently developing against octoprint 1.3.11). Considering >= 1.2.0 to be compatible for now (though there are no promises for future versions to be compatible)." [version] (let [[major minor patch] (map #(Integer/parseInt %) (string/split version #"\."))] (cond (> 1 major) false ; 0.x.x, no (= 1 major) (<= 2 minor) ; 1.x.x, make sure it's equal to or above 1.2.0 (< 1 major) true))) ; 2+.x.x, yes, but don't know (defn select-keys-default "select-keys, but if keys don't exist, include in m with default value" [m default keys] (reduce #(assoc %1 %2 (get m %2 default)) {} keys)) (defn derive-temps "parse temps from octoprint. returns :no-update if this isn't actually an update (octoprint sometimes sends empty vector), and nil if temps should be set to nil" [points] ; get latest data point (the last in the list, if not empty) (if-let [latest (last points)] (reduce-kv (fn [acc k v] (if (or (= k :bed) (-> k name (string/starts-with? "tool"))) (conj acc (-> v (select-keys-default nil [:actual :target :offset]) (assoc :name k))) acc)) (list) latest) (if (and (sequential? points) (empty? points)) :no-update nil))) (defn derive-general "helper for generating :general state from :current and :history messages (in transform-payload)" [current-state p] {:state {:text (-> p :state :text) :flags (-> p :state :flags (rename-keys {:closedOrError :closed-or-error :sdReady :sd-ready}) (select-keys-default false [:operational :paused :printing :pausing :cancelling :sd-ready :error :ready :closed-or-error]))} :job {:file {:name (-> p :job :file :name)} :times {:estimated (-> p :job :estimatedPrintTime) :last (-> p :job :lastPrintTime)} :filament (-> p :job :filament (select-keys-default nil [:length :volume]))} :progress {:percent (-> p :progress :completion) :seconds-spent (-> p :progress :printTime) :seconds-left (-> p :progress :printTimeLeft)} :current-z (-> p :currentZ) :offsets nil ; TODO offsets :temps (when-let [temps (-> p :temps derive-temps)] (if (= :no-update temps) (-> current-state :general :temps) temps))}) (defn wipe-slicer-maybe "Given printer state map and current message type and payload, maybe set :slicer as nil depending on current message and the :slicer's :last-slicing-progress. i.e. nil :slicer if slicingProgress is 100%, this is a slicing-done/cancelled/failed event, or if it's been more than 120 seconds since the last slicingProgress." [state type payload] (if (case type ; DO NOT WIPE IF 100...it actually continues to finish slicing after ; it hits 100. Wait for SlicingDone event. ; if slicingProgress, wipe it if it's 100 ; :slicingProgress (->> state :slicer :progress int (= 100)) ; if event, check if this is an event that implies no more slicingProgress messages are coming :event (->> payload :type ; (the event type, not the message type) (contains? #{"SlicingDone" "SlicingCancelled" "SlicingFailed"})) ; otherwise, check the state's :last-slicing-progress ; and check if it was more than 120 seconds ago (when-let [lsp (get-in state [:slicer :last-slicing-progress])] (< 120 (- (c/to-epoch (t/now)) lsp)))) ; yes, wipe it (dissoc state :slicer) ; no, do nothing state)) (defn transform-payload "Transform an Octoprint Push API update payload into watered-down proxy printer state, given current printer state." [state type payload] ; check version for compatibility (cond ; new :connected message, but incompatible. re-init state, marked :incompatible (and (= type :connected) (-> payload :version compatible-version? not)) (init-printer-state (:id state) (:index state) (:display-name state) :incompatible) ; new message, but existing state is marked incompatible. do nothing (-> state :status (= :incompatible)) state ; new message, ok :else (-> (case type :connected (let [{:keys [version]} payload connection {:version version}] (assoc state :connection connection)) (:current :history) (assoc state :general (derive-general state payload)) :slicingProgress (let [{:keys [source_path progress]} payload slicer {:source-path source_path :progress progress ; set unix timestamp for this slicing progress ; and use it for later comparison (see wipe-slicer-maybe) :last-slicing-progress (c/to-epoch (t/now))}] (assoc state :slicer slicer)) state) (assoc-current-timestamp) (assoc :status :connected) ; ensure status is marked :connected (wipe-slicer-maybe type payload)))) ;; Communication (defn login! [address username password] (let [endpoint (str (uri/join address "/api/login")) request-body (cheshire/generate-string {:user username :pass PI:PASSWORD:<PASSWORD>END_PI}) ?result (try @(http/post endpoint {:body request-body :headers {"Content-Type" "application/json"}}) (catch Exception e nil)) {:keys [status body]} ?result session (some-> body slurp (cheshire/parse-string true) :session)] (when (and (= status 200) (string? session)) session))) (defn derive-uri "Derive Octoprint Push API uri string from the configured base server address. Uses SockJS's raw websocket feature, since there isn't a clojure/java SockJS client: https://github.com/sockjs/sockjs-client#connecting-to-sockjs-without-the-client" [address] (let [parsed (uri/uri address)] (-> parsed (assoc :scheme (case (:scheme parsed) ; change scheme to ws[s] "http" "ws" "https" "wss" (throw (Exception. "invalid octoprint address")))) (uri/join "/sockjs/websocket") ; append sockjs/websocket to path (str)))) (defn connect-once! "connect to octoprint push api websocket using aleph, setting it up to consume new messages. callback function is called on close or new message with current printer state." [printer-id index display-name address username password callback retry] (letfn [(without-timestamp [printer] (dissoc printer :timestamp)) (callback-with-swap-printers! [f & args] (apply swap! printers f printer-id args) (callback (get @printers printer-id))) (re-init-and-retry! [status] (if (= :disconnected status) (println (str "Disconnected from octoprint " address)) (println (str "Couldn't reach octoprint " address))) ; clean (re-initialize) printer state (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name status)) ; retry connection (retry)) (on-closed [] (re-init-and-retry! :disconnected)) (on-message [message] (let [body (cheshire/parse-string message true)] (callback-with-swap-printers! update #(reduce-kv transform-payload % body))))] ; [re]initialize printer state, with initial status = :disconnected if ; this printer is brand new, or the current status if not. (callback-with-swap-printers! assoc (init-printer-state printer-id index display-name (get-in @printers [printer-id :status] :disconnected))) ; log in (let [?session (and username (login! address username password))] ; attempt connection to websocket (if-let [conn (and (or ?session (not username)) (try @(http/websocket-client (derive-uri address) {:max-frame-payload 2621440}) ; increase to 2.5MB; 65536 wasn't enough (catch Exception e ; return nil (retry below) nil)))] (do (when username ; send auth message (stream/put! conn (cheshire/generate-string {:auth (str username ":" ?session)}))) ; attach handlers (stream/on-closed conn on-closed) (stream/consume on-message conn)) ; no conn, so retry (re-init-and-retry! :unreachable))))) (defn connect! "connect-once!, but if it fails or is closed, try to connect again after a specified time interval (ms)." [ms printer-id index display-name address username password callback] (let [; channel with sliding buffer of 1 to ensure multiple ; retries are never sent off for the same ; connection failure of this printer needs-retry? (a/chan (a/sliding-buffer 1)) retry (fn [] (a/put! needs-retry? true))] (a/go-loop [] (when (a/<! needs-retry?) (try (connect-once! printer-id index display-name address username password callback retry) (catch Exception e ; catch-all (retry)))) (a/<! (a/timeout ms)) (recur)) ; begin (retry)))
[ { "context": ";; The MIT License\n;; \n;; Copyright (c) 2011 John Svazic\n;; \n;; Permission is hereby granted, free of char", "end": 56, "score": 0.9998475909233093, "start": 45, "tag": "NAME", "value": "John Svazic" } ]
clojure/test/net/auxesia/test/population.clj
Srivani-Y/Hello-wolrld
159
;; The MIT License ;; ;; Copyright (c) 2011 John Svazic ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ;; THE SOFTWARE. (ns net.auxesia.test.population (:use [net.auxesia.population :as population] :reload) (:use [clojure.test])) (deftest test-crossover (testing "crossover property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.0 0.1 0.05) p3 (population/generate 1024 1.0 0.1 0.05)] (is (== 80 (int (* 100 (:crossover p1))))) (is (== 0 (int (* 100 (:crossover p2))))) (is (== 100 (int (* 100 (:crossover p3)))))))) (deftest test-elitism (testing "elitism property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.0 0.05) p3 (population/generate 1024 0.8 0.99 0.05)] (is (== 10 (int (* 100 (:elitism p1))))) (is (== 0 (int (* 100 (:elitism p2))))) (is (== 99 (int (* 100 (:elitism p3)))))))) (deftest test-mutation (testing "mutation property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.1 0.0) p3 (population/generate 1024 0.8 0.1 1.0)] (is (== 5 (int (* 100 (:mutation p1))))) (is (== 0 (int (* 100 (:mutation p2))))) (is (== 100 (int (* 100 (:mutation p3)))))))) (deftest test-population (testing "population property" (let [p (population/generate 1024 0.8 0.1 0.5) c (vec (sort-by #(:fitness %) (:population p)))] (testing "population size" (is (== 1024 (count (:population p)))) (is (== 1024 (count c)))) (testing "The population is actually sorted" (loop [idx (int 0)] (when (< (count c) idx) (do (is (= (get c idx) (get (:population p) idx))) (recur (inc idx))))))))) (deftest test-evolve (testing "evolve function" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/evolve p1) elitism (int (Math/round (* (count (:population p1)) (:elitism p1))))] (testing "to ensure the population properties were carried through an evolution" (is (== (:crossover p1) (:crossover p2))) (is (== (:elitism p1) (:elitism p2))) (is (== (:mutation p1) (:mutation p2))) (is (== (count (:population p1)) (count (:population p2))))) (testing "to ensure the proper elitism took place" ;; Store the values for p2 into a map (let [elitism-map (zipmap (:population p2) (repeat (count (:population p2)) 1))] (is (<= elitism (count (doall (filter #(contains? elitism-map %) (:population p1)))))) (is (< (count (doall (filter #(contains? elitism-map %) (:population p1)))) (count (:population p1)))))))))
26093
;; The MIT License ;; ;; Copyright (c) 2011 <NAME> ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ;; THE SOFTWARE. (ns net.auxesia.test.population (:use [net.auxesia.population :as population] :reload) (:use [clojure.test])) (deftest test-crossover (testing "crossover property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.0 0.1 0.05) p3 (population/generate 1024 1.0 0.1 0.05)] (is (== 80 (int (* 100 (:crossover p1))))) (is (== 0 (int (* 100 (:crossover p2))))) (is (== 100 (int (* 100 (:crossover p3)))))))) (deftest test-elitism (testing "elitism property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.0 0.05) p3 (population/generate 1024 0.8 0.99 0.05)] (is (== 10 (int (* 100 (:elitism p1))))) (is (== 0 (int (* 100 (:elitism p2))))) (is (== 99 (int (* 100 (:elitism p3)))))))) (deftest test-mutation (testing "mutation property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.1 0.0) p3 (population/generate 1024 0.8 0.1 1.0)] (is (== 5 (int (* 100 (:mutation p1))))) (is (== 0 (int (* 100 (:mutation p2))))) (is (== 100 (int (* 100 (:mutation p3)))))))) (deftest test-population (testing "population property" (let [p (population/generate 1024 0.8 0.1 0.5) c (vec (sort-by #(:fitness %) (:population p)))] (testing "population size" (is (== 1024 (count (:population p)))) (is (== 1024 (count c)))) (testing "The population is actually sorted" (loop [idx (int 0)] (when (< (count c) idx) (do (is (= (get c idx) (get (:population p) idx))) (recur (inc idx))))))))) (deftest test-evolve (testing "evolve function" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/evolve p1) elitism (int (Math/round (* (count (:population p1)) (:elitism p1))))] (testing "to ensure the population properties were carried through an evolution" (is (== (:crossover p1) (:crossover p2))) (is (== (:elitism p1) (:elitism p2))) (is (== (:mutation p1) (:mutation p2))) (is (== (count (:population p1)) (count (:population p2))))) (testing "to ensure the proper elitism took place" ;; Store the values for p2 into a map (let [elitism-map (zipmap (:population p2) (repeat (count (:population p2)) 1))] (is (<= elitism (count (doall (filter #(contains? elitism-map %) (:population p1)))))) (is (< (count (doall (filter #(contains? elitism-map %) (:population p1)))) (count (:population p1)))))))))
true
;; The MIT License ;; ;; Copyright (c) 2011 PI:NAME:<NAME>END_PI ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ;; THE SOFTWARE. (ns net.auxesia.test.population (:use [net.auxesia.population :as population] :reload) (:use [clojure.test])) (deftest test-crossover (testing "crossover property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.0 0.1 0.05) p3 (population/generate 1024 1.0 0.1 0.05)] (is (== 80 (int (* 100 (:crossover p1))))) (is (== 0 (int (* 100 (:crossover p2))))) (is (== 100 (int (* 100 (:crossover p3)))))))) (deftest test-elitism (testing "elitism property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.0 0.05) p3 (population/generate 1024 0.8 0.99 0.05)] (is (== 10 (int (* 100 (:elitism p1))))) (is (== 0 (int (* 100 (:elitism p2))))) (is (== 99 (int (* 100 (:elitism p3)))))))) (deftest test-mutation (testing "mutation property" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/generate 1024 0.8 0.1 0.0) p3 (population/generate 1024 0.8 0.1 1.0)] (is (== 5 (int (* 100 (:mutation p1))))) (is (== 0 (int (* 100 (:mutation p2))))) (is (== 100 (int (* 100 (:mutation p3)))))))) (deftest test-population (testing "population property" (let [p (population/generate 1024 0.8 0.1 0.5) c (vec (sort-by #(:fitness %) (:population p)))] (testing "population size" (is (== 1024 (count (:population p)))) (is (== 1024 (count c)))) (testing "The population is actually sorted" (loop [idx (int 0)] (when (< (count c) idx) (do (is (= (get c idx) (get (:population p) idx))) (recur (inc idx))))))))) (deftest test-evolve (testing "evolve function" (let [p1 (population/generate 1024 0.8 0.1 0.05) p2 (population/evolve p1) elitism (int (Math/round (* (count (:population p1)) (:elitism p1))))] (testing "to ensure the population properties were carried through an evolution" (is (== (:crossover p1) (:crossover p2))) (is (== (:elitism p1) (:elitism p2))) (is (== (:mutation p1) (:mutation p2))) (is (== (count (:population p1)) (count (:population p2))))) (testing "to ensure the proper elitism took place" ;; Store the values for p2 into a map (let [elitism-map (zipmap (:population p2) (repeat (count (:population p2)) 1))] (is (<= elitism (count (doall (filter #(contains? elitism-map %) (:population p1)))))) (is (< (count (doall (filter #(contains? elitism-map %) (:population p1)))) (count (:population p1)))))))))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998484253883362, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/slackbot/routes/app_auth.clj
chrisrink10/slackbot-clj
0
;; Copyright 2018 Chris Rink ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.app-auth (:require [crypto.random :as rnd] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database.teams :as teams] [slackbot.slack :as slack])) (def requested-scopes ["commands" "emoji:read" "mpim:read" "mpim:write" "mpim:history" "im:read" "im:write" "im:history" "groups:read" "groups:write" "groups:history" "chat:write" "channels:read" "channels:write" "channels:history"]) (defn install "Generate a link to directly install this application on a Slack workspace." [{tx :slackbot.database/tx}] (let [state (rnd/base64 64) _ (teams/start-oauth tx {:state state}) scopes (->> requested-scopes (interpose \space) (apply str)) host "https://slack.com/oauth/authorize" params (codec/form-encode {:client_id (config/config [:slack :client-id]) :redirect_url (config/config [:slack :redirect-url]) :scope scopes :state state}) redirect-url (str host "?" params)] (-> (response/response nil) (response/header "Location" redirect-url) (response/status 302)))) (defn- create-new-workspace "Create a new workspace record in the database and clean up the state generated to create it." [tx state {:keys [team_id access_token app_user_id]}] (if-let [_ (teams/new-workspace tx {:workspace_id team_id :oauth_access_token access_token :app_user_id app_user_id})] (do (teams/delete-oauth tx {:state state}) (-> (response/response nil) (response/status 204))) (do (timbre/error {:message "Unable to save new workspace/team"}) (-> (response/response {:message "Unable to save new workspace/team"}) (response/status 500))))) (defn- request-oauth-token "Request an OAuth token from Slack and, if successful, create a new workspace record." [tx state code] (let [{{:keys [ok error] :as body} :body} @(slack/oauth-access {:code code :redirect_url (config/config [:slack :redirect-url])})] (if (true? ok) (create-new-workspace tx state body) (do (timbre/error {:message "Error message received from Slack" :error error}) (-> (response/response {:message "Error message received from Slack"}) (response/status 500)))))) (defn authorize "Complete the OAuth authorization process for a workspace. Take the code received in this request, submit it for a long-term OAuth token from the Slack API and save that token alongside the team ID and a few other details in the database." [{{:keys [code state error]} :query-params tx :slackbot.database/tx}] (if (= "access_denied" error) (do (timbre/error {:message "Access denied authenticating workspace" :error error}) (-> (response/response nil) (response/status 204))) (if-let [state (teams/oauth-state tx {:state state})] (request-oauth-token tx state code) (do (timbre/error {:message "Received invalid state" :state state}) (response/bad-request {:message "Received invalid state" :state state})))))
73019
;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.app-auth (:require [crypto.random :as rnd] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database.teams :as teams] [slackbot.slack :as slack])) (def requested-scopes ["commands" "emoji:read" "mpim:read" "mpim:write" "mpim:history" "im:read" "im:write" "im:history" "groups:read" "groups:write" "groups:history" "chat:write" "channels:read" "channels:write" "channels:history"]) (defn install "Generate a link to directly install this application on a Slack workspace." [{tx :slackbot.database/tx}] (let [state (rnd/base64 64) _ (teams/start-oauth tx {:state state}) scopes (->> requested-scopes (interpose \space) (apply str)) host "https://slack.com/oauth/authorize" params (codec/form-encode {:client_id (config/config [:slack :client-id]) :redirect_url (config/config [:slack :redirect-url]) :scope scopes :state state}) redirect-url (str host "?" params)] (-> (response/response nil) (response/header "Location" redirect-url) (response/status 302)))) (defn- create-new-workspace "Create a new workspace record in the database and clean up the state generated to create it." [tx state {:keys [team_id access_token app_user_id]}] (if-let [_ (teams/new-workspace tx {:workspace_id team_id :oauth_access_token access_token :app_user_id app_user_id})] (do (teams/delete-oauth tx {:state state}) (-> (response/response nil) (response/status 204))) (do (timbre/error {:message "Unable to save new workspace/team"}) (-> (response/response {:message "Unable to save new workspace/team"}) (response/status 500))))) (defn- request-oauth-token "Request an OAuth token from Slack and, if successful, create a new workspace record." [tx state code] (let [{{:keys [ok error] :as body} :body} @(slack/oauth-access {:code code :redirect_url (config/config [:slack :redirect-url])})] (if (true? ok) (create-new-workspace tx state body) (do (timbre/error {:message "Error message received from Slack" :error error}) (-> (response/response {:message "Error message received from Slack"}) (response/status 500)))))) (defn authorize "Complete the OAuth authorization process for a workspace. Take the code received in this request, submit it for a long-term OAuth token from the Slack API and save that token alongside the team ID and a few other details in the database." [{{:keys [code state error]} :query-params tx :slackbot.database/tx}] (if (= "access_denied" error) (do (timbre/error {:message "Access denied authenticating workspace" :error error}) (-> (response/response nil) (response/status 204))) (if-let [state (teams/oauth-state tx {:state state})] (request-oauth-token tx state code) (do (timbre/error {:message "Received invalid state" :state state}) (response/bad-request {:message "Received invalid state" :state state})))))
true
;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.app-auth (:require [crypto.random :as rnd] [ring.util.codec :as codec] [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.config :as config] [slackbot.database.teams :as teams] [slackbot.slack :as slack])) (def requested-scopes ["commands" "emoji:read" "mpim:read" "mpim:write" "mpim:history" "im:read" "im:write" "im:history" "groups:read" "groups:write" "groups:history" "chat:write" "channels:read" "channels:write" "channels:history"]) (defn install "Generate a link to directly install this application on a Slack workspace." [{tx :slackbot.database/tx}] (let [state (rnd/base64 64) _ (teams/start-oauth tx {:state state}) scopes (->> requested-scopes (interpose \space) (apply str)) host "https://slack.com/oauth/authorize" params (codec/form-encode {:client_id (config/config [:slack :client-id]) :redirect_url (config/config [:slack :redirect-url]) :scope scopes :state state}) redirect-url (str host "?" params)] (-> (response/response nil) (response/header "Location" redirect-url) (response/status 302)))) (defn- create-new-workspace "Create a new workspace record in the database and clean up the state generated to create it." [tx state {:keys [team_id access_token app_user_id]}] (if-let [_ (teams/new-workspace tx {:workspace_id team_id :oauth_access_token access_token :app_user_id app_user_id})] (do (teams/delete-oauth tx {:state state}) (-> (response/response nil) (response/status 204))) (do (timbre/error {:message "Unable to save new workspace/team"}) (-> (response/response {:message "Unable to save new workspace/team"}) (response/status 500))))) (defn- request-oauth-token "Request an OAuth token from Slack and, if successful, create a new workspace record." [tx state code] (let [{{:keys [ok error] :as body} :body} @(slack/oauth-access {:code code :redirect_url (config/config [:slack :redirect-url])})] (if (true? ok) (create-new-workspace tx state body) (do (timbre/error {:message "Error message received from Slack" :error error}) (-> (response/response {:message "Error message received from Slack"}) (response/status 500)))))) (defn authorize "Complete the OAuth authorization process for a workspace. Take the code received in this request, submit it for a long-term OAuth token from the Slack API and save that token alongside the team ID and a few other details in the database." [{{:keys [code state error]} :query-params tx :slackbot.database/tx}] (if (= "access_denied" error) (do (timbre/error {:message "Access denied authenticating workspace" :error error}) (-> (response/response nil) (response/status 204))) (if-let [state (teams/oauth-state tx {:state state})] (request-oauth-token tx state code) (do (timbre/error {:message "Received invalid state" :state state}) (response/bad-request {:message "Received invalid state" :state state})))))
[ { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 31, "score": 0.999886155128479, "start": 18, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 45, "score": 0.9999317526817322, "start": 33, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/continuo/postgresql/schema.clj
niwinz/continuo
1
;; Copyright 2015 Andrey Antukh <niwi@niwi.nz> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns continuo.postgresql.schema (:require [suricatta.core :as sc] [cuerdas.core :as str] [continuo.postgresql.transaction :as tx] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.executor :as exec] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Attributes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rows->schema [results] (reduce (fn [acc item] (let [opts (codecs/bytes->data (:opts item)) ident (:ident opts)] (assoc acc ident (assoc opts :ident ident)))) {} results)) (defn refresh-schema-data! [tx] (let [schema (impl/-get-schema tx) conn (impl/-get-connection tx) sql "SELECT ident, opts FROM dbschema" res (sc/fetch conn sql)] (reset! schema (rows->schema res)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Trasnactors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti -apply-schema "A polymorphic abstraction for build appropiate layout transformation sql for the schema fact." (fn [conn [op]] op)) (defmethod -apply-schema :db/add [conn [op ident opts]] (let [tablename (attrs/normalize-attrname ident "user") typename (-> (attrs/lookup-type (:type opts)) (attrs/-sql-typename)) opts (assoc opts :ident ident) sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-add.mustache" {:name tablename :type typename})] (sc/execute conn [sql (codecs/data->bytes opts)]))) (defmethod -apply-schema :db/drop [conn [op ident]] (let [tablename (attrs/normalize-attrname ident "user") sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-drop.mustache" {:name tablename})] (sc/execute conn sql))) (defn -apply-tx [conn txid data] (let [sql (str "INSERT INTO txlog (id, facts, created_at)" " VALUES (?, ?, current_timestamp)") sqlv [sql txid (codecs/data->bytes data)]] (sc/execute conn sqlv))) (defn run-schema [tx schema] {:pre [(not (empty? schema))]} (exec/submit #(with-open [conn (impl/-get-connection tx)] (sc/atomic conn (let [txid (tx/get-next-txid conn)] (run! (partial -apply-schema conn) schema) (-apply-tx conn txid schema))) (refresh-schema-data! tx) @(impl/-get-schema tx))))
26570
;; Copyright 2015 <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns continuo.postgresql.schema (:require [suricatta.core :as sc] [cuerdas.core :as str] [continuo.postgresql.transaction :as tx] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.executor :as exec] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Attributes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rows->schema [results] (reduce (fn [acc item] (let [opts (codecs/bytes->data (:opts item)) ident (:ident opts)] (assoc acc ident (assoc opts :ident ident)))) {} results)) (defn refresh-schema-data! [tx] (let [schema (impl/-get-schema tx) conn (impl/-get-connection tx) sql "SELECT ident, opts FROM dbschema" res (sc/fetch conn sql)] (reset! schema (rows->schema res)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Trasnactors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti -apply-schema "A polymorphic abstraction for build appropiate layout transformation sql for the schema fact." (fn [conn [op]] op)) (defmethod -apply-schema :db/add [conn [op ident opts]] (let [tablename (attrs/normalize-attrname ident "user") typename (-> (attrs/lookup-type (:type opts)) (attrs/-sql-typename)) opts (assoc opts :ident ident) sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-add.mustache" {:name tablename :type typename})] (sc/execute conn [sql (codecs/data->bytes opts)]))) (defmethod -apply-schema :db/drop [conn [op ident]] (let [tablename (attrs/normalize-attrname ident "user") sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-drop.mustache" {:name tablename})] (sc/execute conn sql))) (defn -apply-tx [conn txid data] (let [sql (str "INSERT INTO txlog (id, facts, created_at)" " VALUES (?, ?, current_timestamp)") sqlv [sql txid (codecs/data->bytes data)]] (sc/execute conn sqlv))) (defn run-schema [tx schema] {:pre [(not (empty? schema))]} (exec/submit #(with-open [conn (impl/-get-connection tx)] (sc/atomic conn (let [txid (tx/get-next-txid conn)] (run! (partial -apply-schema conn) schema) (-apply-tx conn txid schema))) (refresh-schema-data! tx) @(impl/-get-schema tx))))
true
;; Copyright 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns continuo.postgresql.schema (:require [suricatta.core :as sc] [cuerdas.core :as str] [continuo.postgresql.transaction :as tx] [continuo.postgresql.attributes :as attrs] [continuo.impl :as impl] [continuo.executor :as exec] [continuo.util.template :as tmpl] [continuo.util.codecs :as codecs])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Attributes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- rows->schema [results] (reduce (fn [acc item] (let [opts (codecs/bytes->data (:opts item)) ident (:ident opts)] (assoc acc ident (assoc opts :ident ident)))) {} results)) (defn refresh-schema-data! [tx] (let [schema (impl/-get-schema tx) conn (impl/-get-connection tx) sql "SELECT ident, opts FROM dbschema" res (sc/fetch conn sql)] (reset! schema (rows->schema res)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Schema Trasnactors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defmulti -apply-schema "A polymorphic abstraction for build appropiate layout transformation sql for the schema fact." (fn [conn [op]] op)) (defmethod -apply-schema :db/add [conn [op ident opts]] (let [tablename (attrs/normalize-attrname ident "user") typename (-> (attrs/lookup-type (:type opts)) (attrs/-sql-typename)) opts (assoc opts :ident ident) sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-add.mustache" {:name tablename :type typename})] (sc/execute conn [sql (codecs/data->bytes opts)]))) (defmethod -apply-schema :db/drop [conn [op ident]] (let [tablename (attrs/normalize-attrname ident "user") sql (tmpl/render "bootstrap/postgresql/tmpl-schema-db-drop.mustache" {:name tablename})] (sc/execute conn sql))) (defn -apply-tx [conn txid data] (let [sql (str "INSERT INTO txlog (id, facts, created_at)" " VALUES (?, ?, current_timestamp)") sqlv [sql txid (codecs/data->bytes data)]] (sc/execute conn sqlv))) (defn run-schema [tx schema] {:pre [(not (empty? schema))]} (exec/submit #(with-open [conn (impl/-get-connection tx)] (sc/atomic conn (let [txid (tx/get-next-txid conn)] (run! (partial -apply-schema conn) schema) (-apply-tx conn txid schema))) (refresh-schema-data! tx) @(impl/-get-schema tx))))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.99980229139328, "start": 96, "tag": "NAME", "value": "Ragnar Svensson" }, { "context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ", "end": 129, "score": 0.9998182058334351, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/benchmark/graph_benchmark.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns benchmark.graph-benchmark (:require [clojure.java.io :as io] [clojure.test :refer :all] [criterium.core :as cc] [dynamo.graph :as g] [support.test-support :refer [tx-nodes with-clean-system]] [editor.core :as core] [integration.test-util :as test-util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.system :as isys])) (defn load-test-project! [world] (let [[workspace project app-view] (test-util/setup! world) project-graph (g/node-id->graph-id project) [atlas-node view] (test-util/open-scene-view! project app-view "/switcher/fish.atlas" 128 128)] {:project-graph project-graph :app-view app-view :resource-node atlas-node :resource-view view})) (defmacro do-benchmark [benchmark-name f] ;;; For more rigorous use benchmark instead of quick-benchmark `(do (println "***************************************") (println) (println) (println ~benchmark-name) (println) (println) (println "***************************************") (cc/with-progress-reporting (let [bresults# (cc/quick-benchmark ~f {})] (cc/report-result bresults# :os) bresults#)))) (g/defnode FWorkspace (inherits core/Scope) (input children g/Any)) (g/defnode FResource (property path g/Int) (output contents g/Int :cached (g/fnk [path] path))) (g/defnode FEditable (input alpha g/Int) (input beta g/Int) (input gamma g/Int) (output omega g/Int :cached (g/fnk [alpha beta gamma] (+ alpha beta gamma))) (output epsilon g/Int :cached (g/fnk [omega] (inc omega)))) (g/defnode FView (input omega g/Int) (input view g/Int) (output scene g/Int :cached (g/fnk [omega view] (+ omega view)))) (defn pile-of-nodes [where tp n] (tx-nodes (repeatedly (int n) #(g/make-node where tp)))) (defn connection-targets [how-many from] (partition how-many (repeatedly #(rand-nth from)))) (defn build-fake-graphs! [resource-count view-node-count] (let [project-graph (g/make-graph! :history true :volatility 1) view-graph (g/make-graph! :history false :volatility 10) workspace (first (tx-nodes (g/make-node project-graph FWorkspace))) bottom-layer (pile-of-nodes project-graph FResource resource-count) middle-layer (pile-of-nodes project-graph FEditable resource-count) top-layer (pile-of-nodes project-graph FEditable (bit-shift-right resource-count 2)) view-layer (pile-of-nodes view-graph FView view-node-count)] (g/transact [(for [b bottom-layer] (g/connect b :_node-id workspace :children)) (for [m middle-layer] (g/connect m :_node-id workspace :children)) (for [t top-layer] (g/connect t :_node-id workspace :children))]) (g/transact (mapcat #(g/set-property % :path (rand-int 10000)) bottom-layer)) (g/transact (mapcat (fn [m [a b c]] [(g/connect a :contents m :alpha) (g/connect b :contents m :beta) (g/connect c :contents m :gamma)]) middle-layer (connection-targets 3 bottom-layer))) (g/transact (mapcat (fn [t [o e o2]] [(g/connect o :omega t :alpha) (g/connect e :epsilon t :beta) (g/connect e :omega t :gamma)]) top-layer (connection-targets 3 middle-layer))) (g/transact (mapcat (fn [v [o e]] [(g/connect o :omega v :omega) (g/connect e :epsilon v :view)]) view-layer (connection-targets 2 top-layer))) [bottom-layer view-layer])) (g/defnode AThing (property a-property g/Str (default "Hey")) (output an-output g/Str (g/fnk [] "Boo."))) (g/defnode Container (input nodes g/Any)) (defn network-creation [] (do-benchmark "Whole Graph Network Creation" (with-clean-system (load-test-project! world)))) (defn add-one-node [] (println "Benching: Adding one node") (with-clean-system (load-test-project! world) (do-benchmark "Add One Node" (g/transact (g/make-node world AThing))))) (defn add-one-node-delete-one-node [] (with-clean-system (load-test-project! world) (do-benchmark "Add One Node and Delete One Node" (let [[new-node] (g/tx-nodes-added (g/transact (g/make-node world AThing)))] (g/transact (g/delete-node new-node)))))) (defn- safe-rand-nth [coll] (when (seq? coll) (rand-nth coll))) (defn set-property-some-nodes [] (with-clean-system (let [r (load-test-project! world) project-graph (isys/graph @g/*the-system* (:project-graph r)) affected-num 100 chosen-node-ids (repeatedly affected-num (partial rand-nth (ig/node-ids project-graph))) chosen-props (mapv (fn [node-id] (safe-rand-nth (vec (disj (-> node-id g/node-type g/declared-property-labels) :id)))) chosen-node-ids)] (str "Set Property on " affected-num " Nodes") (do-benchmark (str "Set Property on " affected-num " Nodes") (mapv (fn [node property] (g/set-property node property nil)) chosen-node-ids chosen-props))))) (defn add-two-nodes-and-connect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes and Connect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)))))) (defn add-two-nodes-and-connect-and-disconnect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes Connect and Disconnect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)) (g/transact (g/disconnect new-input-node :a-property new-output-node :nodes)))))) (defn one-node-value [] (with-clean-system (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (g/node-value new-input-node :an-output)))) (defn one-node-value-bench [] (with-clean-system {:cache-size 0} (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (do-benchmark "Pull :an-output" (g/node-value new-input-node :an-output))))) (defn- run-transactions-for-tracing [actions pulls] (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls)))))) (defn do-transactions-for-tracing [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeat :scene)) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeatedly #(rand-nth [:view :omega])))] (run-transactions-for-tracing actions pulls)))) (defn do-transactions [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeatedly n #(rand-int 10000))) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeat :scene))] (do-benchmark (format "Run %s transactions of setting a property and pulling values" n) (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls))))))))) (defn run-many-transactions [] (println "=======") (println) (doseq [num-trans (take 3 (iterate #(* 10 %) 500))] (let [bench-results (do-transactions num-trans) mean (first (:mean bench-results))] (when mean (println (str "TPS Report with " num-trans " txns: " (/ num-trans mean) " transactions per second"))))) (println) (println "=======")) (defn run-benchmarks [] (network-creation) (add-one-node) (add-one-node-delete-one-node) (set-property-some-nodes) (add-two-nodes-and-connect-them) (add-two-nodes-and-connect-and-disconnect-them) (run-many-transactions) (one-node-value-bench)) (defn -main [& args] (println "Running benchmarks and outputing results to ./test/benchmark/bench-results.txt") (with-open [w (clojure.java.io/writer "./test/benchmark/bench-results.txt")] (binding [*out* w] (run-benchmarks))))
4935
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 <NAME>, <NAME> ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns benchmark.graph-benchmark (:require [clojure.java.io :as io] [clojure.test :refer :all] [criterium.core :as cc] [dynamo.graph :as g] [support.test-support :refer [tx-nodes with-clean-system]] [editor.core :as core] [integration.test-util :as test-util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.system :as isys])) (defn load-test-project! [world] (let [[workspace project app-view] (test-util/setup! world) project-graph (g/node-id->graph-id project) [atlas-node view] (test-util/open-scene-view! project app-view "/switcher/fish.atlas" 128 128)] {:project-graph project-graph :app-view app-view :resource-node atlas-node :resource-view view})) (defmacro do-benchmark [benchmark-name f] ;;; For more rigorous use benchmark instead of quick-benchmark `(do (println "***************************************") (println) (println) (println ~benchmark-name) (println) (println) (println "***************************************") (cc/with-progress-reporting (let [bresults# (cc/quick-benchmark ~f {})] (cc/report-result bresults# :os) bresults#)))) (g/defnode FWorkspace (inherits core/Scope) (input children g/Any)) (g/defnode FResource (property path g/Int) (output contents g/Int :cached (g/fnk [path] path))) (g/defnode FEditable (input alpha g/Int) (input beta g/Int) (input gamma g/Int) (output omega g/Int :cached (g/fnk [alpha beta gamma] (+ alpha beta gamma))) (output epsilon g/Int :cached (g/fnk [omega] (inc omega)))) (g/defnode FView (input omega g/Int) (input view g/Int) (output scene g/Int :cached (g/fnk [omega view] (+ omega view)))) (defn pile-of-nodes [where tp n] (tx-nodes (repeatedly (int n) #(g/make-node where tp)))) (defn connection-targets [how-many from] (partition how-many (repeatedly #(rand-nth from)))) (defn build-fake-graphs! [resource-count view-node-count] (let [project-graph (g/make-graph! :history true :volatility 1) view-graph (g/make-graph! :history false :volatility 10) workspace (first (tx-nodes (g/make-node project-graph FWorkspace))) bottom-layer (pile-of-nodes project-graph FResource resource-count) middle-layer (pile-of-nodes project-graph FEditable resource-count) top-layer (pile-of-nodes project-graph FEditable (bit-shift-right resource-count 2)) view-layer (pile-of-nodes view-graph FView view-node-count)] (g/transact [(for [b bottom-layer] (g/connect b :_node-id workspace :children)) (for [m middle-layer] (g/connect m :_node-id workspace :children)) (for [t top-layer] (g/connect t :_node-id workspace :children))]) (g/transact (mapcat #(g/set-property % :path (rand-int 10000)) bottom-layer)) (g/transact (mapcat (fn [m [a b c]] [(g/connect a :contents m :alpha) (g/connect b :contents m :beta) (g/connect c :contents m :gamma)]) middle-layer (connection-targets 3 bottom-layer))) (g/transact (mapcat (fn [t [o e o2]] [(g/connect o :omega t :alpha) (g/connect e :epsilon t :beta) (g/connect e :omega t :gamma)]) top-layer (connection-targets 3 middle-layer))) (g/transact (mapcat (fn [v [o e]] [(g/connect o :omega v :omega) (g/connect e :epsilon v :view)]) view-layer (connection-targets 2 top-layer))) [bottom-layer view-layer])) (g/defnode AThing (property a-property g/Str (default "Hey")) (output an-output g/Str (g/fnk [] "Boo."))) (g/defnode Container (input nodes g/Any)) (defn network-creation [] (do-benchmark "Whole Graph Network Creation" (with-clean-system (load-test-project! world)))) (defn add-one-node [] (println "Benching: Adding one node") (with-clean-system (load-test-project! world) (do-benchmark "Add One Node" (g/transact (g/make-node world AThing))))) (defn add-one-node-delete-one-node [] (with-clean-system (load-test-project! world) (do-benchmark "Add One Node and Delete One Node" (let [[new-node] (g/tx-nodes-added (g/transact (g/make-node world AThing)))] (g/transact (g/delete-node new-node)))))) (defn- safe-rand-nth [coll] (when (seq? coll) (rand-nth coll))) (defn set-property-some-nodes [] (with-clean-system (let [r (load-test-project! world) project-graph (isys/graph @g/*the-system* (:project-graph r)) affected-num 100 chosen-node-ids (repeatedly affected-num (partial rand-nth (ig/node-ids project-graph))) chosen-props (mapv (fn [node-id] (safe-rand-nth (vec (disj (-> node-id g/node-type g/declared-property-labels) :id)))) chosen-node-ids)] (str "Set Property on " affected-num " Nodes") (do-benchmark (str "Set Property on " affected-num " Nodes") (mapv (fn [node property] (g/set-property node property nil)) chosen-node-ids chosen-props))))) (defn add-two-nodes-and-connect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes and Connect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)))))) (defn add-two-nodes-and-connect-and-disconnect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes Connect and Disconnect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)) (g/transact (g/disconnect new-input-node :a-property new-output-node :nodes)))))) (defn one-node-value [] (with-clean-system (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (g/node-value new-input-node :an-output)))) (defn one-node-value-bench [] (with-clean-system {:cache-size 0} (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (do-benchmark "Pull :an-output" (g/node-value new-input-node :an-output))))) (defn- run-transactions-for-tracing [actions pulls] (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls)))))) (defn do-transactions-for-tracing [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeat :scene)) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeatedly #(rand-nth [:view :omega])))] (run-transactions-for-tracing actions pulls)))) (defn do-transactions [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeatedly n #(rand-int 10000))) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeat :scene))] (do-benchmark (format "Run %s transactions of setting a property and pulling values" n) (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls))))))))) (defn run-many-transactions [] (println "=======") (println) (doseq [num-trans (take 3 (iterate #(* 10 %) 500))] (let [bench-results (do-transactions num-trans) mean (first (:mean bench-results))] (when mean (println (str "TPS Report with " num-trans " txns: " (/ num-trans mean) " transactions per second"))))) (println) (println "=======")) (defn run-benchmarks [] (network-creation) (add-one-node) (add-one-node-delete-one-node) (set-property-some-nodes) (add-two-nodes-and-connect-them) (add-two-nodes-and-connect-and-disconnect-them) (run-many-transactions) (one-node-value-bench)) (defn -main [& args] (println "Running benchmarks and outputing results to ./test/benchmark/bench-results.txt") (with-open [w (clojure.java.io/writer "./test/benchmark/bench-results.txt")] (binding [*out* w] (run-benchmarks))))
true
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns benchmark.graph-benchmark (:require [clojure.java.io :as io] [clojure.test :refer :all] [criterium.core :as cc] [dynamo.graph :as g] [support.test-support :refer [tx-nodes with-clean-system]] [editor.core :as core] [integration.test-util :as test-util] [internal.graph :as ig] [internal.graph.types :as gt] [internal.system :as isys])) (defn load-test-project! [world] (let [[workspace project app-view] (test-util/setup! world) project-graph (g/node-id->graph-id project) [atlas-node view] (test-util/open-scene-view! project app-view "/switcher/fish.atlas" 128 128)] {:project-graph project-graph :app-view app-view :resource-node atlas-node :resource-view view})) (defmacro do-benchmark [benchmark-name f] ;;; For more rigorous use benchmark instead of quick-benchmark `(do (println "***************************************") (println) (println) (println ~benchmark-name) (println) (println) (println "***************************************") (cc/with-progress-reporting (let [bresults# (cc/quick-benchmark ~f {})] (cc/report-result bresults# :os) bresults#)))) (g/defnode FWorkspace (inherits core/Scope) (input children g/Any)) (g/defnode FResource (property path g/Int) (output contents g/Int :cached (g/fnk [path] path))) (g/defnode FEditable (input alpha g/Int) (input beta g/Int) (input gamma g/Int) (output omega g/Int :cached (g/fnk [alpha beta gamma] (+ alpha beta gamma))) (output epsilon g/Int :cached (g/fnk [omega] (inc omega)))) (g/defnode FView (input omega g/Int) (input view g/Int) (output scene g/Int :cached (g/fnk [omega view] (+ omega view)))) (defn pile-of-nodes [where tp n] (tx-nodes (repeatedly (int n) #(g/make-node where tp)))) (defn connection-targets [how-many from] (partition how-many (repeatedly #(rand-nth from)))) (defn build-fake-graphs! [resource-count view-node-count] (let [project-graph (g/make-graph! :history true :volatility 1) view-graph (g/make-graph! :history false :volatility 10) workspace (first (tx-nodes (g/make-node project-graph FWorkspace))) bottom-layer (pile-of-nodes project-graph FResource resource-count) middle-layer (pile-of-nodes project-graph FEditable resource-count) top-layer (pile-of-nodes project-graph FEditable (bit-shift-right resource-count 2)) view-layer (pile-of-nodes view-graph FView view-node-count)] (g/transact [(for [b bottom-layer] (g/connect b :_node-id workspace :children)) (for [m middle-layer] (g/connect m :_node-id workspace :children)) (for [t top-layer] (g/connect t :_node-id workspace :children))]) (g/transact (mapcat #(g/set-property % :path (rand-int 10000)) bottom-layer)) (g/transact (mapcat (fn [m [a b c]] [(g/connect a :contents m :alpha) (g/connect b :contents m :beta) (g/connect c :contents m :gamma)]) middle-layer (connection-targets 3 bottom-layer))) (g/transact (mapcat (fn [t [o e o2]] [(g/connect o :omega t :alpha) (g/connect e :epsilon t :beta) (g/connect e :omega t :gamma)]) top-layer (connection-targets 3 middle-layer))) (g/transact (mapcat (fn [v [o e]] [(g/connect o :omega v :omega) (g/connect e :epsilon v :view)]) view-layer (connection-targets 2 top-layer))) [bottom-layer view-layer])) (g/defnode AThing (property a-property g/Str (default "Hey")) (output an-output g/Str (g/fnk [] "Boo."))) (g/defnode Container (input nodes g/Any)) (defn network-creation [] (do-benchmark "Whole Graph Network Creation" (with-clean-system (load-test-project! world)))) (defn add-one-node [] (println "Benching: Adding one node") (with-clean-system (load-test-project! world) (do-benchmark "Add One Node" (g/transact (g/make-node world AThing))))) (defn add-one-node-delete-one-node [] (with-clean-system (load-test-project! world) (do-benchmark "Add One Node and Delete One Node" (let [[new-node] (g/tx-nodes-added (g/transact (g/make-node world AThing)))] (g/transact (g/delete-node new-node)))))) (defn- safe-rand-nth [coll] (when (seq? coll) (rand-nth coll))) (defn set-property-some-nodes [] (with-clean-system (let [r (load-test-project! world) project-graph (isys/graph @g/*the-system* (:project-graph r)) affected-num 100 chosen-node-ids (repeatedly affected-num (partial rand-nth (ig/node-ids project-graph))) chosen-props (mapv (fn [node-id] (safe-rand-nth (vec (disj (-> node-id g/node-type g/declared-property-labels) :id)))) chosen-node-ids)] (str "Set Property on " affected-num " Nodes") (do-benchmark (str "Set Property on " affected-num " Nodes") (mapv (fn [node property] (g/set-property node property nil)) chosen-node-ids chosen-props))))) (defn add-two-nodes-and-connect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes and Connect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)))))) (defn add-two-nodes-and-connect-and-disconnect-them [] (with-clean-system (load-test-project! world) (do-benchmark "Add Two Nodes Connect and Disconnect Them" (let [txn-results (g/transact [(g/make-node world AThing) (g/make-node world Container)]) [new-input-node new-output-node] (g/tx-nodes-added txn-results)] (g/transact (g/connect new-input-node :a-property new-output-node :nodes)) (g/transact (g/disconnect new-input-node :a-property new-output-node :nodes)))))) (defn one-node-value [] (with-clean-system (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (g/node-value new-input-node :an-output)))) (defn one-node-value-bench [] (with-clean-system {:cache-size 0} (let [txn-results (g/transact [(g/make-node world AThing)]) [new-input-node] (g/tx-nodes-added txn-results)] (do-benchmark "Pull :an-output" (g/node-value new-input-node :an-output))))) (defn- run-transactions-for-tracing [actions pulls] (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls)))))) (defn do-transactions-for-tracing [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeat :scene)) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeatedly #(rand-nth [:view :omega])))] (run-transactions-for-tracing actions pulls)))) (defn do-transactions [n] (with-clean-system (let [[resources views] (build-fake-graphs! 1000 100) actions (map (fn [& a] a) (repeatedly n #(rand-nth resources)) (repeat n :path) (repeatedly n #(rand-int 10000))) pulls (map (fn [& a] a) (repeatedly #(rand-nth views)) (repeat :scene))] (do-benchmark (format "Run %s transactions of setting a property and pulling values" n) (loop [i 0 actions actions pulls pulls] (when (seq actions) (let [[node property value] (first actions)] (g/transact (g/set-property node property value)) (if (= 0 (mod i 11)) (let [[view output] (first pulls)] (g/node-value view output) (recur (inc i) (next actions) (next pulls))) (recur (inc i) (next actions) pulls))))))))) (defn run-many-transactions [] (println "=======") (println) (doseq [num-trans (take 3 (iterate #(* 10 %) 500))] (let [bench-results (do-transactions num-trans) mean (first (:mean bench-results))] (when mean (println (str "TPS Report with " num-trans " txns: " (/ num-trans mean) " transactions per second"))))) (println) (println "=======")) (defn run-benchmarks [] (network-creation) (add-one-node) (add-one-node-delete-one-node) (set-property-some-nodes) (add-two-nodes-and-connect-them) (add-two-nodes-and-connect-and-disconnect-them) (run-many-transactions) (one-node-value-bench)) (defn -main [& args] (println "Running benchmarks and outputing results to ./test/benchmark/bench-results.txt") (with-open [w (clojure.java.io/writer "./test/benchmark/bench-results.txt")] (binding [*out* w] (run-benchmarks))))
[ { "context": " :name \"Science\"}}\n\n {:student {:name \"Ivan\" ;;; And then Ivan, who does English, Sc", "end": 2882, "score": 0.9998122453689575, "start": 2878, "tag": "NAME", "value": "Ivan" }, { "context": "\n {:student {:name \"Ivan\" ;;; And then Ivan, who does English, Science and Sports\n ", "end": 2910, "score": 0.9995119571685791, "start": 2906, "tag": "NAME", "value": "Ivan" }, { "context": ":+/db/id (iid :Sports)}}}}\n\n {:teacher {:name \"Mr. Blair\" ;; Here's Mr Blair\n ", "end": 3151, "score": 0.9984259009361267, "start": 3142, "tag": "NAME", "value": "Mr. Blair" }, { "context": " \"Mr. Blair\" ;; Here's Mr Blair\n :teaches #{{:+/db/id (iid :Art)\n ", "end": 3193, "score": 0.5885472297668457, "start": 3190, "tag": "NAME", "value": "air" }, { "context": " ;; And a fish and a bird\n\n {:teacher {:name \"Mr. Carpenter\" ;; This is Mr Carpenter\n ", "end": 3641, "score": 0.9993870854377747, "start": 3628, "tag": "NAME", "value": "Mr. Carpenter" }, { "context": " \"Mr. Carpenter\" ;; This is Mr Carpenter\n :canTeach #{:sports :maths}\n ", "end": 3684, "score": 0.9157475233078003, "start": 3676, "tag": "NAME", "value": "arpenter" }, { "context": "se\n :students #{{:name \"Jack\" ;; There's Jack\n ", "end": 4028, "score": 0.9997291564941406, "start": 4024, "tag": "NAME", "value": "Jack" }, { "context": " :students #{{:name \"Jack\" ;; There's Jack\n :siblings", "end": 4047, "score": 0.998529314994812, "start": 4043, "tag": "NAME", "value": "Jack" }, { "context": " :students {:name \"Anna\" ;; There's also Anna in the class\n ", "end": 4292, "score": 0.9997410774230957, "start": 4288, "tag": "NAME", "value": "Anna" }, { "context": " :students {:name \"Anna\" ;; There's also Anna in the class\n ", "end": 4315, "score": 0.9984556436538696, "start": 4311, "tag": "NAME", "value": "Anna" }, { "context": " :students #{{:name \"Charlie\"\n :sibling", "end": 4891, "score": 0.9997811913490295, "start": 4884, "tag": "NAME", "value": "Charlie" }, { "context": " {:name \"Francis\"\n :sibling", "end": 5078, "score": 0.999786913394928, "start": 5071, "tag": "NAME", "value": "Francis" }, { "context": " {:name \"Harry\"\n :sibling", "end": 5337, "score": 0.9997854828834534, "start": 5332, "tag": "NAME", "value": "Harry" }, { "context": " :name \"English A\"\n :teacher {:name \"Mr. Anderson\" ;; Mr Anderson is the teacher\n ", "end": 5785, "score": 0.9907681941986084, "start": 5773, "tag": "NAME", "value": "Mr. Anderson" }, { "context": "\n :teacher {:name \"Mr. Anderson\" ;; Mr Anderson is the teacher\n :teaches {", "end": 5801, "score": 0.9686990976333618, "start": 5793, "tag": "NAME", "value": "Anderson" }, { "context": " :pets :dog}\n :students #{{:name \"Bobby\" ;; And the students are listed\n ", "end": 6014, "score": 0.9997515082359314, "start": 6009, "tag": "NAME", "value": "Bobby" }, { "context": "d (iid :Maths)}}\n {:name \"David\"\n :siblings 5\n ", "end": 6186, "score": 0.9998460412025452, "start": 6181, "tag": "NAME", "value": "David" }, { "context": " (iid :Maths)}}}\n {:name \"Erin\"\n :siblings 1\n ", "end": 6389, "score": 0.9997843503952026, "start": 6385, "tag": "NAME", "value": "Erin" }, { "context": "id (iid :Art)}}}\n {:name \"Kelly\"\n :siblings 0\n ", "end": 6528, "score": 0.9997532367706299, "start": 6523, "tag": "NAME", "value": "Kelly" }, { "context": "iid :Maths)}}}}}}])\n\n\n\n(def DATA\n {:user {:name \"zcaudate\"\n :blog_owner_of\n #{{:name \"Som", "end": 6737, "score": 0.9995236396789551, "start": 6729, "tag": "USERNAME", "value": "zcaudate" }, { "context": "id (adi/iid :Adam)\n :name \"Adam\"} {:name \"Bill\"}]\n :posts [{:title \"H", "end": 6903, "score": 0.9998294711112976, "start": 6899, "tag": "NAME", "value": "Adam" }, { "context": "am)\n :name \"Adam\"} {:name \"Bill\"}]\n :posts [{:title \"How To Flex Data", "end": 6918, "score": 0.9998685121536255, "start": 6914, "tag": "NAME", "value": "Bill" }, { "context": "\n :user (adi/iid :Adam)}}\n {:title \"How To Flex Data", "end": 7171, "score": 0.9856823086738586, "start": 7167, "tag": "NAME", "value": "Adam" } ]
data/test/clojure/e4006e2043e443b875c9ced14b05e3ff00c509afs1.clj
harshp8l/deep-learning-lang-detection
84
(ns adi-example.s1 (:require [ring.util.response :refer [response]] [ring.middleware.session :refer [wrap-session]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [resources]] [ribol.core :refer [manage on]] [cheshire.core :as json] [adi.core :refer :all :as adi] [org.httpkit.server :refer [run-server]] [vraja.http-kit :refer [with-clj-channel with-js-channel]] [clojure.core.async :refer [<! >! put! close! go]])) (def DEFAULT_SCHEMA {:blog {:name [{:required true}] :id [{:type :long}] :owner [{:type :ref :ref {:ns :user :rval :blog_owner_of}}] :authors [{:type :ref :cardinality :many :ref {:ns :user :rval :blog_author_of}}]} :post {:blog [{:type :ref :ref {:ns :blog}}] :author [{:type :ref :ref {:ns :user}}] :tags [{:cardinality :many}] :text [{}] :title [{:required true}]} :comment {:post [{:type :ref :ref {:ns :post}}] :text [{:required true}] :user [{:type :ref :ref {:ns :user}}]} :user {:name [{:required true}]}}) (def student-schema {:class {:type [{:type :keyword}] :name [{:type :string}] :accelerated [{:type :boolean}] :teacher [{:type :ref ;; <- Note that refs allow a reverse :ref {:ns :teacher ;; look-up to be defined to allow for more :rval :teaches}}]} ;; natural expression. In this case, :teacher {:name [{:type :string}] ;; we say that every `class` has a `teacher` :canTeach [{:type :keyword ;; so the reverse will be defined as a :cardinality :many}] ;; a `teacher` `teaches` a class :pets [{:type :keyword :cardinality :many}]} :student {:name [{:type :string}] :siblings [{:type :long}] :classes [{:type :ref :ref {:ns :class :rval :students} ;; Same with students :cardinality :many}]}}) (def student-data ;;; Lets See.... [{:db/id (iid :Maths) :class {:type :maths ;;; There's Math. The most important subject :name "Maths" ;;; We will be giving all the classes ids :accelerated true}} ;;; for easier reference {:db/id (iid :Science) ;;; Lets add science :class {:type :science :name "Science"}} {:student {:name "Ivan" ;;; And then Ivan, who does English, Science and Sports :siblings 2 :classes #{{:+/db/id (iid :EnglishA)} {:+/db/id (iid :Science)} {:+/db/id (iid :Sports)}}}} {:teacher {:name "Mr. Blair" ;; Here's Mr Blair :teaches #{{:+/db/id (iid :Art) :type :art ;; He teaches Art :name "Art" :accelerated true} {:+/db/id (iid :Science)}} ;; He also teaches Science :canTeach #{:maths :science} :pets #{:fish :bird}}} ;; And a fish and a bird {:teacher {:name "Mr. Carpenter" ;; This is Mr Carpenter :canTeach #{:sports :maths} :pets #{:dog :fish :bird} :teaches #{{:+/db/id (iid :Sports) ;; He teaches sports :type :sports :name "Sports" :accelerated false :students #{{:name "Jack" ;; There's Jack :siblings 4 ;; Who is also in EnglishB and Maths :classes #{{:+/db/id (iid :EnglishB) :students {:name "Anna" ;; There's also Anna in the class :siblings 1 :classes #{{:+/db/id (iid :Art)}}}} {:+/db/id (iid :Maths)}}}}} {:+/db/id (iid :EnglishB) :type :english ;; Now we revisit English B :name "English B" ;; Here are all the additional students :students #{{:name "Charlie" :siblings 3 :classes #{{:+/db/id (iid :Art)}}} {:name "Francis" :siblings 0 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Maths)}}} {:name "Harry" :siblings 2 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}}} {:db/id (iid :EnglishA) ;; What about Engilsh A ? :class {:type :english :name "English A" :teacher {:name "Mr. Anderson" ;; Mr Anderson is the teacher :teaches {:+/db/id (iid :Maths)} ;; He also takes Maths :canTeach :maths :pets :dog} :students #{{:name "Bobby" ;; And the students are listed :siblings 2 :classes {:+/db/id (iid :Maths)}} {:name "David" :siblings 5 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}} {:name "Erin" :siblings 1 :classes #{{:+/db/id (iid :Art)}}} {:name "Kelly" :siblings 0 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}]) (def DATA {:user {:name "zcaudate" :blog_owner_of #{{:name "Something Same" :id 3 :authors [{:+/db/id (adi/iid :Adam) :name "Adam"} {:name "Bill"}] :posts [{:title "How To Flex Data" :tags #{"computing"}} {:title "Cats and Dogs" :tags #{"pets"} :comments {:text "This is a great article" :user (adi/iid :Adam)}} {:title "How To Flex Data"}]}}}}) (def URI "datomic:mem://adi-example-s1") (def ENV (connect-env! URI student-schema true)) ;;(def ENV (connect-env! URI DEFAULT_SCHEMA true)) (insert! ENV student-data) (comment (reset! (:model STATE) {:hello "a" :hoeuo (fn [] nil)}) ) ;;(select ENV {:blog/owner '_}) (def STATE {:uri URI :env (atom ENV) :schema (atom (-> ENV :schema :tree)) :model (atom nil) :access (atom nil) :return (atom nil)}) (def METHODS {:insert! insert! :delete! delete! :update! update! :retract! retract! :select select :update-in! update-in! :delete-in! delete-in! :retract-in! retract-in!}) (comment {:op-type "setup" :resource #{"schema" "model" "access"} :op #{"set" "clear" "return"} } (reset! (:schema STATE) {:account {:user [{}]}}) ) (defn parse-clj-arg [s] (try (read-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-js-arg [s] (try (json/parse-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-arg [msg s] (condp = (get msg "lang") "clj" (parse-clj-arg s) "js" (parse-js-arg s))) (defn handle-setup-request [msg] (let [op (get msg "op") resource (get msg "resource") res (STATE (keyword resource)) arg (parse-clj-arg (get msg "arg"))] (cond (and (= op "set") (= resource "schema")) (let [env (connect-env! URI arg true)] (reset! (:env STATE) env) (reset! (:schema STATE) (-> env :schema :tree)) @(:schema STATE)) (= op "set") (do (reset! res arg) @res) (= op "view") @res (= op "clear") (do (reset! res nil) @res)))) (defn handle-standard-request [msg] #_(println "STANDARD REQUEST:" (get msg "op") (get msg "args")) (let [op (get msg "op") nargs (get msg "nargs") args (->> (get msg "args") (map #(parse-arg msg %)) (take nargs)) f (METHODS (keyword op)) res (apply f @(:env STATE) (concat args [:transact :full] (if (get msg "ids") [:ids]) (if-let [ret @(:return STATE)] [:return ret]) (if-let [acc @(:access STATE)] [:access acc]) (if-let [mod @(:model STATE)] [:model mod])))] (println "STANDARD REQUEST:" res) (if (not= op "insert!") res {:message "DONE"}))) (defn ws-handler [req] (let [req (assoc req :ws-session (atom {}))] (with-js-channel req ws (go (loop [] (when-let [msg (<! ws)] (let [op-type (get msg "op-type") output (try (manage (cond (= op-type "test") {:stuff (get msg "return")} (= op-type "setup") (handle-setup-request msg) (= op-type "standard") (handle-standard-request msg)) (on :data-not-in-schema [nsv] {:error (str nsv " is not in the schema")})) (catch clojure.lang.ExceptionInfo e (ex-data e)) (catch Throwable t (.printStackTrace t)))] (if output (>! ws output) (>! ws {})) (recur)))))))) (defroutes app (GET "/ws" [] (wrap-session ws-handler)) (resources "/")) (serv) (def serv (run-server app {:port 8088})) (comment )
115707
(ns adi-example.s1 (:require [ring.util.response :refer [response]] [ring.middleware.session :refer [wrap-session]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [resources]] [ribol.core :refer [manage on]] [cheshire.core :as json] [adi.core :refer :all :as adi] [org.httpkit.server :refer [run-server]] [vraja.http-kit :refer [with-clj-channel with-js-channel]] [clojure.core.async :refer [<! >! put! close! go]])) (def DEFAULT_SCHEMA {:blog {:name [{:required true}] :id [{:type :long}] :owner [{:type :ref :ref {:ns :user :rval :blog_owner_of}}] :authors [{:type :ref :cardinality :many :ref {:ns :user :rval :blog_author_of}}]} :post {:blog [{:type :ref :ref {:ns :blog}}] :author [{:type :ref :ref {:ns :user}}] :tags [{:cardinality :many}] :text [{}] :title [{:required true}]} :comment {:post [{:type :ref :ref {:ns :post}}] :text [{:required true}] :user [{:type :ref :ref {:ns :user}}]} :user {:name [{:required true}]}}) (def student-schema {:class {:type [{:type :keyword}] :name [{:type :string}] :accelerated [{:type :boolean}] :teacher [{:type :ref ;; <- Note that refs allow a reverse :ref {:ns :teacher ;; look-up to be defined to allow for more :rval :teaches}}]} ;; natural expression. In this case, :teacher {:name [{:type :string}] ;; we say that every `class` has a `teacher` :canTeach [{:type :keyword ;; so the reverse will be defined as a :cardinality :many}] ;; a `teacher` `teaches` a class :pets [{:type :keyword :cardinality :many}]} :student {:name [{:type :string}] :siblings [{:type :long}] :classes [{:type :ref :ref {:ns :class :rval :students} ;; Same with students :cardinality :many}]}}) (def student-data ;;; Lets See.... [{:db/id (iid :Maths) :class {:type :maths ;;; There's Math. The most important subject :name "Maths" ;;; We will be giving all the classes ids :accelerated true}} ;;; for easier reference {:db/id (iid :Science) ;;; Lets add science :class {:type :science :name "Science"}} {:student {:name "<NAME>" ;;; And then <NAME>, who does English, Science and Sports :siblings 2 :classes #{{:+/db/id (iid :EnglishA)} {:+/db/id (iid :Science)} {:+/db/id (iid :Sports)}}}} {:teacher {:name "<NAME>" ;; Here's Mr Bl<NAME> :teaches #{{:+/db/id (iid :Art) :type :art ;; He teaches Art :name "Art" :accelerated true} {:+/db/id (iid :Science)}} ;; He also teaches Science :canTeach #{:maths :science} :pets #{:fish :bird}}} ;; And a fish and a bird {:teacher {:name "<NAME>" ;; This is Mr C<NAME> :canTeach #{:sports :maths} :pets #{:dog :fish :bird} :teaches #{{:+/db/id (iid :Sports) ;; He teaches sports :type :sports :name "Sports" :accelerated false :students #{{:name "<NAME>" ;; There's <NAME> :siblings 4 ;; Who is also in EnglishB and Maths :classes #{{:+/db/id (iid :EnglishB) :students {:name "<NAME>" ;; There's also <NAME> in the class :siblings 1 :classes #{{:+/db/id (iid :Art)}}}} {:+/db/id (iid :Maths)}}}}} {:+/db/id (iid :EnglishB) :type :english ;; Now we revisit English B :name "English B" ;; Here are all the additional students :students #{{:name "<NAME>" :siblings 3 :classes #{{:+/db/id (iid :Art)}}} {:name "<NAME>" :siblings 0 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Maths)}}} {:name "<NAME>" :siblings 2 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}}} {:db/id (iid :EnglishA) ;; What about Engilsh A ? :class {:type :english :name "English A" :teacher {:name "<NAME>" ;; Mr <NAME> is the teacher :teaches {:+/db/id (iid :Maths)} ;; He also takes Maths :canTeach :maths :pets :dog} :students #{{:name "<NAME>" ;; And the students are listed :siblings 2 :classes {:+/db/id (iid :Maths)}} {:name "<NAME>" :siblings 5 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}} {:name "<NAME>" :siblings 1 :classes #{{:+/db/id (iid :Art)}}} {:name "<NAME>" :siblings 0 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}]) (def DATA {:user {:name "zcaudate" :blog_owner_of #{{:name "Something Same" :id 3 :authors [{:+/db/id (adi/iid :Adam) :name "<NAME>"} {:name "<NAME>"}] :posts [{:title "How To Flex Data" :tags #{"computing"}} {:title "Cats and Dogs" :tags #{"pets"} :comments {:text "This is a great article" :user (adi/iid :<NAME>)}} {:title "How To Flex Data"}]}}}}) (def URI "datomic:mem://adi-example-s1") (def ENV (connect-env! URI student-schema true)) ;;(def ENV (connect-env! URI DEFAULT_SCHEMA true)) (insert! ENV student-data) (comment (reset! (:model STATE) {:hello "a" :hoeuo (fn [] nil)}) ) ;;(select ENV {:blog/owner '_}) (def STATE {:uri URI :env (atom ENV) :schema (atom (-> ENV :schema :tree)) :model (atom nil) :access (atom nil) :return (atom nil)}) (def METHODS {:insert! insert! :delete! delete! :update! update! :retract! retract! :select select :update-in! update-in! :delete-in! delete-in! :retract-in! retract-in!}) (comment {:op-type "setup" :resource #{"schema" "model" "access"} :op #{"set" "clear" "return"} } (reset! (:schema STATE) {:account {:user [{}]}}) ) (defn parse-clj-arg [s] (try (read-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-js-arg [s] (try (json/parse-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-arg [msg s] (condp = (get msg "lang") "clj" (parse-clj-arg s) "js" (parse-js-arg s))) (defn handle-setup-request [msg] (let [op (get msg "op") resource (get msg "resource") res (STATE (keyword resource)) arg (parse-clj-arg (get msg "arg"))] (cond (and (= op "set") (= resource "schema")) (let [env (connect-env! URI arg true)] (reset! (:env STATE) env) (reset! (:schema STATE) (-> env :schema :tree)) @(:schema STATE)) (= op "set") (do (reset! res arg) @res) (= op "view") @res (= op "clear") (do (reset! res nil) @res)))) (defn handle-standard-request [msg] #_(println "STANDARD REQUEST:" (get msg "op") (get msg "args")) (let [op (get msg "op") nargs (get msg "nargs") args (->> (get msg "args") (map #(parse-arg msg %)) (take nargs)) f (METHODS (keyword op)) res (apply f @(:env STATE) (concat args [:transact :full] (if (get msg "ids") [:ids]) (if-let [ret @(:return STATE)] [:return ret]) (if-let [acc @(:access STATE)] [:access acc]) (if-let [mod @(:model STATE)] [:model mod])))] (println "STANDARD REQUEST:" res) (if (not= op "insert!") res {:message "DONE"}))) (defn ws-handler [req] (let [req (assoc req :ws-session (atom {}))] (with-js-channel req ws (go (loop [] (when-let [msg (<! ws)] (let [op-type (get msg "op-type") output (try (manage (cond (= op-type "test") {:stuff (get msg "return")} (= op-type "setup") (handle-setup-request msg) (= op-type "standard") (handle-standard-request msg)) (on :data-not-in-schema [nsv] {:error (str nsv " is not in the schema")})) (catch clojure.lang.ExceptionInfo e (ex-data e)) (catch Throwable t (.printStackTrace t)))] (if output (>! ws output) (>! ws {})) (recur)))))))) (defroutes app (GET "/ws" [] (wrap-session ws-handler)) (resources "/")) (serv) (def serv (run-server app {:port 8088})) (comment )
true
(ns adi-example.s1 (:require [ring.util.response :refer [response]] [ring.middleware.session :refer [wrap-session]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [resources]] [ribol.core :refer [manage on]] [cheshire.core :as json] [adi.core :refer :all :as adi] [org.httpkit.server :refer [run-server]] [vraja.http-kit :refer [with-clj-channel with-js-channel]] [clojure.core.async :refer [<! >! put! close! go]])) (def DEFAULT_SCHEMA {:blog {:name [{:required true}] :id [{:type :long}] :owner [{:type :ref :ref {:ns :user :rval :blog_owner_of}}] :authors [{:type :ref :cardinality :many :ref {:ns :user :rval :blog_author_of}}]} :post {:blog [{:type :ref :ref {:ns :blog}}] :author [{:type :ref :ref {:ns :user}}] :tags [{:cardinality :many}] :text [{}] :title [{:required true}]} :comment {:post [{:type :ref :ref {:ns :post}}] :text [{:required true}] :user [{:type :ref :ref {:ns :user}}]} :user {:name [{:required true}]}}) (def student-schema {:class {:type [{:type :keyword}] :name [{:type :string}] :accelerated [{:type :boolean}] :teacher [{:type :ref ;; <- Note that refs allow a reverse :ref {:ns :teacher ;; look-up to be defined to allow for more :rval :teaches}}]} ;; natural expression. In this case, :teacher {:name [{:type :string}] ;; we say that every `class` has a `teacher` :canTeach [{:type :keyword ;; so the reverse will be defined as a :cardinality :many}] ;; a `teacher` `teaches` a class :pets [{:type :keyword :cardinality :many}]} :student {:name [{:type :string}] :siblings [{:type :long}] :classes [{:type :ref :ref {:ns :class :rval :students} ;; Same with students :cardinality :many}]}}) (def student-data ;;; Lets See.... [{:db/id (iid :Maths) :class {:type :maths ;;; There's Math. The most important subject :name "Maths" ;;; We will be giving all the classes ids :accelerated true}} ;;; for easier reference {:db/id (iid :Science) ;;; Lets add science :class {:type :science :name "Science"}} {:student {:name "PI:NAME:<NAME>END_PI" ;;; And then PI:NAME:<NAME>END_PI, who does English, Science and Sports :siblings 2 :classes #{{:+/db/id (iid :EnglishA)} {:+/db/id (iid :Science)} {:+/db/id (iid :Sports)}}}} {:teacher {:name "PI:NAME:<NAME>END_PI" ;; Here's Mr BlPI:NAME:<NAME>END_PI :teaches #{{:+/db/id (iid :Art) :type :art ;; He teaches Art :name "Art" :accelerated true} {:+/db/id (iid :Science)}} ;; He also teaches Science :canTeach #{:maths :science} :pets #{:fish :bird}}} ;; And a fish and a bird {:teacher {:name "PI:NAME:<NAME>END_PI" ;; This is Mr CPI:NAME:<NAME>END_PI :canTeach #{:sports :maths} :pets #{:dog :fish :bird} :teaches #{{:+/db/id (iid :Sports) ;; He teaches sports :type :sports :name "Sports" :accelerated false :students #{{:name "PI:NAME:<NAME>END_PI" ;; There's PI:NAME:<NAME>END_PI :siblings 4 ;; Who is also in EnglishB and Maths :classes #{{:+/db/id (iid :EnglishB) :students {:name "PI:NAME:<NAME>END_PI" ;; There's also PI:NAME:<NAME>END_PI in the class :siblings 1 :classes #{{:+/db/id (iid :Art)}}}} {:+/db/id (iid :Maths)}}}}} {:+/db/id (iid :EnglishB) :type :english ;; Now we revisit English B :name "English B" ;; Here are all the additional students :students #{{:name "PI:NAME:<NAME>END_PI" :siblings 3 :classes #{{:+/db/id (iid :Art)}}} {:name "PI:NAME:<NAME>END_PI" :siblings 0 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Maths)}}} {:name "PI:NAME:<NAME>END_PI" :siblings 2 :classes #{{:+/db/id (iid :Art)} {:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}}} {:db/id (iid :EnglishA) ;; What about Engilsh A ? :class {:type :english :name "English A" :teacher {:name "PI:NAME:<NAME>END_PI" ;; Mr PI:NAME:<NAME>END_PI is the teacher :teaches {:+/db/id (iid :Maths)} ;; He also takes Maths :canTeach :maths :pets :dog} :students #{{:name "PI:NAME:<NAME>END_PI" ;; And the students are listed :siblings 2 :classes {:+/db/id (iid :Maths)}} {:name "PI:NAME:<NAME>END_PI" :siblings 5 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}} {:name "PI:NAME:<NAME>END_PI" :siblings 1 :classes #{{:+/db/id (iid :Art)}}} {:name "PI:NAME:<NAME>END_PI" :siblings 0 :classes #{{:+/db/id (iid :Science)} {:+/db/id (iid :Maths)}}}}}}]) (def DATA {:user {:name "zcaudate" :blog_owner_of #{{:name "Something Same" :id 3 :authors [{:+/db/id (adi/iid :Adam) :name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}] :posts [{:title "How To Flex Data" :tags #{"computing"}} {:title "Cats and Dogs" :tags #{"pets"} :comments {:text "This is a great article" :user (adi/iid :PI:NAME:<NAME>END_PI)}} {:title "How To Flex Data"}]}}}}) (def URI "datomic:mem://adi-example-s1") (def ENV (connect-env! URI student-schema true)) ;;(def ENV (connect-env! URI DEFAULT_SCHEMA true)) (insert! ENV student-data) (comment (reset! (:model STATE) {:hello "a" :hoeuo (fn [] nil)}) ) ;;(select ENV {:blog/owner '_}) (def STATE {:uri URI :env (atom ENV) :schema (atom (-> ENV :schema :tree)) :model (atom nil) :access (atom nil) :return (atom nil)}) (def METHODS {:insert! insert! :delete! delete! :update! update! :retract! retract! :select select :update-in! update-in! :delete-in! delete-in! :retract-in! retract-in!}) (comment {:op-type "setup" :resource #{"schema" "model" "access"} :op #{"set" "clear" "return"} } (reset! (:schema STATE) {:account {:user [{}]}}) ) (defn parse-clj-arg [s] (try (read-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-js-arg [s] (try (json/parse-string s) (catch Throwable t #_(.printStackTrace t)))) (defn parse-arg [msg s] (condp = (get msg "lang") "clj" (parse-clj-arg s) "js" (parse-js-arg s))) (defn handle-setup-request [msg] (let [op (get msg "op") resource (get msg "resource") res (STATE (keyword resource)) arg (parse-clj-arg (get msg "arg"))] (cond (and (= op "set") (= resource "schema")) (let [env (connect-env! URI arg true)] (reset! (:env STATE) env) (reset! (:schema STATE) (-> env :schema :tree)) @(:schema STATE)) (= op "set") (do (reset! res arg) @res) (= op "view") @res (= op "clear") (do (reset! res nil) @res)))) (defn handle-standard-request [msg] #_(println "STANDARD REQUEST:" (get msg "op") (get msg "args")) (let [op (get msg "op") nargs (get msg "nargs") args (->> (get msg "args") (map #(parse-arg msg %)) (take nargs)) f (METHODS (keyword op)) res (apply f @(:env STATE) (concat args [:transact :full] (if (get msg "ids") [:ids]) (if-let [ret @(:return STATE)] [:return ret]) (if-let [acc @(:access STATE)] [:access acc]) (if-let [mod @(:model STATE)] [:model mod])))] (println "STANDARD REQUEST:" res) (if (not= op "insert!") res {:message "DONE"}))) (defn ws-handler [req] (let [req (assoc req :ws-session (atom {}))] (with-js-channel req ws (go (loop [] (when-let [msg (<! ws)] (let [op-type (get msg "op-type") output (try (manage (cond (= op-type "test") {:stuff (get msg "return")} (= op-type "setup") (handle-setup-request msg) (= op-type "standard") (handle-standard-request msg)) (on :data-not-in-schema [nsv] {:error (str nsv " is not in the schema")})) (catch clojure.lang.ExceptionInfo e (ex-data e)) (catch Throwable t (.printStackTrace t)))] (if output (>! ws output) (>! ws {})) (recur)))))))) (defroutes app (GET "/ws" [] (wrap-session ws-handler)) (resources "/")) (serv) (def serv (run-server app {:port 8088})) (comment )
[ { "context": "\n port 28015\n username \"admin\"\n password \"\"}} db-server\n tc", "end": 2224, "score": 0.9984123110771179, "start": 2219, "tag": "USERNAME", "value": "admin" }, { "context": "initial-scram]} (scram/initial-proposal {:username username})\n _ (send message)\n {:keys [se", "end": 3336, "score": 0.998327910900116, "start": 3328, "tag": "USERNAME", "value": "username" }, { "context": " :password password})\n _ (send message)\n {:keys [au", "end": 4014, "score": 0.9951393604278564, "start": 4006, "tag": "PASSWORD", "value": "password" } ]
src/servo/connection.clj
7theta/servo
0
;; Copyright (c) 7theta. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; MIT License (https://opensource.org/licenses/MIT) which can also be ;; found in the LICENSE file at the root of this distribution. ;; ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any others, from this software. (ns servo.connection (:refer-clojure :exclude [send]) (:require [servo.util.scram :as scram] [signum.signal :refer [signal alter!]] [tempus.core :as t] [aleph.tcp :as tcp] [manifold.stream :as s] [manifold.deferred :as d] [gloss.core :as gloss] [gloss.io :as gloss-io] [byte-streams.core :as bs] [jsonista.core :as json] [inflections.core :refer [hyphenate underscore]] [utilis.map :refer [map-keys map-vals]] [utilis.types.number :refer [string->long string->double]] [clojure.string :as st] [integrant.core :as ig] [metrics.gauges :refer [gauge-fn]] [clojure.tools.logging :as log]) (:import [tempus.core DateTime] [java.nio ByteBuffer ByteOrder] [java.io ByteArrayOutputStream])) (declare connect disconnect ->rql-connection await-tables-ready ensure-db ensure-table ensure-index json-mapper ->rt-name ->rt-query ->rt-query-term send handle-message token request-types) (defmethod ig/init-key :servo/connection [_ options] (connect options)) (defmethod ig/halt-key! :servo/connection [_ connection] (try (disconnect connection) (catch Exception e (log/error ":servo/connection shutdown exception" e)))) (defn connect [{:keys [db-server db-name await-ready trace response-buffer-size on-disconnected tables indices] :or {await-ready true response-buffer-size 1000}}] (when trace (log/debug "servo/connection connect" (pr-str db-server))) (let [{:keys [host port username password] :or {host "localhost" port 28015 username "admin" password ""}} db-server tcp-connection (tcp/client {:host host :port port})] @(s/put! @tcp-connection (byte-array [0xc3 0xbd 0xc2 0x34])) (let [version (try (:server_version (-> @(s/take! @tcp-connection) bs/to-string (json/read-value json/keyword-keys-object-mapper))) (catch Exception _ (throw (ex-info ":servo/connection initial handshake failed" {:db-server db-server :db-name db-name})))) send (fn [message] (s/put! @tcp-connection (let [json-str (json/write-value-as-string message json-mapper)] ;; Rethink requires JSON strings to be "null terminated" (byte-array (inc (count json-str)) (map int json-str))))) recv #(json/read-value (bs/to-string @(s/take! @tcp-connection)) json-mapper) {:keys [message client-initial-scram]} (scram/initial-proposal {:username username}) _ (send message) {:keys [server-scram server-authentication]} (scram/server-challenge {:client-initial-scram client-initial-scram} (recv)) {:keys [message server-signature]} (scram/authentication-request {:client-initial-scram client-initial-scram :server-authentication server-authentication :server-scram server-scram :password password}) _ (send message) {:keys [authentication success]} (recv)] (when-not (and success (scram/validate-server {:server-signature server-signature :server-authentication authentication})) (throw (ex-info ":servo/connection authentication failed" {:client-initial-scram client-initial-scram :server-scram server-scram}))) (when on-disconnected (s/on-closed @tcp-connection on-disconnected)) (let [queries (atom {}) feeds (atom {}) connection {:server-version version :db-name db-name :db-term {:db (:query (->rt-query [[:db db-name]]))} :query-counter (atom (long 0)) :queries queries :feeds feeds :subscriptions (atom {}) :tcp-connection @tcp-connection :rql-connection (->rql-connection @tcp-connection) :response-buffer-size response-buffer-size :trace trace}] (gauge-fn ["servo" "queries" "active"] #(- (count @queries) (count @feeds))) (gauge-fn ["servo" "feeds" "active"] #(count @feeds)) (s/consume (partial handle-message connection) (:rql-connection connection)) (ensure-db connection db-name) (when (or await-ready (not-empty tables) (not-empty indices)) (await-tables-ready connection)) (doseq [table tables] (ensure-table connection table)) (doseq [[table index multi?] indices] (ensure-index connection table index :multi (boolean multi?))) connection)))) (defn disconnect [{:keys [queries feeds subscriptions rql-connection tcp-connection]}] (when rql-connection (s/close! rql-connection)) (when tcp-connection (s/close! tcp-connection)) nil) (defn on-disconnected [{:keys [tcp-connection]} f] (s/on-closed tcp-connection f)) (defonce ^:private var-counter (atom 0)) (defmacro func [params body] (let [vars (reduce (fn [params p] (assoc params p (swap! var-counter inc))) {} params)] `[:func [(into [:make-array] ~(mapv vars params)) (into [~(first body)] ~(mapv (fn [v] (if-let [vi (get vars v)] [10 [vi]] v)) (rest body)))]])) (defn run [{:keys [db-term queries] :as connection} query & {:keys [query-type] :or {query-type :start}}] (let [token (token connection) response-d (d/deferred) {:keys [response-fn query]} (->rt-query query)] (swap! queries assoc token {:query query :response-d response-d :response-fn response-fn}) (when-not @(send connection token [(get request-types query-type) query db-term]) (swap! queries dissoc token) (throw (ex-info ":servo/connection send failed" {:connection connection :query query}))) response-d)) (defn subscribe [{:keys [feeds subscriptions] :as connection} query] (when (some #(= :changes (first %)) query) (throw (ex-info ":servo/connection subscribe query should not include :changes" {:query query}))) (let [feed @(run connection (concat query [[:changes {:squash true :include-initial true :include-types true :include-states true}]])) token (get-in @feeds [feed :token]) single (= :atom-feed (get-in @feeds [feed :type])) value-ref (signal (if single nil [])) initial-value (atom (if single nil []))] (swap! subscriptions assoc value-ref feed) (s/consume (fn [change] (try (cond (and (= "state" (:type change)) (= "initializing" (:state change))) nil (and (= "state" (:type change)) (= "ready" (:state change))) (do (alter! value-ref (constantly @initial-value)) (reset! initial-value nil)) (= "initial" (:type change)) (if single (reset! initial-value (:new-val change)) (swap! initial-value conj (:new-val change))) (= "uninitial" (:type change)) (if single (reset! initial-value nil) (swap! initial-value (fn [value] (let [id (get-in change [:old-val :id])] (->> value (remove #(= (:id %) id)) vec))))) (= "add" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) #(conj % (:new-val change)))) (= "change" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) (let [id (get-in change [:new-val :id])] (partial mapv #(if (= (:id %) id) (:new-val change) %))))) (= "remove" (:type change)) (alter! value-ref (if single (constantly nil) (let [id (get-in change [:old-val :id])] (comp vec (partial remove #(= (:id %) id)))))) :else (log/warn ":servo/connection unknown change type" query change)) (catch Exception e (log/error ":servo/connection change error" e)))) feed) value-ref)) (def ->seq s/stream->seq) (defn dispose [{:keys [feeds subscriptions] :as connection} value-ref] (locking connection (if-let [feed (get @subscriptions value-ref)] (when-let [token (get-in @feeds [feed :token])] (send connection (get-in @feeds [feed :token]) [(get request-types :stop)]) (swap! feeds dissoc feed) (swap! subscriptions dissoc value-ref)) (log/warn (ex-info ":servo.connection/dispose unknown subscription" {:signal (hash value-ref)})))) nil) (defn noreply-wait [connection] (run connection nil :query-type :noreply-wait)) (defn server-info [connection] (run connection nil :query-type :server-info)) (defn ensure-table [connection table-name] (let [table-list (set @(run connection [[:table-list]]))] (when-not (get table-list table-name) @(run connection [[:table-create table-name]])))) (defn ensure-index [connection table-name index-name & {:as options}] (let [index-list (set @(run connection [[:table table-name] [:index-list]]))] (when-not (get index-list index-name) @(run connection [[:table table-name] (cond-> [:index-create index-name] (not-empty options) (conj options))])))) ;;; Private (def ^:private json-mapper (json/object-mapper {:encode-key-fn (comp underscore name) :decode-key-fn (comp keyword hyphenate)})) (defn- token [{:keys [query-counter]}] (swap! query-counter inc)) (def ^:private rql-protocol (gloss/compile-frame [:int64-be (gloss/finite-frame :int32-le (gloss/string :utf-8))] (fn [[token query]] [token (json/write-value-as-string query json-mapper)]) (fn [[token query-str]] [token (json/read-value query-str json-mapper)]))) (defn- ->rql-connection [tcp-connection] (let [out (s/stream)] (s/connect (s/map (partial gloss-io/encode rql-protocol) out) tcp-connection) (s/splice out (gloss-io/decode-stream tcp-connection rql-protocol)))) (defn- send [{:keys [rql-connection trace]} token query] (when trace (log/debug (format ">> 0x%04x" token) (pr-str query))) (when token (s/put! rql-connection [token query]))) (declare response-types response-note-types response-error-types) (defn- handle-message [{:keys [queries feeds response-buffer-size trace] :as connection} [token response]] (let [{:keys [r t e n]} response {:keys [query response-d response-fn]} (get @queries token) success #(when response-d (d/success! response-d %)) error #(when response-d (d/error! response-d %)) handle-seq (fn [& {:keys [close] :or {close false}}] (when-not (and (d/realized? response-d) (s/stream? @response-d)) (let [feed (s/stream response-buffer-size (map response-fn))] (swap! feeds assoc feed {:type (get response-note-types (first n)) :token token}) (success feed))) (s/put-all! @response-d r) (when (and response-d close) (s/close! @response-d)))] (when trace (log/debug (format "<< 0x%04x" token) (pr-str response))) (try (case (get response-types t) :success-atom (do (success (response-fn (first r))) (swap! queries dissoc token)) :success-sequence (do (handle-seq :close true) (swap! queries dissoc token)) :success-partial (do (handle-seq :close false) (send connection token [(get request-types :continue)])) :wait-complete (do (success (response-fn nil)) (swap! queries dissoc token)) :server-info (do (success (response-fn (first r))) (swap! queries dissoc token)) :client-error (do (error (ex-info ":servo/connection client-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :compile-error (do (error (ex-info ":servo/connection compile-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :runtime-error (do (error (ex-info ":servo/connection runtime-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token))) (catch Exception e (error (ex-info ":servo/connection response error" {:query query :token token :response response :error e})) (swap! queries dissoc token))))) (declare term-types response-types response-error-types ->rt ->rt-options ->rt-key ->rt-name ->rt-value rt-> rt-string-> rt-key-> rt-name-> rt-value->) (defn- ->rt-query-term [[id & parameters]] (merge {:id (get term-types id)} (let [nested-fields #(reduce merge ((fn xform [params] (map (fn [v] (cond (or (keyword? v) (string? v)) {(->rt-key v) true} (map? v) (->> (map (fn [[k v]] [(->rt-key k) (reduce merge (xform v))]) v) (into {})))) params)) parameters))] (case id :db-list {:response-fn (partial map rt-name->)} :db {:arguments [(->rt-name (first parameters))]} :db-create {:arguments [(->rt-name (first parameters))]} :table-list {:response-fn (partial map rt-name->)} :index-list {:response-fn (partial map rt-name->)} :table {:arguments [(->rt-name (first parameters))] :response-fn rt->} :table-create {:arguments [(->rt-name (first parameters))]} :table-drop {:arguments [(->rt-name (first parameters))]} :index-create {:arguments [(->rt-name (first parameters))] :options (->rt (second parameters))} :index-wait {:arguments [(->rt-name (first parameters))]} :index-rename {:arguments [map] ->rt-name parameters} :index-drop {:arguments [(->rt-name (first parameters))]} :get {:arguments [(->rt-value (first parameters))] :response-fn rt->} :get-all {:arguments (map ->rt-value (first parameters)) :options (when-let [index (second parameters)] {"index" (->rt-name (:index index))}) :response-fn rt->} :insert (let [[value options] parameters] {:arguments [(if (or (map? value) (not (coll? value))) (->rt value) [(get term-types :make-array) (map ->rt value)])] :options (->rt-options options)}) :update (let [[value options] parameters] {:arguments [(->rt value)] :options (->rt-options options)}) :filter (let [[value options] parameters] (merge (cond (map? value) {:arguments [(->rt value)]}) {:options options :response-fn rt->})) :between (let [[lower upper options] parameters] {:arguments (mapv ->rt-value [lower upper]) :options (when options {"index" (->rt-name (:index options))})}) :order-by (let [[param] parameters ->rt-sort #(if (and (vector? %) (#{:asc :desc} (first %))) (let [[order index] %] [(get term-types order) [(->rt-name index)]]) (->rt-name %))] (if (map? param) (let [{:keys [index]} param] {:options {"index" (->rt-sort index)}}) {:arguments [(->rt-sort param)]})) :get-field {:arguments [(->rt-name (first parameters))]} :pluck {:arguments [(nested-fields)]} :with-fields {:arguments [(nested-fields)]} :without {:arguments [(nested-fields)]} :contains {:arguments [(first (->rt-value (first parameters)))]} :nth {:arguments [(first parameters)]} ;;:pred (pred (first parameters)) :distinct (when-some [index (first parameters)] {:options {"index" (->rt-name index)}}) :slice (let [[start opt1 opt2] parameters [end opts] (if (map? opt1) [nil opt1] [opt1 opt2])] {:arguments (vec (concat [start] (when end [end]))) :options (let [{:keys [left-bound right-bound]} opts] (merge (when left-bound {"left_bound" (->rt-name left-bound)}) (when right-bound {"right_bound" (->rt-name right-bound)})))}) :during (let [[start end] parameters] {:arguments [[(->rt-value start) (->rt-value end)]]}) ;; :func (let [[params body] (first parameters)] ;; [(->rt-query-term params) (->rt-query-term body)]) :changes {:options (map-keys (comp underscore name) (first parameters)) :response-fn #(cond-> % (:new-val %) (update :new-val rt->) (:old-val %) (update :old-val rt->))} {:arguments parameters})))) (defn- ->rt-query [query] {:query (reduce (fn [query term] (let [{:keys [id arguments options]} (->rt-query-term term)] (remove nil? [id (cond->> arguments query (cons query) true (remove nil?)) options]))) nil query) :response-fn (or (->> (map (comp :response-fn ->rt-query-term) query) (remove nil?) last) rt->)}) (defn- xform-map [m kf vf] (into {} (map (fn [[k v]] [(kf k) (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (vf v) (and (map? v) (= "TIME" (get v :$reql-type$))) (vf v) (instance? DateTime v) (vf v) (map? v) (xform-map v kf vf) :else (vf v))]) m))) (defn- ->rt-name [s] (underscore (str (when (keyword? s) (when-let [ns (namespace s)] (str ns "/"))) (name s)))) (defn- rt-name-> [s] (keyword (hyphenate s))) (defn- ->rt-key [k] (cond (keyword? k) (->rt-name k) (string? k) (str "servo/str=" (->rt-name k)) (double? k) (str "servo/double=" (str k)) (int? k) (str "servo/long=" (str k)) :else (throw (ex-info ":servo/connection unsupported type for key" {:key k})))) (defn namespaced-string [k] (if (keyword? k) (if-let [ns (namespace k)] (str ns "/" (name k)) (name k)) k)) (defn- rt-key-> [k] (let [k (namespaced-string k) coerced (rt-string-> k)] (if (= k coerced) (keyword (hyphenate k)) coerced))) (defn- ->rt-value [v] (cond (keyword? v) (str "servo/keyword=" (->rt-name v)) (instance? DateTime v) {"$reql_type$" "TIME" "epoch_time" (double (/ (t/into :long v) 1000)) "timezone" "+00:00"} (or (vector? v) (seq? v)) [(get term-types :make-array) (map ->rt v)] :else v)) (defn- rt-value-> [v] (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (t/from :long (* 1000 (get v "epoch_time"))) (and (map? v) (= "TIME" (get v :$reql-type$))) (t/from :long (* 1000 (get v :epoch-time))) (or (vector? v) (seq? v)) (into (empty v) (map rt-> v)) (string? v) (rt-string-> v) :else v)) (defn- rt-string-> [s] (let [[_ type-fn value-str] (re-find #"^servo/(.*)=(.*)$" s)] (if (and type-fn value-str) ((case type-fn "keyword" (comp keyword hyphenate) "str" str "double" string->double "long" string->long) value-str) s))) (defn- ->rt [v] (cond (instance? DateTime v) (->rt-value v) (or (seq? v) (vector? v)) [(get term-types :make-array) (map ->rt v)] (map? v) (xform-map v ->rt-key ->rt-value) :else (->rt-value v))) (defn- ->rt-options [options] (->> options (map-vals (fn [option] (if (keyword? option) (name option) option))) ->rt)) (defn- rt-> [m] (cond (and (map? m) (= "TIME" (get m "$reql_type$"))) (rt-value-> m) (and (map? m) (= "TIME" (get m :$reql-type$))) (rt-value-> m) (map? m) (not-empty (xform-map m rt-key-> rt-value->)) :else (rt-value-> m))) (defn- ensure-db [connection db-name] (when-not ((set @(run connection [[:db-list]])) (rt-name-> db-name)) @(run connection [[:db-create (->rt-name db-name)]]))) (defn- await-tables-ready [{:keys [trace] :as connection}] (let [table-list @(run connection [[:table-list]]) await-tables-ready (fn [] (->> table-list (map (fn [table] @(run connection [[:table table] [:status]]))) (filter (comp :all-replicas-ready :status)) count))] (loop [] (let [ready-count (await-tables-ready)] (when (< ready-count (count table-list)) (when trace (log/debug (format ":servo/connection %s/%s tables ready." ready-count (count table-list)))) (Thread/sleep 1000) (recur)))) (when trace (log/debug ":servo/connection all tables ready")))) (def ^:private request-types {:start 1 :continue 2 :stop 3 :noreply-wait 4 :server-info 5}) (def ^:private response-types {1 :success-atom 2 :success-sequence 3 :success-partial 4 :wait-complete 5 :server-info 16 :client-error 17 :compile-error 18 :runtime-error}) (def ^:private response-error-types {1000000 :internal 2000000 :resource-limit 3000000 :query-logic 3100000 :non-existence 4100000 :op-failed 4200000 :op-indeterminate 5000000 :user 6000000 :permission-error}) (def ^:private response-note-types {1 :sequence-feed 2 :atom-feed 3 :order-by-limit-feed 4 :unioned-feed 5 :includes-states}) (def ^:private term-types {:datum 1 :make-array 2 :make-obj 3 :javascript 11 :uuid 169 :http 153 :error 12 :implicit-var 13 :db 14 :table 15 :get 16 :get-all 78 :eq 17 :ne 18 :lt 19 :le 20 :gt 21 :ge 22 :not 23 :add 24 :sub 25 :mul 26 :div 27 :mod 28 :floor 183 :ceil 184 :round 185 :append 29 :prepend 80 :difference 95 :set-insert 88 :set-intersection 89 :set-union 90 :set-difference 91 :slice 30 :skip 70 :limit 71 :offsets-of 87 :contains 93 :get-field 31 :keys 94 :values 186 :object 143 :has-fields 32 :with-fields 96 :pluck 33 :without 34 :merge 35 :between-deprecated 36 :between 182 :reduce 37 :map 38 :fold 187 :filter 39 :concat-map 40 :order-by 41 :distinct 42 :count 43 :is-empty 86 :union 44 :nth 45 :bracket 170 :inner-join 48 :outer-join 49 :eq-join 50 :zip 72 :range 173 :insert-at 82 :delete-at 83 :change-at 84 :splice-at 85 :coerce-to 51 :type-of 52 :update 53 :delete 54 :replace 55 :insert 56 :db-create 57 :db-drop 58 :db-list 59 :table-create 60 :table-drop 61 :table-list 62 :config 174 :status 175 :wait 177 :reconfigure 176 :rebalance 179 :sync 138 :grant 188 :index-create 75 :index-drop 76 :index-list 77 :index-status 139 :index-wait 140 :index-rename 156 :set-write-hook 189 :get-write-hook 190 :funcall 64 :branch 65 :or 66 :and 67 :for-each 68 :func 69 :asc 73 :desc 74 :info 79 :match 97 :upcase 141 :downcase 142 :sample 81 :default 92 :json 98 :iso8601 99 :to-iso8601 100 :epoch-time 101 :to-epoch-time 102 :now 103 :in-timezone 104 :during 105 :date 106 :time-of-day 126 :timezone 127 :year 128 :month 129 :day 130 :day-of-week 131 :day-of-year 132 :hours 133 :minutes 134 :seconds 135 :time 136 :monday 107 :tuesday 108 :wednesday 109 :thursday 110 :friday 111 :saturday 112 :sunday 113 :january 114 :february 115 :march 116 :april 117 :may 118 :june 119 :july 120 :august 121 :september 122 :october 123 :november 124 :december 125 :literal 137 :group 144 :sum 145 :avg 146 :min 147 :max 148 :split 149 :ungroup 150 :random 151 :changes 152 :arguments 154 :binary 155 :geojson 157 :to-geojson 158 :point 159 :line 160 :polygon 161 :distance 162 :intersects 163 :includes 164 :circle 165 :get-intersecting 166 :fill 167 :get-nearest 168 :polygon-sub 171 :to-json-string 172 :minval 180 :maxval 181 :bit-and 191 :bit-or 192 :bit-xor 193 :bit-not 194 :bit-sal 195 :bit-sar 196})
11333
;; Copyright (c) 7theta. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; MIT License (https://opensource.org/licenses/MIT) which can also be ;; found in the LICENSE file at the root of this distribution. ;; ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any others, from this software. (ns servo.connection (:refer-clojure :exclude [send]) (:require [servo.util.scram :as scram] [signum.signal :refer [signal alter!]] [tempus.core :as t] [aleph.tcp :as tcp] [manifold.stream :as s] [manifold.deferred :as d] [gloss.core :as gloss] [gloss.io :as gloss-io] [byte-streams.core :as bs] [jsonista.core :as json] [inflections.core :refer [hyphenate underscore]] [utilis.map :refer [map-keys map-vals]] [utilis.types.number :refer [string->long string->double]] [clojure.string :as st] [integrant.core :as ig] [metrics.gauges :refer [gauge-fn]] [clojure.tools.logging :as log]) (:import [tempus.core DateTime] [java.nio ByteBuffer ByteOrder] [java.io ByteArrayOutputStream])) (declare connect disconnect ->rql-connection await-tables-ready ensure-db ensure-table ensure-index json-mapper ->rt-name ->rt-query ->rt-query-term send handle-message token request-types) (defmethod ig/init-key :servo/connection [_ options] (connect options)) (defmethod ig/halt-key! :servo/connection [_ connection] (try (disconnect connection) (catch Exception e (log/error ":servo/connection shutdown exception" e)))) (defn connect [{:keys [db-server db-name await-ready trace response-buffer-size on-disconnected tables indices] :or {await-ready true response-buffer-size 1000}}] (when trace (log/debug "servo/connection connect" (pr-str db-server))) (let [{:keys [host port username password] :or {host "localhost" port 28015 username "admin" password ""}} db-server tcp-connection (tcp/client {:host host :port port})] @(s/put! @tcp-connection (byte-array [0xc3 0xbd 0xc2 0x34])) (let [version (try (:server_version (-> @(s/take! @tcp-connection) bs/to-string (json/read-value json/keyword-keys-object-mapper))) (catch Exception _ (throw (ex-info ":servo/connection initial handshake failed" {:db-server db-server :db-name db-name})))) send (fn [message] (s/put! @tcp-connection (let [json-str (json/write-value-as-string message json-mapper)] ;; Rethink requires JSON strings to be "null terminated" (byte-array (inc (count json-str)) (map int json-str))))) recv #(json/read-value (bs/to-string @(s/take! @tcp-connection)) json-mapper) {:keys [message client-initial-scram]} (scram/initial-proposal {:username username}) _ (send message) {:keys [server-scram server-authentication]} (scram/server-challenge {:client-initial-scram client-initial-scram} (recv)) {:keys [message server-signature]} (scram/authentication-request {:client-initial-scram client-initial-scram :server-authentication server-authentication :server-scram server-scram :password <PASSWORD>}) _ (send message) {:keys [authentication success]} (recv)] (when-not (and success (scram/validate-server {:server-signature server-signature :server-authentication authentication})) (throw (ex-info ":servo/connection authentication failed" {:client-initial-scram client-initial-scram :server-scram server-scram}))) (when on-disconnected (s/on-closed @tcp-connection on-disconnected)) (let [queries (atom {}) feeds (atom {}) connection {:server-version version :db-name db-name :db-term {:db (:query (->rt-query [[:db db-name]]))} :query-counter (atom (long 0)) :queries queries :feeds feeds :subscriptions (atom {}) :tcp-connection @tcp-connection :rql-connection (->rql-connection @tcp-connection) :response-buffer-size response-buffer-size :trace trace}] (gauge-fn ["servo" "queries" "active"] #(- (count @queries) (count @feeds))) (gauge-fn ["servo" "feeds" "active"] #(count @feeds)) (s/consume (partial handle-message connection) (:rql-connection connection)) (ensure-db connection db-name) (when (or await-ready (not-empty tables) (not-empty indices)) (await-tables-ready connection)) (doseq [table tables] (ensure-table connection table)) (doseq [[table index multi?] indices] (ensure-index connection table index :multi (boolean multi?))) connection)))) (defn disconnect [{:keys [queries feeds subscriptions rql-connection tcp-connection]}] (when rql-connection (s/close! rql-connection)) (when tcp-connection (s/close! tcp-connection)) nil) (defn on-disconnected [{:keys [tcp-connection]} f] (s/on-closed tcp-connection f)) (defonce ^:private var-counter (atom 0)) (defmacro func [params body] (let [vars (reduce (fn [params p] (assoc params p (swap! var-counter inc))) {} params)] `[:func [(into [:make-array] ~(mapv vars params)) (into [~(first body)] ~(mapv (fn [v] (if-let [vi (get vars v)] [10 [vi]] v)) (rest body)))]])) (defn run [{:keys [db-term queries] :as connection} query & {:keys [query-type] :or {query-type :start}}] (let [token (token connection) response-d (d/deferred) {:keys [response-fn query]} (->rt-query query)] (swap! queries assoc token {:query query :response-d response-d :response-fn response-fn}) (when-not @(send connection token [(get request-types query-type) query db-term]) (swap! queries dissoc token) (throw (ex-info ":servo/connection send failed" {:connection connection :query query}))) response-d)) (defn subscribe [{:keys [feeds subscriptions] :as connection} query] (when (some #(= :changes (first %)) query) (throw (ex-info ":servo/connection subscribe query should not include :changes" {:query query}))) (let [feed @(run connection (concat query [[:changes {:squash true :include-initial true :include-types true :include-states true}]])) token (get-in @feeds [feed :token]) single (= :atom-feed (get-in @feeds [feed :type])) value-ref (signal (if single nil [])) initial-value (atom (if single nil []))] (swap! subscriptions assoc value-ref feed) (s/consume (fn [change] (try (cond (and (= "state" (:type change)) (= "initializing" (:state change))) nil (and (= "state" (:type change)) (= "ready" (:state change))) (do (alter! value-ref (constantly @initial-value)) (reset! initial-value nil)) (= "initial" (:type change)) (if single (reset! initial-value (:new-val change)) (swap! initial-value conj (:new-val change))) (= "uninitial" (:type change)) (if single (reset! initial-value nil) (swap! initial-value (fn [value] (let [id (get-in change [:old-val :id])] (->> value (remove #(= (:id %) id)) vec))))) (= "add" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) #(conj % (:new-val change)))) (= "change" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) (let [id (get-in change [:new-val :id])] (partial mapv #(if (= (:id %) id) (:new-val change) %))))) (= "remove" (:type change)) (alter! value-ref (if single (constantly nil) (let [id (get-in change [:old-val :id])] (comp vec (partial remove #(= (:id %) id)))))) :else (log/warn ":servo/connection unknown change type" query change)) (catch Exception e (log/error ":servo/connection change error" e)))) feed) value-ref)) (def ->seq s/stream->seq) (defn dispose [{:keys [feeds subscriptions] :as connection} value-ref] (locking connection (if-let [feed (get @subscriptions value-ref)] (when-let [token (get-in @feeds [feed :token])] (send connection (get-in @feeds [feed :token]) [(get request-types :stop)]) (swap! feeds dissoc feed) (swap! subscriptions dissoc value-ref)) (log/warn (ex-info ":servo.connection/dispose unknown subscription" {:signal (hash value-ref)})))) nil) (defn noreply-wait [connection] (run connection nil :query-type :noreply-wait)) (defn server-info [connection] (run connection nil :query-type :server-info)) (defn ensure-table [connection table-name] (let [table-list (set @(run connection [[:table-list]]))] (when-not (get table-list table-name) @(run connection [[:table-create table-name]])))) (defn ensure-index [connection table-name index-name & {:as options}] (let [index-list (set @(run connection [[:table table-name] [:index-list]]))] (when-not (get index-list index-name) @(run connection [[:table table-name] (cond-> [:index-create index-name] (not-empty options) (conj options))])))) ;;; Private (def ^:private json-mapper (json/object-mapper {:encode-key-fn (comp underscore name) :decode-key-fn (comp keyword hyphenate)})) (defn- token [{:keys [query-counter]}] (swap! query-counter inc)) (def ^:private rql-protocol (gloss/compile-frame [:int64-be (gloss/finite-frame :int32-le (gloss/string :utf-8))] (fn [[token query]] [token (json/write-value-as-string query json-mapper)]) (fn [[token query-str]] [token (json/read-value query-str json-mapper)]))) (defn- ->rql-connection [tcp-connection] (let [out (s/stream)] (s/connect (s/map (partial gloss-io/encode rql-protocol) out) tcp-connection) (s/splice out (gloss-io/decode-stream tcp-connection rql-protocol)))) (defn- send [{:keys [rql-connection trace]} token query] (when trace (log/debug (format ">> 0x%04x" token) (pr-str query))) (when token (s/put! rql-connection [token query]))) (declare response-types response-note-types response-error-types) (defn- handle-message [{:keys [queries feeds response-buffer-size trace] :as connection} [token response]] (let [{:keys [r t e n]} response {:keys [query response-d response-fn]} (get @queries token) success #(when response-d (d/success! response-d %)) error #(when response-d (d/error! response-d %)) handle-seq (fn [& {:keys [close] :or {close false}}] (when-not (and (d/realized? response-d) (s/stream? @response-d)) (let [feed (s/stream response-buffer-size (map response-fn))] (swap! feeds assoc feed {:type (get response-note-types (first n)) :token token}) (success feed))) (s/put-all! @response-d r) (when (and response-d close) (s/close! @response-d)))] (when trace (log/debug (format "<< 0x%04x" token) (pr-str response))) (try (case (get response-types t) :success-atom (do (success (response-fn (first r))) (swap! queries dissoc token)) :success-sequence (do (handle-seq :close true) (swap! queries dissoc token)) :success-partial (do (handle-seq :close false) (send connection token [(get request-types :continue)])) :wait-complete (do (success (response-fn nil)) (swap! queries dissoc token)) :server-info (do (success (response-fn (first r))) (swap! queries dissoc token)) :client-error (do (error (ex-info ":servo/connection client-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :compile-error (do (error (ex-info ":servo/connection compile-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :runtime-error (do (error (ex-info ":servo/connection runtime-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token))) (catch Exception e (error (ex-info ":servo/connection response error" {:query query :token token :response response :error e})) (swap! queries dissoc token))))) (declare term-types response-types response-error-types ->rt ->rt-options ->rt-key ->rt-name ->rt-value rt-> rt-string-> rt-key-> rt-name-> rt-value->) (defn- ->rt-query-term [[id & parameters]] (merge {:id (get term-types id)} (let [nested-fields #(reduce merge ((fn xform [params] (map (fn [v] (cond (or (keyword? v) (string? v)) {(->rt-key v) true} (map? v) (->> (map (fn [[k v]] [(->rt-key k) (reduce merge (xform v))]) v) (into {})))) params)) parameters))] (case id :db-list {:response-fn (partial map rt-name->)} :db {:arguments [(->rt-name (first parameters))]} :db-create {:arguments [(->rt-name (first parameters))]} :table-list {:response-fn (partial map rt-name->)} :index-list {:response-fn (partial map rt-name->)} :table {:arguments [(->rt-name (first parameters))] :response-fn rt->} :table-create {:arguments [(->rt-name (first parameters))]} :table-drop {:arguments [(->rt-name (first parameters))]} :index-create {:arguments [(->rt-name (first parameters))] :options (->rt (second parameters))} :index-wait {:arguments [(->rt-name (first parameters))]} :index-rename {:arguments [map] ->rt-name parameters} :index-drop {:arguments [(->rt-name (first parameters))]} :get {:arguments [(->rt-value (first parameters))] :response-fn rt->} :get-all {:arguments (map ->rt-value (first parameters)) :options (when-let [index (second parameters)] {"index" (->rt-name (:index index))}) :response-fn rt->} :insert (let [[value options] parameters] {:arguments [(if (or (map? value) (not (coll? value))) (->rt value) [(get term-types :make-array) (map ->rt value)])] :options (->rt-options options)}) :update (let [[value options] parameters] {:arguments [(->rt value)] :options (->rt-options options)}) :filter (let [[value options] parameters] (merge (cond (map? value) {:arguments [(->rt value)]}) {:options options :response-fn rt->})) :between (let [[lower upper options] parameters] {:arguments (mapv ->rt-value [lower upper]) :options (when options {"index" (->rt-name (:index options))})}) :order-by (let [[param] parameters ->rt-sort #(if (and (vector? %) (#{:asc :desc} (first %))) (let [[order index] %] [(get term-types order) [(->rt-name index)]]) (->rt-name %))] (if (map? param) (let [{:keys [index]} param] {:options {"index" (->rt-sort index)}}) {:arguments [(->rt-sort param)]})) :get-field {:arguments [(->rt-name (first parameters))]} :pluck {:arguments [(nested-fields)]} :with-fields {:arguments [(nested-fields)]} :without {:arguments [(nested-fields)]} :contains {:arguments [(first (->rt-value (first parameters)))]} :nth {:arguments [(first parameters)]} ;;:pred (pred (first parameters)) :distinct (when-some [index (first parameters)] {:options {"index" (->rt-name index)}}) :slice (let [[start opt1 opt2] parameters [end opts] (if (map? opt1) [nil opt1] [opt1 opt2])] {:arguments (vec (concat [start] (when end [end]))) :options (let [{:keys [left-bound right-bound]} opts] (merge (when left-bound {"left_bound" (->rt-name left-bound)}) (when right-bound {"right_bound" (->rt-name right-bound)})))}) :during (let [[start end] parameters] {:arguments [[(->rt-value start) (->rt-value end)]]}) ;; :func (let [[params body] (first parameters)] ;; [(->rt-query-term params) (->rt-query-term body)]) :changes {:options (map-keys (comp underscore name) (first parameters)) :response-fn #(cond-> % (:new-val %) (update :new-val rt->) (:old-val %) (update :old-val rt->))} {:arguments parameters})))) (defn- ->rt-query [query] {:query (reduce (fn [query term] (let [{:keys [id arguments options]} (->rt-query-term term)] (remove nil? [id (cond->> arguments query (cons query) true (remove nil?)) options]))) nil query) :response-fn (or (->> (map (comp :response-fn ->rt-query-term) query) (remove nil?) last) rt->)}) (defn- xform-map [m kf vf] (into {} (map (fn [[k v]] [(kf k) (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (vf v) (and (map? v) (= "TIME" (get v :$reql-type$))) (vf v) (instance? DateTime v) (vf v) (map? v) (xform-map v kf vf) :else (vf v))]) m))) (defn- ->rt-name [s] (underscore (str (when (keyword? s) (when-let [ns (namespace s)] (str ns "/"))) (name s)))) (defn- rt-name-> [s] (keyword (hyphenate s))) (defn- ->rt-key [k] (cond (keyword? k) (->rt-name k) (string? k) (str "servo/str=" (->rt-name k)) (double? k) (str "servo/double=" (str k)) (int? k) (str "servo/long=" (str k)) :else (throw (ex-info ":servo/connection unsupported type for key" {:key k})))) (defn namespaced-string [k] (if (keyword? k) (if-let [ns (namespace k)] (str ns "/" (name k)) (name k)) k)) (defn- rt-key-> [k] (let [k (namespaced-string k) coerced (rt-string-> k)] (if (= k coerced) (keyword (hyphenate k)) coerced))) (defn- ->rt-value [v] (cond (keyword? v) (str "servo/keyword=" (->rt-name v)) (instance? DateTime v) {"$reql_type$" "TIME" "epoch_time" (double (/ (t/into :long v) 1000)) "timezone" "+00:00"} (or (vector? v) (seq? v)) [(get term-types :make-array) (map ->rt v)] :else v)) (defn- rt-value-> [v] (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (t/from :long (* 1000 (get v "epoch_time"))) (and (map? v) (= "TIME" (get v :$reql-type$))) (t/from :long (* 1000 (get v :epoch-time))) (or (vector? v) (seq? v)) (into (empty v) (map rt-> v)) (string? v) (rt-string-> v) :else v)) (defn- rt-string-> [s] (let [[_ type-fn value-str] (re-find #"^servo/(.*)=(.*)$" s)] (if (and type-fn value-str) ((case type-fn "keyword" (comp keyword hyphenate) "str" str "double" string->double "long" string->long) value-str) s))) (defn- ->rt [v] (cond (instance? DateTime v) (->rt-value v) (or (seq? v) (vector? v)) [(get term-types :make-array) (map ->rt v)] (map? v) (xform-map v ->rt-key ->rt-value) :else (->rt-value v))) (defn- ->rt-options [options] (->> options (map-vals (fn [option] (if (keyword? option) (name option) option))) ->rt)) (defn- rt-> [m] (cond (and (map? m) (= "TIME" (get m "$reql_type$"))) (rt-value-> m) (and (map? m) (= "TIME" (get m :$reql-type$))) (rt-value-> m) (map? m) (not-empty (xform-map m rt-key-> rt-value->)) :else (rt-value-> m))) (defn- ensure-db [connection db-name] (when-not ((set @(run connection [[:db-list]])) (rt-name-> db-name)) @(run connection [[:db-create (->rt-name db-name)]]))) (defn- await-tables-ready [{:keys [trace] :as connection}] (let [table-list @(run connection [[:table-list]]) await-tables-ready (fn [] (->> table-list (map (fn [table] @(run connection [[:table table] [:status]]))) (filter (comp :all-replicas-ready :status)) count))] (loop [] (let [ready-count (await-tables-ready)] (when (< ready-count (count table-list)) (when trace (log/debug (format ":servo/connection %s/%s tables ready." ready-count (count table-list)))) (Thread/sleep 1000) (recur)))) (when trace (log/debug ":servo/connection all tables ready")))) (def ^:private request-types {:start 1 :continue 2 :stop 3 :noreply-wait 4 :server-info 5}) (def ^:private response-types {1 :success-atom 2 :success-sequence 3 :success-partial 4 :wait-complete 5 :server-info 16 :client-error 17 :compile-error 18 :runtime-error}) (def ^:private response-error-types {1000000 :internal 2000000 :resource-limit 3000000 :query-logic 3100000 :non-existence 4100000 :op-failed 4200000 :op-indeterminate 5000000 :user 6000000 :permission-error}) (def ^:private response-note-types {1 :sequence-feed 2 :atom-feed 3 :order-by-limit-feed 4 :unioned-feed 5 :includes-states}) (def ^:private term-types {:datum 1 :make-array 2 :make-obj 3 :javascript 11 :uuid 169 :http 153 :error 12 :implicit-var 13 :db 14 :table 15 :get 16 :get-all 78 :eq 17 :ne 18 :lt 19 :le 20 :gt 21 :ge 22 :not 23 :add 24 :sub 25 :mul 26 :div 27 :mod 28 :floor 183 :ceil 184 :round 185 :append 29 :prepend 80 :difference 95 :set-insert 88 :set-intersection 89 :set-union 90 :set-difference 91 :slice 30 :skip 70 :limit 71 :offsets-of 87 :contains 93 :get-field 31 :keys 94 :values 186 :object 143 :has-fields 32 :with-fields 96 :pluck 33 :without 34 :merge 35 :between-deprecated 36 :between 182 :reduce 37 :map 38 :fold 187 :filter 39 :concat-map 40 :order-by 41 :distinct 42 :count 43 :is-empty 86 :union 44 :nth 45 :bracket 170 :inner-join 48 :outer-join 49 :eq-join 50 :zip 72 :range 173 :insert-at 82 :delete-at 83 :change-at 84 :splice-at 85 :coerce-to 51 :type-of 52 :update 53 :delete 54 :replace 55 :insert 56 :db-create 57 :db-drop 58 :db-list 59 :table-create 60 :table-drop 61 :table-list 62 :config 174 :status 175 :wait 177 :reconfigure 176 :rebalance 179 :sync 138 :grant 188 :index-create 75 :index-drop 76 :index-list 77 :index-status 139 :index-wait 140 :index-rename 156 :set-write-hook 189 :get-write-hook 190 :funcall 64 :branch 65 :or 66 :and 67 :for-each 68 :func 69 :asc 73 :desc 74 :info 79 :match 97 :upcase 141 :downcase 142 :sample 81 :default 92 :json 98 :iso8601 99 :to-iso8601 100 :epoch-time 101 :to-epoch-time 102 :now 103 :in-timezone 104 :during 105 :date 106 :time-of-day 126 :timezone 127 :year 128 :month 129 :day 130 :day-of-week 131 :day-of-year 132 :hours 133 :minutes 134 :seconds 135 :time 136 :monday 107 :tuesday 108 :wednesday 109 :thursday 110 :friday 111 :saturday 112 :sunday 113 :january 114 :february 115 :march 116 :april 117 :may 118 :june 119 :july 120 :august 121 :september 122 :october 123 :november 124 :december 125 :literal 137 :group 144 :sum 145 :avg 146 :min 147 :max 148 :split 149 :ungroup 150 :random 151 :changes 152 :arguments 154 :binary 155 :geojson 157 :to-geojson 158 :point 159 :line 160 :polygon 161 :distance 162 :intersects 163 :includes 164 :circle 165 :get-intersecting 166 :fill 167 :get-nearest 168 :polygon-sub 171 :to-json-string 172 :minval 180 :maxval 181 :bit-and 191 :bit-or 192 :bit-xor 193 :bit-not 194 :bit-sal 195 :bit-sar 196})
true
;; Copyright (c) 7theta. All rights reserved. ;; The use and distribution terms for this software are covered by the ;; MIT License (https://opensource.org/licenses/MIT) which can also be ;; found in the LICENSE file at the root of this distribution. ;; ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any others, from this software. (ns servo.connection (:refer-clojure :exclude [send]) (:require [servo.util.scram :as scram] [signum.signal :refer [signal alter!]] [tempus.core :as t] [aleph.tcp :as tcp] [manifold.stream :as s] [manifold.deferred :as d] [gloss.core :as gloss] [gloss.io :as gloss-io] [byte-streams.core :as bs] [jsonista.core :as json] [inflections.core :refer [hyphenate underscore]] [utilis.map :refer [map-keys map-vals]] [utilis.types.number :refer [string->long string->double]] [clojure.string :as st] [integrant.core :as ig] [metrics.gauges :refer [gauge-fn]] [clojure.tools.logging :as log]) (:import [tempus.core DateTime] [java.nio ByteBuffer ByteOrder] [java.io ByteArrayOutputStream])) (declare connect disconnect ->rql-connection await-tables-ready ensure-db ensure-table ensure-index json-mapper ->rt-name ->rt-query ->rt-query-term send handle-message token request-types) (defmethod ig/init-key :servo/connection [_ options] (connect options)) (defmethod ig/halt-key! :servo/connection [_ connection] (try (disconnect connection) (catch Exception e (log/error ":servo/connection shutdown exception" e)))) (defn connect [{:keys [db-server db-name await-ready trace response-buffer-size on-disconnected tables indices] :or {await-ready true response-buffer-size 1000}}] (when trace (log/debug "servo/connection connect" (pr-str db-server))) (let [{:keys [host port username password] :or {host "localhost" port 28015 username "admin" password ""}} db-server tcp-connection (tcp/client {:host host :port port})] @(s/put! @tcp-connection (byte-array [0xc3 0xbd 0xc2 0x34])) (let [version (try (:server_version (-> @(s/take! @tcp-connection) bs/to-string (json/read-value json/keyword-keys-object-mapper))) (catch Exception _ (throw (ex-info ":servo/connection initial handshake failed" {:db-server db-server :db-name db-name})))) send (fn [message] (s/put! @tcp-connection (let [json-str (json/write-value-as-string message json-mapper)] ;; Rethink requires JSON strings to be "null terminated" (byte-array (inc (count json-str)) (map int json-str))))) recv #(json/read-value (bs/to-string @(s/take! @tcp-connection)) json-mapper) {:keys [message client-initial-scram]} (scram/initial-proposal {:username username}) _ (send message) {:keys [server-scram server-authentication]} (scram/server-challenge {:client-initial-scram client-initial-scram} (recv)) {:keys [message server-signature]} (scram/authentication-request {:client-initial-scram client-initial-scram :server-authentication server-authentication :server-scram server-scram :password PI:PASSWORD:<PASSWORD>END_PI}) _ (send message) {:keys [authentication success]} (recv)] (when-not (and success (scram/validate-server {:server-signature server-signature :server-authentication authentication})) (throw (ex-info ":servo/connection authentication failed" {:client-initial-scram client-initial-scram :server-scram server-scram}))) (when on-disconnected (s/on-closed @tcp-connection on-disconnected)) (let [queries (atom {}) feeds (atom {}) connection {:server-version version :db-name db-name :db-term {:db (:query (->rt-query [[:db db-name]]))} :query-counter (atom (long 0)) :queries queries :feeds feeds :subscriptions (atom {}) :tcp-connection @tcp-connection :rql-connection (->rql-connection @tcp-connection) :response-buffer-size response-buffer-size :trace trace}] (gauge-fn ["servo" "queries" "active"] #(- (count @queries) (count @feeds))) (gauge-fn ["servo" "feeds" "active"] #(count @feeds)) (s/consume (partial handle-message connection) (:rql-connection connection)) (ensure-db connection db-name) (when (or await-ready (not-empty tables) (not-empty indices)) (await-tables-ready connection)) (doseq [table tables] (ensure-table connection table)) (doseq [[table index multi?] indices] (ensure-index connection table index :multi (boolean multi?))) connection)))) (defn disconnect [{:keys [queries feeds subscriptions rql-connection tcp-connection]}] (when rql-connection (s/close! rql-connection)) (when tcp-connection (s/close! tcp-connection)) nil) (defn on-disconnected [{:keys [tcp-connection]} f] (s/on-closed tcp-connection f)) (defonce ^:private var-counter (atom 0)) (defmacro func [params body] (let [vars (reduce (fn [params p] (assoc params p (swap! var-counter inc))) {} params)] `[:func [(into [:make-array] ~(mapv vars params)) (into [~(first body)] ~(mapv (fn [v] (if-let [vi (get vars v)] [10 [vi]] v)) (rest body)))]])) (defn run [{:keys [db-term queries] :as connection} query & {:keys [query-type] :or {query-type :start}}] (let [token (token connection) response-d (d/deferred) {:keys [response-fn query]} (->rt-query query)] (swap! queries assoc token {:query query :response-d response-d :response-fn response-fn}) (when-not @(send connection token [(get request-types query-type) query db-term]) (swap! queries dissoc token) (throw (ex-info ":servo/connection send failed" {:connection connection :query query}))) response-d)) (defn subscribe [{:keys [feeds subscriptions] :as connection} query] (when (some #(= :changes (first %)) query) (throw (ex-info ":servo/connection subscribe query should not include :changes" {:query query}))) (let [feed @(run connection (concat query [[:changes {:squash true :include-initial true :include-types true :include-states true}]])) token (get-in @feeds [feed :token]) single (= :atom-feed (get-in @feeds [feed :type])) value-ref (signal (if single nil [])) initial-value (atom (if single nil []))] (swap! subscriptions assoc value-ref feed) (s/consume (fn [change] (try (cond (and (= "state" (:type change)) (= "initializing" (:state change))) nil (and (= "state" (:type change)) (= "ready" (:state change))) (do (alter! value-ref (constantly @initial-value)) (reset! initial-value nil)) (= "initial" (:type change)) (if single (reset! initial-value (:new-val change)) (swap! initial-value conj (:new-val change))) (= "uninitial" (:type change)) (if single (reset! initial-value nil) (swap! initial-value (fn [value] (let [id (get-in change [:old-val :id])] (->> value (remove #(= (:id %) id)) vec))))) (= "add" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) #(conj % (:new-val change)))) (= "change" (:type change)) (alter! value-ref (if single (constantly (:new-val change)) (let [id (get-in change [:new-val :id])] (partial mapv #(if (= (:id %) id) (:new-val change) %))))) (= "remove" (:type change)) (alter! value-ref (if single (constantly nil) (let [id (get-in change [:old-val :id])] (comp vec (partial remove #(= (:id %) id)))))) :else (log/warn ":servo/connection unknown change type" query change)) (catch Exception e (log/error ":servo/connection change error" e)))) feed) value-ref)) (def ->seq s/stream->seq) (defn dispose [{:keys [feeds subscriptions] :as connection} value-ref] (locking connection (if-let [feed (get @subscriptions value-ref)] (when-let [token (get-in @feeds [feed :token])] (send connection (get-in @feeds [feed :token]) [(get request-types :stop)]) (swap! feeds dissoc feed) (swap! subscriptions dissoc value-ref)) (log/warn (ex-info ":servo.connection/dispose unknown subscription" {:signal (hash value-ref)})))) nil) (defn noreply-wait [connection] (run connection nil :query-type :noreply-wait)) (defn server-info [connection] (run connection nil :query-type :server-info)) (defn ensure-table [connection table-name] (let [table-list (set @(run connection [[:table-list]]))] (when-not (get table-list table-name) @(run connection [[:table-create table-name]])))) (defn ensure-index [connection table-name index-name & {:as options}] (let [index-list (set @(run connection [[:table table-name] [:index-list]]))] (when-not (get index-list index-name) @(run connection [[:table table-name] (cond-> [:index-create index-name] (not-empty options) (conj options))])))) ;;; Private (def ^:private json-mapper (json/object-mapper {:encode-key-fn (comp underscore name) :decode-key-fn (comp keyword hyphenate)})) (defn- token [{:keys [query-counter]}] (swap! query-counter inc)) (def ^:private rql-protocol (gloss/compile-frame [:int64-be (gloss/finite-frame :int32-le (gloss/string :utf-8))] (fn [[token query]] [token (json/write-value-as-string query json-mapper)]) (fn [[token query-str]] [token (json/read-value query-str json-mapper)]))) (defn- ->rql-connection [tcp-connection] (let [out (s/stream)] (s/connect (s/map (partial gloss-io/encode rql-protocol) out) tcp-connection) (s/splice out (gloss-io/decode-stream tcp-connection rql-protocol)))) (defn- send [{:keys [rql-connection trace]} token query] (when trace (log/debug (format ">> 0x%04x" token) (pr-str query))) (when token (s/put! rql-connection [token query]))) (declare response-types response-note-types response-error-types) (defn- handle-message [{:keys [queries feeds response-buffer-size trace] :as connection} [token response]] (let [{:keys [r t e n]} response {:keys [query response-d response-fn]} (get @queries token) success #(when response-d (d/success! response-d %)) error #(when response-d (d/error! response-d %)) handle-seq (fn [& {:keys [close] :or {close false}}] (when-not (and (d/realized? response-d) (s/stream? @response-d)) (let [feed (s/stream response-buffer-size (map response-fn))] (swap! feeds assoc feed {:type (get response-note-types (first n)) :token token}) (success feed))) (s/put-all! @response-d r) (when (and response-d close) (s/close! @response-d)))] (when trace (log/debug (format "<< 0x%04x" token) (pr-str response))) (try (case (get response-types t) :success-atom (do (success (response-fn (first r))) (swap! queries dissoc token)) :success-sequence (do (handle-seq :close true) (swap! queries dissoc token)) :success-partial (do (handle-seq :close false) (send connection token [(get request-types :continue)])) :wait-complete (do (success (response-fn nil)) (swap! queries dissoc token)) :server-info (do (success (response-fn (first r))) (swap! queries dissoc token)) :client-error (do (error (ex-info ":servo/connection client-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :compile-error (do (error (ex-info ":servo/connection compile-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token)) :runtime-error (do (error (ex-info ":servo/connection runtime-error" {:query query :error (get response-error-types e) :error-text (first r)})) (swap! queries dissoc token))) (catch Exception e (error (ex-info ":servo/connection response error" {:query query :token token :response response :error e})) (swap! queries dissoc token))))) (declare term-types response-types response-error-types ->rt ->rt-options ->rt-key ->rt-name ->rt-value rt-> rt-string-> rt-key-> rt-name-> rt-value->) (defn- ->rt-query-term [[id & parameters]] (merge {:id (get term-types id)} (let [nested-fields #(reduce merge ((fn xform [params] (map (fn [v] (cond (or (keyword? v) (string? v)) {(->rt-key v) true} (map? v) (->> (map (fn [[k v]] [(->rt-key k) (reduce merge (xform v))]) v) (into {})))) params)) parameters))] (case id :db-list {:response-fn (partial map rt-name->)} :db {:arguments [(->rt-name (first parameters))]} :db-create {:arguments [(->rt-name (first parameters))]} :table-list {:response-fn (partial map rt-name->)} :index-list {:response-fn (partial map rt-name->)} :table {:arguments [(->rt-name (first parameters))] :response-fn rt->} :table-create {:arguments [(->rt-name (first parameters))]} :table-drop {:arguments [(->rt-name (first parameters))]} :index-create {:arguments [(->rt-name (first parameters))] :options (->rt (second parameters))} :index-wait {:arguments [(->rt-name (first parameters))]} :index-rename {:arguments [map] ->rt-name parameters} :index-drop {:arguments [(->rt-name (first parameters))]} :get {:arguments [(->rt-value (first parameters))] :response-fn rt->} :get-all {:arguments (map ->rt-value (first parameters)) :options (when-let [index (second parameters)] {"index" (->rt-name (:index index))}) :response-fn rt->} :insert (let [[value options] parameters] {:arguments [(if (or (map? value) (not (coll? value))) (->rt value) [(get term-types :make-array) (map ->rt value)])] :options (->rt-options options)}) :update (let [[value options] parameters] {:arguments [(->rt value)] :options (->rt-options options)}) :filter (let [[value options] parameters] (merge (cond (map? value) {:arguments [(->rt value)]}) {:options options :response-fn rt->})) :between (let [[lower upper options] parameters] {:arguments (mapv ->rt-value [lower upper]) :options (when options {"index" (->rt-name (:index options))})}) :order-by (let [[param] parameters ->rt-sort #(if (and (vector? %) (#{:asc :desc} (first %))) (let [[order index] %] [(get term-types order) [(->rt-name index)]]) (->rt-name %))] (if (map? param) (let [{:keys [index]} param] {:options {"index" (->rt-sort index)}}) {:arguments [(->rt-sort param)]})) :get-field {:arguments [(->rt-name (first parameters))]} :pluck {:arguments [(nested-fields)]} :with-fields {:arguments [(nested-fields)]} :without {:arguments [(nested-fields)]} :contains {:arguments [(first (->rt-value (first parameters)))]} :nth {:arguments [(first parameters)]} ;;:pred (pred (first parameters)) :distinct (when-some [index (first parameters)] {:options {"index" (->rt-name index)}}) :slice (let [[start opt1 opt2] parameters [end opts] (if (map? opt1) [nil opt1] [opt1 opt2])] {:arguments (vec (concat [start] (when end [end]))) :options (let [{:keys [left-bound right-bound]} opts] (merge (when left-bound {"left_bound" (->rt-name left-bound)}) (when right-bound {"right_bound" (->rt-name right-bound)})))}) :during (let [[start end] parameters] {:arguments [[(->rt-value start) (->rt-value end)]]}) ;; :func (let [[params body] (first parameters)] ;; [(->rt-query-term params) (->rt-query-term body)]) :changes {:options (map-keys (comp underscore name) (first parameters)) :response-fn #(cond-> % (:new-val %) (update :new-val rt->) (:old-val %) (update :old-val rt->))} {:arguments parameters})))) (defn- ->rt-query [query] {:query (reduce (fn [query term] (let [{:keys [id arguments options]} (->rt-query-term term)] (remove nil? [id (cond->> arguments query (cons query) true (remove nil?)) options]))) nil query) :response-fn (or (->> (map (comp :response-fn ->rt-query-term) query) (remove nil?) last) rt->)}) (defn- xform-map [m kf vf] (into {} (map (fn [[k v]] [(kf k) (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (vf v) (and (map? v) (= "TIME" (get v :$reql-type$))) (vf v) (instance? DateTime v) (vf v) (map? v) (xform-map v kf vf) :else (vf v))]) m))) (defn- ->rt-name [s] (underscore (str (when (keyword? s) (when-let [ns (namespace s)] (str ns "/"))) (name s)))) (defn- rt-name-> [s] (keyword (hyphenate s))) (defn- ->rt-key [k] (cond (keyword? k) (->rt-name k) (string? k) (str "servo/str=" (->rt-name k)) (double? k) (str "servo/double=" (str k)) (int? k) (str "servo/long=" (str k)) :else (throw (ex-info ":servo/connection unsupported type for key" {:key k})))) (defn namespaced-string [k] (if (keyword? k) (if-let [ns (namespace k)] (str ns "/" (name k)) (name k)) k)) (defn- rt-key-> [k] (let [k (namespaced-string k) coerced (rt-string-> k)] (if (= k coerced) (keyword (hyphenate k)) coerced))) (defn- ->rt-value [v] (cond (keyword? v) (str "servo/keyword=" (->rt-name v)) (instance? DateTime v) {"$reql_type$" "TIME" "epoch_time" (double (/ (t/into :long v) 1000)) "timezone" "+00:00"} (or (vector? v) (seq? v)) [(get term-types :make-array) (map ->rt v)] :else v)) (defn- rt-value-> [v] (cond (and (map? v) (= "TIME" (get v "$reql_type$"))) (t/from :long (* 1000 (get v "epoch_time"))) (and (map? v) (= "TIME" (get v :$reql-type$))) (t/from :long (* 1000 (get v :epoch-time))) (or (vector? v) (seq? v)) (into (empty v) (map rt-> v)) (string? v) (rt-string-> v) :else v)) (defn- rt-string-> [s] (let [[_ type-fn value-str] (re-find #"^servo/(.*)=(.*)$" s)] (if (and type-fn value-str) ((case type-fn "keyword" (comp keyword hyphenate) "str" str "double" string->double "long" string->long) value-str) s))) (defn- ->rt [v] (cond (instance? DateTime v) (->rt-value v) (or (seq? v) (vector? v)) [(get term-types :make-array) (map ->rt v)] (map? v) (xform-map v ->rt-key ->rt-value) :else (->rt-value v))) (defn- ->rt-options [options] (->> options (map-vals (fn [option] (if (keyword? option) (name option) option))) ->rt)) (defn- rt-> [m] (cond (and (map? m) (= "TIME" (get m "$reql_type$"))) (rt-value-> m) (and (map? m) (= "TIME" (get m :$reql-type$))) (rt-value-> m) (map? m) (not-empty (xform-map m rt-key-> rt-value->)) :else (rt-value-> m))) (defn- ensure-db [connection db-name] (when-not ((set @(run connection [[:db-list]])) (rt-name-> db-name)) @(run connection [[:db-create (->rt-name db-name)]]))) (defn- await-tables-ready [{:keys [trace] :as connection}] (let [table-list @(run connection [[:table-list]]) await-tables-ready (fn [] (->> table-list (map (fn [table] @(run connection [[:table table] [:status]]))) (filter (comp :all-replicas-ready :status)) count))] (loop [] (let [ready-count (await-tables-ready)] (when (< ready-count (count table-list)) (when trace (log/debug (format ":servo/connection %s/%s tables ready." ready-count (count table-list)))) (Thread/sleep 1000) (recur)))) (when trace (log/debug ":servo/connection all tables ready")))) (def ^:private request-types {:start 1 :continue 2 :stop 3 :noreply-wait 4 :server-info 5}) (def ^:private response-types {1 :success-atom 2 :success-sequence 3 :success-partial 4 :wait-complete 5 :server-info 16 :client-error 17 :compile-error 18 :runtime-error}) (def ^:private response-error-types {1000000 :internal 2000000 :resource-limit 3000000 :query-logic 3100000 :non-existence 4100000 :op-failed 4200000 :op-indeterminate 5000000 :user 6000000 :permission-error}) (def ^:private response-note-types {1 :sequence-feed 2 :atom-feed 3 :order-by-limit-feed 4 :unioned-feed 5 :includes-states}) (def ^:private term-types {:datum 1 :make-array 2 :make-obj 3 :javascript 11 :uuid 169 :http 153 :error 12 :implicit-var 13 :db 14 :table 15 :get 16 :get-all 78 :eq 17 :ne 18 :lt 19 :le 20 :gt 21 :ge 22 :not 23 :add 24 :sub 25 :mul 26 :div 27 :mod 28 :floor 183 :ceil 184 :round 185 :append 29 :prepend 80 :difference 95 :set-insert 88 :set-intersection 89 :set-union 90 :set-difference 91 :slice 30 :skip 70 :limit 71 :offsets-of 87 :contains 93 :get-field 31 :keys 94 :values 186 :object 143 :has-fields 32 :with-fields 96 :pluck 33 :without 34 :merge 35 :between-deprecated 36 :between 182 :reduce 37 :map 38 :fold 187 :filter 39 :concat-map 40 :order-by 41 :distinct 42 :count 43 :is-empty 86 :union 44 :nth 45 :bracket 170 :inner-join 48 :outer-join 49 :eq-join 50 :zip 72 :range 173 :insert-at 82 :delete-at 83 :change-at 84 :splice-at 85 :coerce-to 51 :type-of 52 :update 53 :delete 54 :replace 55 :insert 56 :db-create 57 :db-drop 58 :db-list 59 :table-create 60 :table-drop 61 :table-list 62 :config 174 :status 175 :wait 177 :reconfigure 176 :rebalance 179 :sync 138 :grant 188 :index-create 75 :index-drop 76 :index-list 77 :index-status 139 :index-wait 140 :index-rename 156 :set-write-hook 189 :get-write-hook 190 :funcall 64 :branch 65 :or 66 :and 67 :for-each 68 :func 69 :asc 73 :desc 74 :info 79 :match 97 :upcase 141 :downcase 142 :sample 81 :default 92 :json 98 :iso8601 99 :to-iso8601 100 :epoch-time 101 :to-epoch-time 102 :now 103 :in-timezone 104 :during 105 :date 106 :time-of-day 126 :timezone 127 :year 128 :month 129 :day 130 :day-of-week 131 :day-of-year 132 :hours 133 :minutes 134 :seconds 135 :time 136 :monday 107 :tuesday 108 :wednesday 109 :thursday 110 :friday 111 :saturday 112 :sunday 113 :january 114 :february 115 :march 116 :april 117 :may 118 :june 119 :july 120 :august 121 :september 122 :october 123 :november 124 :december 125 :literal 137 :group 144 :sum 145 :avg 146 :min 147 :max 148 :split 149 :ungroup 150 :random 151 :changes 152 :arguments 154 :binary 155 :geojson 157 :to-geojson 158 :point 159 :line 160 :polygon 161 :distance 162 :intersects 163 :includes 164 :circle 165 :get-intersecting 166 :fill 167 :get-nearest 168 :polygon-sub 171 :to-json-string 172 :minval 180 :maxval 181 :bit-and 191 :bit-or 192 :bit-xor 193 :bit-not 194 :bit-sal 195 :bit-sar 196})
[ { "context": "> db\n (let [user1-eid (user-entity-id c \"user1@example.net\")]\n (assertions\n (schema/", "end": 6444, "score": 0.9999150633811951, "start": 6427, "tag": "EMAIL", "value": "user1@example.net" }, { "context": "\n (assertions\n (user-entity-id c \"user1@example.net\") => user1id)\n (schema/vtransact c [[:db/a", "end": 16336, "score": 0.9999139308929443, "start": 16319, "tag": "EMAIL", "value": "user1@example.net" }, { "context": "schema/vtransact c [[:db/add user1id :user/email \"updated@email.net\"]]) ;; update user email address\n (asserti", "end": 16427, "score": 0.9999240040779114, "start": 16410, "tag": "EMAIL", "value": "updated@email.net" }, { "context": "n't find the old one\n (user-entity-id c \"user1@example.net\") => nil\n ;; CAN find the new one!\n ", "end": 16563, "score": 0.999923050403595, "start": 16546, "tag": "EMAIL", "value": "user1@example.net" }, { "context": "AN find the new one!\n (user-entity-id c \"updated@email.net\") => user1id))\n\n (behavior \"fails against a ", "end": 16654, "score": 0.9999231100082397, "start": 16637, "tag": "EMAIL", "value": "updated@email.net" }, { "context": " (user-entity-id c \"updated@email.net\") => user1id))\n\n (behavior \"fails against a real database", "end": 16667, "score": 0.9324023127555847, "start": 16660, "tag": "USERNAME", "value": "user1id" } ]
specs/fulcro/datomic/schema/validation_spec.clj
fulcro-legacy/fulcro-datomic
6
(ns fulcro.datomic.schema.validation-spec (:require [fulcro.datomic.schema :as schema] [fulcro-spec.core :refer [specification assertions when-mocking component behavior]] [datomic.api :as datomic] [seeddata.auth :as a] [fulcro.datomic.test-helpers :as test-helpers :refer [with-db-fixture]] [resources.datomic-schema.validation-schema.initial] [clojure.test :refer [is]]) (:import (clojure.lang ExceptionInfo) (java.util.concurrent ExecutionException))) (defn- user-entity-id [conn email] (datomic/q '[:find ?e . :in $ ?v :where [?e :user/email ?v]] (datomic/db conn) email)) (defn- seed-validation [conn] (let [entities (concat (a/create-base-user-and-realm) [[:db/add :datomic.id/user1 :user/realm :datomic.id/realm1] [:db/add :datomic.id/user2 :user/realm :datomic.id/realm1]] [(test-helpers/generate-entity {:db/id :datomic.id/prop-entitlement :entitlement/kind :entitlement.kind/property }) (test-helpers/generate-entity {:db/id :datomic.id/comp-entitlement :entitlement/kind :entitlement.kind/component })])] (test-helpers/link-and-load-seed-data conn entities))) (specification "as-set" (behavior "converts scalars to singular sets" (assertions (schema/as-set 1) => #{1})) (behavior "converts lists to sets" (assertions (schema/as-set '(1 2 2)) => #{1 2})) (behavior "converts vectors to sets" (assertions (schema/as-set [1 2 2]) => #{1 2})) (behavior "leaves sets as sets" (assertions (schema/as-set #{1 2}) => #{1 2})) (behavior "throws an exception if passed a map" (assertions (schema/as-set {:a 1}) =throws=> (AssertionError #"does not work on maps")))) (specification "Attribute derivation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (behavior "foreign-attributes can find the allowed foreign attributes for an entity type" (assertions (schema/foreign-attributes db :user) => #{:authorization-role/name}) ; see schema in initial.clj ) (behavior "foreign-attributes accepts a string for kind" (assertions (schema/foreign-attributes db "user") => #{:authorization-role/name})) (behavior "core-attributes can find the normal attributes for an entity type" (assertions (schema/core-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "core-attributes accepts a string for kind" (assertions (schema/core-attributes db "user") => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "all-attributes can find all allowed attributes for an entity type including foreign" (assertions (schema/all-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role :authorization-role/name})) (behavior "definitive-attributes finds all of the definitive attributes in the schema." (assertions (schema/definitive-attributes db) => #{:user/user-id :realm/account-id})) (behavior "entity-types finds all of the types that a given entity conforms to" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]])) user-realm (datomic/entity new-db user1id)] (assertions (schema/entity-types new-db user-realm) => #{:user :realm}))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) (specification "Validation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (component "reference-constraint-for-attribute" (behavior "returns nil for non-constrained attributes" (assertions (schema/reference-constraint-for-attribute db :user/name) => nil)) (behavior "finds constraint data about schema" (assertions (select-keys (schema/reference-constraint-for-attribute db :user/property-entitlement) [:constraint/references :constraint/with-values]) => {:constraint/references :entitlement/kind :constraint/with-values #{:entitlement.kind/property-group :entitlement.kind/property :entitlement.kind/all-properties}})) (behavior "finds constraint data even when there are no constrained values " (assertions (:constraint/references (schema/reference-constraint-for-attribute db :realm/subscription)) => :subscription/name)) (behavior "includes the referencing (source) attribute" (assertions (:constraint/attribute (schema/reference-constraint-for-attribute db :realm/subscription)) => :realm/subscription))) (behavior "entity-has-attribute? can detect if an entity has an attribute" (when-mocking (datomic/db c) => db (let [user1-eid (user-entity-id c "user1@example.net")] (assertions (schema/entity-has-attribute? db user1-eid :user/user-id) => true (schema/entity-has-attribute? db user1-eid :realm/account-id) => false)))) (component "entities-in-tx" (behavior "finds the resolved temporary entity IDs and real IDs in a transaction" (let [newuser-tempid (datomic/tempid :db.part/user) datoms [[:db/add newuser-tempid :user/email "sample"] [:db/add user2id :user/email "sample2"]] result (datomic/with db datoms) newuser-realid (datomic/resolve-tempid (:db-after result) (:tempids result) newuser-tempid)] (assertions (schema/entities-in-tx result true) => #{newuser-realid user2id}))) (behavior "can optionally elide entities that were completely removed" (let [email (:user/email (datomic/entity db user1id)) datoms [[:db.fn/retractEntity prope-id] [:db/retract user1id :user/email email]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{user1id} (schema/entities-in-tx result true) => #{user1id prope-id}))) (behavior "includes entities that were updated because of reference nulling" (let [datoms [[:db.fn/retractEntity user2id]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{realm-id} ; realm is modified because it refs the user (schema/entities-in-tx result true) => #{user2id realm-id})))) (behavior "entities-that-reference returns the IDs of entities that reference a given entity" (assertions (into #{} (schema/entities-that-reference db realm-id)) => #{user1id user2id})) (component "invalid-references" (behavior "returns nil when all outgoing MANY references are valid" (assertions (schema/invalid-references db realm-id) => nil)) (behavior "returns nil when all outgoing ONE references are valid" (assertions (schema/invalid-references db user1id) => nil)) (behavior "returns a list of bad references when outgoing references are incorrect" (let [new-db (-> (datomic/with db [[:db/add user1id :user/realm compe-id] [:db/add user2id :user/property-entitlement compe-id]]) :db-after)] (assertions (select-keys (first (schema/invalid-references new-db user1id)) [:target-attr :reason]) => {:target-attr :realm/account-id :reason "Target attribute is missing"} (select-keys (first (schema/invalid-references new-db user2id)) [:target-attr :reason]) => {:target-attr :entitlement/kind :reason "Target attribute has incorrect value"})))) (component "invalid-attributes" (behavior "returns nil when the entity contains only valid attributes" (assertions (schema/invalid-attributes db (datomic/entity db user1id)) => nil)) (behavior "returns a set of invalid attributes on an entity" (let [new-db (:db-after (datomic/with db [[:db/add user1id :subscription/name "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => #{:subscription/name}))) (behavior "allows a definitive attribute to extend the allowed attributes" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => nil)))) (component "validate-transaction" (behavior "returns true if the transaction is empty" (let [new-db (datomic/with db [])] (assertions (schema/validate-transaction new-db) => true))) (behavior "returns true if the transaction is valid" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])] (assertions (schema/validate-transaction new-db) => true))) (behavior "throws an invalid reference exception when the transaction has a bad reference in the main modification" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References")))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by removing the targeted attribute" (let [new-db (datomic/with db [[:db/retract realm-id :realm/account-id "realm1"]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :realm/account-id (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by changing the targeted attribute value" (let [valid-db (:db-after (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])) new-db (datomic/with valid-db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(re-find #"incorrect value" (-> % ex-data :problems first :reason))) (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :entitlement/kind (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid attribute exception when an entity affected by the transaction ends up with a disallowed attribute" (let [new-db (datomic/with db [[:db/add user1id :subscription/name "boo"]])] (assertions (schema/validate-transaction new-db true) =throws=> (ExceptionInfo #"Invalid Attribute")))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) ;; IMPORTANT NOTE: These NON-integration tests are a bit heavy (as they have to muck about with the internals of the function ;; under test quite a bit); however, they are the only way to prove that both paths of validation (optimistic and ;; pessimistic) are correct. (specification "vtransact" (behavior "always validates references and attributes on the peer" (when-mocking (datomic/db _) => "conn" (datomic/basis-t _) => 1 (datomic/with _ _) => true (schema/validate-transaction _ true) => true (datomic/transact _ _) => (future []) (assertions (future? (schema/vtransact "conn" [])) => true))) (behavior "skips transact when optimistic validation fails" (when-mocking (datomic/db _) =2x=> "db" (datomic/with _ []) =2x=> {} (datomic/basis-t _) => 1 (schema/validate-transaction {} true) =1x=> (throw (ex-info "Validation failed" {})) (assertions @(schema/vtransact "conn" []) =throws=> (ExecutionException #"Validation failed")))) (behavior "optimistically applies changes via the transactor while enforcing version known at peer" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => :anything (schema/validate-transaction _ true) => true (datomic/transact conn tx) => (do (is (= (-> tx first) [:ensure-version optimistic-version])) (is (= (-> tx rest) tx-data)) (future [])) (schema/vtransact :connection tx-data)))) (behavior "completes if the optimistic update succeeds" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 transact-result (future [])] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => "..result.." (schema/validate-transaction _ true) => true (datomic/transact _ anything) => transact-result (assertions (schema/vtransact "connection" tx-data) => transact-result)))) (behavior "reverts to a pessimistic application in the transactor if optimistic update fails" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 tx-result-1 (future (throw (ex-info "Bad Version" {}))) tx-result-2 (future [])] (when-mocking (datomic/db conn) => "db" (datomic/basis-t db) => optimistic-version (datomic/with db tx-data) => "result" (schema/validate-transaction result true) => true (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:ensure-version optimistic-version])) ;; first attempt with ensured version fails (is (= (-> tx rest) tx-data)) tx-result-1) (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:constrained-transaction tx-data])) ;; second attempt constrained tx-result-2) (assertions (schema/vtransact "connection" tx-data) => tx-result-2)))) (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) user1id (:datomic.id/user1 id-map) bad-attr-tx [[:db/add user1id :subscription/name "data"]]] (behavior "succeeds against a real database" (assertions (user-entity-id c "user1@example.net") => user1id) (schema/vtransact c [[:db/add user1id :user/email "updated@email.net"]]) ;; update user email address (assertions ;; can't find the old one (user-entity-id c "user1@example.net") => nil ;; CAN find the new one! (user-entity-id c "updated@email.net") => user1id)) (behavior "fails against a real database when invalid attribute" (assertions @(schema/vtransact c bad-attr-tx) =throws=> (ExecutionException #"Invalid Attribute" #(contains? (-> % .getCause ex-data :problems) :subscription/name))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation))
97386
(ns fulcro.datomic.schema.validation-spec (:require [fulcro.datomic.schema :as schema] [fulcro-spec.core :refer [specification assertions when-mocking component behavior]] [datomic.api :as datomic] [seeddata.auth :as a] [fulcro.datomic.test-helpers :as test-helpers :refer [with-db-fixture]] [resources.datomic-schema.validation-schema.initial] [clojure.test :refer [is]]) (:import (clojure.lang ExceptionInfo) (java.util.concurrent ExecutionException))) (defn- user-entity-id [conn email] (datomic/q '[:find ?e . :in $ ?v :where [?e :user/email ?v]] (datomic/db conn) email)) (defn- seed-validation [conn] (let [entities (concat (a/create-base-user-and-realm) [[:db/add :datomic.id/user1 :user/realm :datomic.id/realm1] [:db/add :datomic.id/user2 :user/realm :datomic.id/realm1]] [(test-helpers/generate-entity {:db/id :datomic.id/prop-entitlement :entitlement/kind :entitlement.kind/property }) (test-helpers/generate-entity {:db/id :datomic.id/comp-entitlement :entitlement/kind :entitlement.kind/component })])] (test-helpers/link-and-load-seed-data conn entities))) (specification "as-set" (behavior "converts scalars to singular sets" (assertions (schema/as-set 1) => #{1})) (behavior "converts lists to sets" (assertions (schema/as-set '(1 2 2)) => #{1 2})) (behavior "converts vectors to sets" (assertions (schema/as-set [1 2 2]) => #{1 2})) (behavior "leaves sets as sets" (assertions (schema/as-set #{1 2}) => #{1 2})) (behavior "throws an exception if passed a map" (assertions (schema/as-set {:a 1}) =throws=> (AssertionError #"does not work on maps")))) (specification "Attribute derivation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (behavior "foreign-attributes can find the allowed foreign attributes for an entity type" (assertions (schema/foreign-attributes db :user) => #{:authorization-role/name}) ; see schema in initial.clj ) (behavior "foreign-attributes accepts a string for kind" (assertions (schema/foreign-attributes db "user") => #{:authorization-role/name})) (behavior "core-attributes can find the normal attributes for an entity type" (assertions (schema/core-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "core-attributes accepts a string for kind" (assertions (schema/core-attributes db "user") => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "all-attributes can find all allowed attributes for an entity type including foreign" (assertions (schema/all-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role :authorization-role/name})) (behavior "definitive-attributes finds all of the definitive attributes in the schema." (assertions (schema/definitive-attributes db) => #{:user/user-id :realm/account-id})) (behavior "entity-types finds all of the types that a given entity conforms to" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]])) user-realm (datomic/entity new-db user1id)] (assertions (schema/entity-types new-db user-realm) => #{:user :realm}))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) (specification "Validation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (component "reference-constraint-for-attribute" (behavior "returns nil for non-constrained attributes" (assertions (schema/reference-constraint-for-attribute db :user/name) => nil)) (behavior "finds constraint data about schema" (assertions (select-keys (schema/reference-constraint-for-attribute db :user/property-entitlement) [:constraint/references :constraint/with-values]) => {:constraint/references :entitlement/kind :constraint/with-values #{:entitlement.kind/property-group :entitlement.kind/property :entitlement.kind/all-properties}})) (behavior "finds constraint data even when there are no constrained values " (assertions (:constraint/references (schema/reference-constraint-for-attribute db :realm/subscription)) => :subscription/name)) (behavior "includes the referencing (source) attribute" (assertions (:constraint/attribute (schema/reference-constraint-for-attribute db :realm/subscription)) => :realm/subscription))) (behavior "entity-has-attribute? can detect if an entity has an attribute" (when-mocking (datomic/db c) => db (let [user1-eid (user-entity-id c "<EMAIL>")] (assertions (schema/entity-has-attribute? db user1-eid :user/user-id) => true (schema/entity-has-attribute? db user1-eid :realm/account-id) => false)))) (component "entities-in-tx" (behavior "finds the resolved temporary entity IDs and real IDs in a transaction" (let [newuser-tempid (datomic/tempid :db.part/user) datoms [[:db/add newuser-tempid :user/email "sample"] [:db/add user2id :user/email "sample2"]] result (datomic/with db datoms) newuser-realid (datomic/resolve-tempid (:db-after result) (:tempids result) newuser-tempid)] (assertions (schema/entities-in-tx result true) => #{newuser-realid user2id}))) (behavior "can optionally elide entities that were completely removed" (let [email (:user/email (datomic/entity db user1id)) datoms [[:db.fn/retractEntity prope-id] [:db/retract user1id :user/email email]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{user1id} (schema/entities-in-tx result true) => #{user1id prope-id}))) (behavior "includes entities that were updated because of reference nulling" (let [datoms [[:db.fn/retractEntity user2id]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{realm-id} ; realm is modified because it refs the user (schema/entities-in-tx result true) => #{user2id realm-id})))) (behavior "entities-that-reference returns the IDs of entities that reference a given entity" (assertions (into #{} (schema/entities-that-reference db realm-id)) => #{user1id user2id})) (component "invalid-references" (behavior "returns nil when all outgoing MANY references are valid" (assertions (schema/invalid-references db realm-id) => nil)) (behavior "returns nil when all outgoing ONE references are valid" (assertions (schema/invalid-references db user1id) => nil)) (behavior "returns a list of bad references when outgoing references are incorrect" (let [new-db (-> (datomic/with db [[:db/add user1id :user/realm compe-id] [:db/add user2id :user/property-entitlement compe-id]]) :db-after)] (assertions (select-keys (first (schema/invalid-references new-db user1id)) [:target-attr :reason]) => {:target-attr :realm/account-id :reason "Target attribute is missing"} (select-keys (first (schema/invalid-references new-db user2id)) [:target-attr :reason]) => {:target-attr :entitlement/kind :reason "Target attribute has incorrect value"})))) (component "invalid-attributes" (behavior "returns nil when the entity contains only valid attributes" (assertions (schema/invalid-attributes db (datomic/entity db user1id)) => nil)) (behavior "returns a set of invalid attributes on an entity" (let [new-db (:db-after (datomic/with db [[:db/add user1id :subscription/name "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => #{:subscription/name}))) (behavior "allows a definitive attribute to extend the allowed attributes" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => nil)))) (component "validate-transaction" (behavior "returns true if the transaction is empty" (let [new-db (datomic/with db [])] (assertions (schema/validate-transaction new-db) => true))) (behavior "returns true if the transaction is valid" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])] (assertions (schema/validate-transaction new-db) => true))) (behavior "throws an invalid reference exception when the transaction has a bad reference in the main modification" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References")))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by removing the targeted attribute" (let [new-db (datomic/with db [[:db/retract realm-id :realm/account-id "realm1"]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :realm/account-id (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by changing the targeted attribute value" (let [valid-db (:db-after (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])) new-db (datomic/with valid-db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(re-find #"incorrect value" (-> % ex-data :problems first :reason))) (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :entitlement/kind (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid attribute exception when an entity affected by the transaction ends up with a disallowed attribute" (let [new-db (datomic/with db [[:db/add user1id :subscription/name "boo"]])] (assertions (schema/validate-transaction new-db true) =throws=> (ExceptionInfo #"Invalid Attribute")))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) ;; IMPORTANT NOTE: These NON-integration tests are a bit heavy (as they have to muck about with the internals of the function ;; under test quite a bit); however, they are the only way to prove that both paths of validation (optimistic and ;; pessimistic) are correct. (specification "vtransact" (behavior "always validates references and attributes on the peer" (when-mocking (datomic/db _) => "conn" (datomic/basis-t _) => 1 (datomic/with _ _) => true (schema/validate-transaction _ true) => true (datomic/transact _ _) => (future []) (assertions (future? (schema/vtransact "conn" [])) => true))) (behavior "skips transact when optimistic validation fails" (when-mocking (datomic/db _) =2x=> "db" (datomic/with _ []) =2x=> {} (datomic/basis-t _) => 1 (schema/validate-transaction {} true) =1x=> (throw (ex-info "Validation failed" {})) (assertions @(schema/vtransact "conn" []) =throws=> (ExecutionException #"Validation failed")))) (behavior "optimistically applies changes via the transactor while enforcing version known at peer" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => :anything (schema/validate-transaction _ true) => true (datomic/transact conn tx) => (do (is (= (-> tx first) [:ensure-version optimistic-version])) (is (= (-> tx rest) tx-data)) (future [])) (schema/vtransact :connection tx-data)))) (behavior "completes if the optimistic update succeeds" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 transact-result (future [])] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => "..result.." (schema/validate-transaction _ true) => true (datomic/transact _ anything) => transact-result (assertions (schema/vtransact "connection" tx-data) => transact-result)))) (behavior "reverts to a pessimistic application in the transactor if optimistic update fails" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 tx-result-1 (future (throw (ex-info "Bad Version" {}))) tx-result-2 (future [])] (when-mocking (datomic/db conn) => "db" (datomic/basis-t db) => optimistic-version (datomic/with db tx-data) => "result" (schema/validate-transaction result true) => true (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:ensure-version optimistic-version])) ;; first attempt with ensured version fails (is (= (-> tx rest) tx-data)) tx-result-1) (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:constrained-transaction tx-data])) ;; second attempt constrained tx-result-2) (assertions (schema/vtransact "connection" tx-data) => tx-result-2)))) (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) user1id (:datomic.id/user1 id-map) bad-attr-tx [[:db/add user1id :subscription/name "data"]]] (behavior "succeeds against a real database" (assertions (user-entity-id c "<EMAIL>") => user1id) (schema/vtransact c [[:db/add user1id :user/email "<EMAIL>"]]) ;; update user email address (assertions ;; can't find the old one (user-entity-id c "<EMAIL>") => nil ;; CAN find the new one! (user-entity-id c "<EMAIL>") => user1id)) (behavior "fails against a real database when invalid attribute" (assertions @(schema/vtransact c bad-attr-tx) =throws=> (ExecutionException #"Invalid Attribute" #(contains? (-> % .getCause ex-data :problems) :subscription/name))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation))
true
(ns fulcro.datomic.schema.validation-spec (:require [fulcro.datomic.schema :as schema] [fulcro-spec.core :refer [specification assertions when-mocking component behavior]] [datomic.api :as datomic] [seeddata.auth :as a] [fulcro.datomic.test-helpers :as test-helpers :refer [with-db-fixture]] [resources.datomic-schema.validation-schema.initial] [clojure.test :refer [is]]) (:import (clojure.lang ExceptionInfo) (java.util.concurrent ExecutionException))) (defn- user-entity-id [conn email] (datomic/q '[:find ?e . :in $ ?v :where [?e :user/email ?v]] (datomic/db conn) email)) (defn- seed-validation [conn] (let [entities (concat (a/create-base-user-and-realm) [[:db/add :datomic.id/user1 :user/realm :datomic.id/realm1] [:db/add :datomic.id/user2 :user/realm :datomic.id/realm1]] [(test-helpers/generate-entity {:db/id :datomic.id/prop-entitlement :entitlement/kind :entitlement.kind/property }) (test-helpers/generate-entity {:db/id :datomic.id/comp-entitlement :entitlement/kind :entitlement.kind/component })])] (test-helpers/link-and-load-seed-data conn entities))) (specification "as-set" (behavior "converts scalars to singular sets" (assertions (schema/as-set 1) => #{1})) (behavior "converts lists to sets" (assertions (schema/as-set '(1 2 2)) => #{1 2})) (behavior "converts vectors to sets" (assertions (schema/as-set [1 2 2]) => #{1 2})) (behavior "leaves sets as sets" (assertions (schema/as-set #{1 2}) => #{1 2})) (behavior "throws an exception if passed a map" (assertions (schema/as-set {:a 1}) =throws=> (AssertionError #"does not work on maps")))) (specification "Attribute derivation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (behavior "foreign-attributes can find the allowed foreign attributes for an entity type" (assertions (schema/foreign-attributes db :user) => #{:authorization-role/name}) ; see schema in initial.clj ) (behavior "foreign-attributes accepts a string for kind" (assertions (schema/foreign-attributes db "user") => #{:authorization-role/name})) (behavior "core-attributes can find the normal attributes for an entity type" (assertions (schema/core-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "core-attributes accepts a string for kind" (assertions (schema/core-attributes db "user") => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role})) (behavior "all-attributes can find all allowed attributes for an entity type including foreign" (assertions (schema/all-attributes db :user) => #{:user/password :user/property-entitlement :user/user-id :user/email :user/is-active :user/validation-code :user/realm :user/authorization-role :authorization-role/name})) (behavior "definitive-attributes finds all of the definitive attributes in the schema." (assertions (schema/definitive-attributes db) => #{:user/user-id :realm/account-id})) (behavior "entity-types finds all of the types that a given entity conforms to" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]])) user-realm (datomic/entity new-db user1id)] (assertions (schema/entity-types new-db user-realm) => #{:user :realm}))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) (specification "Validation" (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) realm-id (:datomic.id/realm1 id-map) user1id (:datomic.id/user1 id-map) user2id (:datomic.id/user2 id-map) compe-id (:datomic.id/comp-entitlement id-map) prope-id (:datomic.id/prop-entitlement id-map)] (component "reference-constraint-for-attribute" (behavior "returns nil for non-constrained attributes" (assertions (schema/reference-constraint-for-attribute db :user/name) => nil)) (behavior "finds constraint data about schema" (assertions (select-keys (schema/reference-constraint-for-attribute db :user/property-entitlement) [:constraint/references :constraint/with-values]) => {:constraint/references :entitlement/kind :constraint/with-values #{:entitlement.kind/property-group :entitlement.kind/property :entitlement.kind/all-properties}})) (behavior "finds constraint data even when there are no constrained values " (assertions (:constraint/references (schema/reference-constraint-for-attribute db :realm/subscription)) => :subscription/name)) (behavior "includes the referencing (source) attribute" (assertions (:constraint/attribute (schema/reference-constraint-for-attribute db :realm/subscription)) => :realm/subscription))) (behavior "entity-has-attribute? can detect if an entity has an attribute" (when-mocking (datomic/db c) => db (let [user1-eid (user-entity-id c "PI:EMAIL:<EMAIL>END_PI")] (assertions (schema/entity-has-attribute? db user1-eid :user/user-id) => true (schema/entity-has-attribute? db user1-eid :realm/account-id) => false)))) (component "entities-in-tx" (behavior "finds the resolved temporary entity IDs and real IDs in a transaction" (let [newuser-tempid (datomic/tempid :db.part/user) datoms [[:db/add newuser-tempid :user/email "sample"] [:db/add user2id :user/email "sample2"]] result (datomic/with db datoms) newuser-realid (datomic/resolve-tempid (:db-after result) (:tempids result) newuser-tempid)] (assertions (schema/entities-in-tx result true) => #{newuser-realid user2id}))) (behavior "can optionally elide entities that were completely removed" (let [email (:user/email (datomic/entity db user1id)) datoms [[:db.fn/retractEntity prope-id] [:db/retract user1id :user/email email]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{user1id} (schema/entities-in-tx result true) => #{user1id prope-id}))) (behavior "includes entities that were updated because of reference nulling" (let [datoms [[:db.fn/retractEntity user2id]] result (datomic/with db datoms)] (assertions (schema/entities-in-tx result) => #{realm-id} ; realm is modified because it refs the user (schema/entities-in-tx result true) => #{user2id realm-id})))) (behavior "entities-that-reference returns the IDs of entities that reference a given entity" (assertions (into #{} (schema/entities-that-reference db realm-id)) => #{user1id user2id})) (component "invalid-references" (behavior "returns nil when all outgoing MANY references are valid" (assertions (schema/invalid-references db realm-id) => nil)) (behavior "returns nil when all outgoing ONE references are valid" (assertions (schema/invalid-references db user1id) => nil)) (behavior "returns a list of bad references when outgoing references are incorrect" (let [new-db (-> (datomic/with db [[:db/add user1id :user/realm compe-id] [:db/add user2id :user/property-entitlement compe-id]]) :db-after)] (assertions (select-keys (first (schema/invalid-references new-db user1id)) [:target-attr :reason]) => {:target-attr :realm/account-id :reason "Target attribute is missing"} (select-keys (first (schema/invalid-references new-db user2id)) [:target-attr :reason]) => {:target-attr :entitlement/kind :reason "Target attribute has incorrect value"})))) (component "invalid-attributes" (behavior "returns nil when the entity contains only valid attributes" (assertions (schema/invalid-attributes db (datomic/entity db user1id)) => nil)) (behavior "returns a set of invalid attributes on an entity" (let [new-db (:db-after (datomic/with db [[:db/add user1id :subscription/name "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => #{:subscription/name}))) (behavior "allows a definitive attribute to extend the allowed attributes" (let [new-db (:db-after (datomic/with db [[:db/add user1id :realm/account-id "boo"]]))] (assertions (schema/invalid-attributes new-db (datomic/entity new-db user1id)) => nil)))) (component "validate-transaction" (behavior "returns true if the transaction is empty" (let [new-db (datomic/with db [])] (assertions (schema/validate-transaction new-db) => true))) (behavior "returns true if the transaction is valid" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])] (assertions (schema/validate-transaction new-db) => true))) (behavior "throws an invalid reference exception when the transaction has a bad reference in the main modification" (let [new-db (datomic/with db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References")))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by removing the targeted attribute" (let [new-db (datomic/with db [[:db/retract realm-id :realm/account-id "realm1"]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :realm/account-id (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid reference exception when the transaction causes an existing reference to become invalid by changing the targeted attribute value" (let [valid-db (:db-after (datomic/with db [[:db/add user1id :user/property-entitlement prope-id]])) new-db (datomic/with valid-db [[:db/add user1id :user/property-entitlement compe-id]])] (assertions (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(re-find #"incorrect value" (-> % ex-data :problems first :reason))) (schema/validate-transaction new-db) =throws=> (ExceptionInfo #"Invalid References" #(= :entitlement/kind (-> % ex-data :problems first :target-attr)))))) (behavior "throws an invalid attribute exception when an entity affected by the transaction ends up with a disallowed attribute" (let [new-db (datomic/with db [[:db/add user1id :subscription/name "boo"]])] (assertions (schema/validate-transaction new-db true) =throws=> (ExceptionInfo #"Invalid Attribute")))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation)) ;; IMPORTANT NOTE: These NON-integration tests are a bit heavy (as they have to muck about with the internals of the function ;; under test quite a bit); however, they are the only way to prove that both paths of validation (optimistic and ;; pessimistic) are correct. (specification "vtransact" (behavior "always validates references and attributes on the peer" (when-mocking (datomic/db _) => "conn" (datomic/basis-t _) => 1 (datomic/with _ _) => true (schema/validate-transaction _ true) => true (datomic/transact _ _) => (future []) (assertions (future? (schema/vtransact "conn" [])) => true))) (behavior "skips transact when optimistic validation fails" (when-mocking (datomic/db _) =2x=> "db" (datomic/with _ []) =2x=> {} (datomic/basis-t _) => 1 (schema/validate-transaction {} true) =1x=> (throw (ex-info "Validation failed" {})) (assertions @(schema/vtransact "conn" []) =throws=> (ExecutionException #"Validation failed")))) (behavior "optimistically applies changes via the transactor while enforcing version known at peer" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => :anything (schema/validate-transaction _ true) => true (datomic/transact conn tx) => (do (is (= (-> tx first) [:ensure-version optimistic-version])) (is (= (-> tx rest) tx-data)) (future [])) (schema/vtransact :connection tx-data)))) (behavior "completes if the optimistic update succeeds" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 transact-result (future [])] (when-mocking (datomic/db _) => "db" (datomic/basis-t _) => optimistic-version (datomic/with _ tx-data) => "..result.." (schema/validate-transaction _ true) => true (datomic/transact _ anything) => transact-result (assertions (schema/vtransact "connection" tx-data) => transact-result)))) (behavior "reverts to a pessimistic application in the transactor if optimistic update fails" (let [tx-data [[:db/add 1 :blah 2]] optimistic-version 1 tx-result-1 (future (throw (ex-info "Bad Version" {}))) tx-result-2 (future [])] (when-mocking (datomic/db conn) => "db" (datomic/basis-t db) => optimistic-version (datomic/with db tx-data) => "result" (schema/validate-transaction result true) => true (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:ensure-version optimistic-version])) ;; first attempt with ensured version fails (is (= (-> tx rest) tx-data)) tx-result-1) (datomic/transact conn tx) =1x=> (do (is (= (-> tx first) [:constrained-transaction tx-data])) ;; second attempt constrained tx-result-2) (assertions (schema/vtransact "connection" tx-data) => tx-result-2)))) (with-db-fixture dbcomp (let [c (:connection dbcomp) db (datomic/db c) id-map (-> dbcomp :seed-result) user1id (:datomic.id/user1 id-map) bad-attr-tx [[:db/add user1id :subscription/name "data"]]] (behavior "succeeds against a real database" (assertions (user-entity-id c "PI:EMAIL:<EMAIL>END_PI") => user1id) (schema/vtransact c [[:db/add user1id :user/email "PI:EMAIL:<EMAIL>END_PI"]]) ;; update user email address (assertions ;; can't find the old one (user-entity-id c "PI:EMAIL:<EMAIL>END_PI") => nil ;; CAN find the new one! (user-entity-id c "PI:EMAIL:<EMAIL>END_PI") => user1id)) (behavior "fails against a real database when invalid attribute" (assertions @(schema/vtransact c bad-attr-tx) =throws=> (ExecutionException #"Invalid Attribute" #(contains? (-> % .getCause ex-data :problems) :subscription/name))))) :migrations "resources.datomic-schema.validation-schema" :seed-fn seed-validation))
[ { "context": " (goto \"https://www.walmart.com/\")\n (send-keys \"global-search-input\" \"iphone 6s\\n\")\n (click \"//img[contains(@alt,'Ap", "end": 548, "score": 0.893195629119873, "start": 529, "tag": "KEY", "value": "global-search-input" }, { "context": "almart.com/\")\n (send-keys \"global-search-input\" \"iphone 6s\\n\")\n (click \"//img[contains(@alt,'Apple iPhone 6s'", "end": 562, "score": 0.9117853045463562, "start": 551, "tag": "KEY", "value": "iphone 6s\\n" } ]
src/pbot/tests/samples/sample2.clj
mogenslund/pragmatic-robot
0
(ns pbot.tests.samples.sample2 (:require [clojure.test :refer :all] [pbot.shared.walmart :refer :all] [pbot.lib.web :refer :all])) (deftest searchtest1 (set-retries 6) (new-browser) (walmart-search "iphone 6s") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest searchtest2 (set-retries 6) (new-browser) (goto "https://www.walmart.com/") (send-keys "global-search-input" "iphone 6s\n") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest good (is (= 2 (+ 1 1)) "Not working"))
46937
(ns pbot.tests.samples.sample2 (:require [clojure.test :refer :all] [pbot.shared.walmart :refer :all] [pbot.lib.web :refer :all])) (deftest searchtest1 (set-retries 6) (new-browser) (walmart-search "iphone 6s") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest searchtest2 (set-retries 6) (new-browser) (goto "https://www.walmart.com/") (send-keys "<KEY>" "<KEY>") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest good (is (= 2 (+ 1 1)) "Not working"))
true
(ns pbot.tests.samples.sample2 (:require [clojure.test :refer :all] [pbot.shared.walmart :refer :all] [pbot.lib.web :refer :all])) (deftest searchtest1 (set-retries 6) (new-browser) (walmart-search "iphone 6s") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest searchtest2 (set-retries 6) (new-browser) (goto "https://www.walmart.com/") (send-keys "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI") (click "//img[contains(@alt,'Apple iPhone 6s')]") (is (= (get-text "//div[contains(@class,'prod-product-cta-add-to-cart')]/button") "Add to Cart") "Text not found") (quit)) (deftest good (is (= 2 (+ 1 1)) "Not working"))
[ { "context": "\"\n [{:keys [destination recipient]}]\n (and (#{\"nord_sten\" \"ms_stein\"} recipient)\n (scandinavia-citie", "end": 4952, "score": 0.7797166705131531, "start": 4944, "tag": "USERNAME", "value": "ord_sten" }, { "context": "destination recipient]}]\n (and (#{\"nord_sten\" \"ms_stein\"} recipient)\n (scandinavia-cities destinati", "end": 4963, "score": 0.8930532932281494, "start": 4958, "tag": "USERNAME", "value": "stein" }, { "context": "[recipient]}]\n (= \"c_navale\" recipient))\n\n(defn michaelangelo\n \"Deliver from the Carrara quarry (marmo in Livo", "end": 5907, "score": 0.7911155223846436, "start": 5895, "tag": "USERNAME", "value": "ichaelangelo" }, { "context": "Livorno).\"\n [{:keys [origin sender]}]\n (and (= \"marmo\" sender)\n (= \"livorno\" origin)))\n\n\n(def ^:p", "end": 6008, "score": 0.7360172867774963, "start": 6003, "tag": "USERNAME", "value": "marmo" }, { "context": "ver to all quarries in Scandinavia (Nordic Stenbrott, MS Stein).\"\n :pred miner}]}\n\n :baltic\n ", "end": 7019, "score": 0.5691680908203125, "start": 7017, "tag": "NAME", "value": "tt" }, { "context": "tiare Navale)\"\n :pred captain}\n\n {:key :michaelangelo\n :name \"Michaelangelo\"\n :desc \"Deliver ", "end": 8865, "score": 0.9709986448287964, "start": 8852, "tag": "USERNAME", "value": "michaelangelo" }, { "context": "captain}\n\n {:key :michaelangelo\n :name \"Michaelangelo\"\n :desc \"Deliver from the Carrara quarry (Ma", "end": 8892, "score": 0.9246097207069397, "start": 8879, "tag": "NAME", "value": "Michaelangelo" }, { "context": " :pred gas-must-flow}]}\n\n :iberia\n {:name \"Iberia\"\n :achievements\n [{:key :lets-get-shippi", "end": 9573, "score": 0.5912916660308838, "start": 9570, "tag": "NAME", "value": "ber" }, { "context": "un}\n\n {:key :iberian-pilgrimage\n :name \"Iberian Pilgrimage\"\n :desc \"Deliver to A Coruña from Lisbon, Se", "end": 10139, "score": 0.9949756860733032, "start": 10121, "tag": "NAME", "value": "Iberian Pilgrimage" } ]
components/ets2/src/ets/jobs/ets2/achievements.clj
bshepherdson/etsjobs
0
(ns ets.jobs.ets2.achievements (:require [ets.jobs.ets2.map :as map])) (defn baltic? [city-slug] (#{"EST" "FI" "LT" "LV" "RU"} (:c (map/cities city-slug)))) (defn concrete-jungle [{:keys [sender origin]}] (and (baltic? origin) (= "radus" sender))) (defn industry-standard "2 deliveries to every paper mill, loco factory, and furniture factory in the Baltic states. Those are LVR, Renat, Viljo Paperitehdas Oy, Estonian Paper AS, and VPF (lvr, renat, viljo_paper, ee_paper, viln_paper)." [{:keys [recipient]}] (#{"lvr" "renat" "viljo_paper" "ee_paper" "viln_paper"} recipient)) (def russian-main-cities #{"luga" "pskov" "petersburg" "sosnovy_bor" "vyborg"}) (defn exclave-transit "Delivery from Kaliningrad to other Russian cities." [{:keys [origin destination]}] (and (= "kaliningrad" origin) (russian-main-cities destination))) (defn like-a-farmer "Deliver to each farm in the Baltic region. Agrominta UAB (agrominta, agrominta_a; both near Utena LT) Eviksi (eviksi, eviksi_a; (double near Liepaja LV)) Maatila Egres (egres) Onnelik talu (onnelik, onnelik_a; double near Parna EST) Zelenye Polja (zelenye, zelenye_a)" [{:keys [recipient]}] (#{"agrominta" "agrominta_a" "eviksi" "eviksi_a" "egres" "onnelik" "onnelik_a" "zelenye" "zelenye_a"} recipient)) (defn turkish-delight [{:keys [origin distance]}] (and (>= distance 2500) (= "istanbul" origin))) (defn along-the-black-sea "Perfect deliveries either direction between these pairs: Istanbul-Burgas Burgas-Varna Varna-Mangalia Mangalia-Constanta" [{:keys [origin destination]}] (or (and (= origin "istanbul") (= destination "burgas")) (and (= origin "burgas") (= destination "istanbul")) (and (= origin "burgas") (= destination "varna")) (and (= origin "varna") (= destination "burgas")) (and (= origin "varna") (= destination "mangalia")) (and (= origin "mangalia") (= destination "varna")) (and (= origin "mangalia") (= destination "constanta")) (and (= origin "constanta") (= destination "mangalia")))) (defn orient-express [{:keys [origin destination]}] (or (and (= origin "paris") (= destination "strasbourg")) (and (= origin "strasbourg") (= destination "munchen")) (and (= origin "munchen") (= destination "wien")) (and (= origin "wien") (= destination "budapest")) (and (= origin "budapest") (= destination "bucuresti")) (and (= origin "bucuresti") (= destination "istanbul")))) (defn lets-get-shipping "Deliver to all container ports in Iberia (TS Atlas)." [{:keys [recipient]}] (= "ts_atlas" recipient)) (defn fleet-builder "Deliver to all shipyards in Iberia (Ocean Solution Group, ocean_sol)." [{:keys [recipient]}] (= "ocean_sol" recipient)) (defn iberian-pilgrimage "Deliver from Lisbon, Seville and Pamplona to A Coruna." [{:keys [origin destination]}] (and (= destination "a_coruna") (#{"lisboa" "sevilla" "pamplona"} origin))) (defn taste-the-sun "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." [{:keys [cargo recipient]}] (and (= "engeron" recipient) (:adr (map/cargos cargo)))) ; TODO Test this one - no jobs found. (defn volvo-trucks-lover "Deliver trucks from the Volvo factory to a dealer." [{:keys [cargo sender]}] (and (= "volvo_fac" sender) (= "trucks" cargo))) ; TODO Test this one - no jobs found. (defn scania-trucks-lover "Deliver trucks from Scania factory to a dealer." [{:keys [cargo sender]}] (and (= "scania_fac" sender) (= "trucks" cargo))) (def scandinavia-cities #{; Denmark "aalborg" "esbjerg" "frederikshavn" "gedser" "hirtshals" "kobenhavn" "odense" ; Norway "bergen" "kristiansand" "oslo" "stavanger" ; Sweden "goteborg" "helsingborg" "jonkoping" "kalmar" "kapellskar" "karlskrona" "linkoping" "malmo" "nynashamn" "orebro" "stockholm" "sodertalje" "trelleborg" "uppsala" "vasteraas" "vaxjo"}) (defn sailor "Deliver yachts to all Scandinavian marinas (marina)." [{:keys [cargo destination recipient]}] (and (scandinavia-cities destination) (= "marina" recipient) (= "yacht" cargo))) (defn cattle-drive "Complete a livestock delivery to Scandinavia." [{:keys [destination cargo]}] (and (= "livestock" cargo) (scandinavia-cities destination))) (defn whatever-floats-your-boat "Deliver to all container ports in Scandinavia (cont_port)." [{:keys [destination recipient]}] (and (= "cont_port" recipient) (scandinavia-cities destination))) (defn miner "Deliver to all quarries in Scandinavia (nord_sten, ms_stein)." [{:keys [destination recipient]}] (and (#{"nord_sten" "ms_stein"} recipient) (scandinavia-cities destination))) ; France (def french-reactors #{"civaux" "golfech" "paluel" "alban" "laurent"}) (defn go-nuclear "Deliver to 5 nuclear plants in France (nucleon)." [{:keys [destination recipient]}] (and (= "nucleon" recipient) (french-reactors destination))) (def french-airports #{"bastia" "brest" "calvi" "clermont" "montpellier" "nantes" "paris" "toulouse"}) (defn check-in-check-out "Deliver to all cargo airport terminals in France (fle, in France.)" [{:keys [destination recipient]}] (and (= "fle" recipient) (french-airports destination))) ; TODO Implement this one once I can see a "gas must flow" job. (defn gas-must-flow "Deliver petrol/gasoline, diesel, or LPG to all truck stops in France." [_] false) ; Italy (defn captain "Deliver to all Italian shipyards (c_navale)." [{:keys [recipient]}] (= "c_navale" recipient)) (defn michaelangelo "Deliver from the Carrara quarry (marmo in Livorno)." [{:keys [origin sender]}] (and (= "marmo" sender) (= "livorno" origin))) (def ^:private ets-regions {:scandinavia {:name "Scandinavia" :achievements [{:key :whatever-floats-your-boat :name "Whatever Floats Your Boat" :desc "Deliver to all container ports in Scandinavia (Container Port)." :pred whatever-floats-your-boat} {:key :sailor :name "Sailor" :desc "Deliver yachts to all Scandinavian marinas (boat symbol)." :pred sailor} {:key :volvo-trucks-lover :name "Volvo Trucks Lover" :desc "Deliver trucks from the Volvo factory." :pred volvo-trucks-lover} {:key :scania-trucks-lover :name "Scania Trucks Lover" :desc "Deliver trucks from the Scania factory." :pred scania-trucks-lover} {:key :cattle-drive :name "Cattle Drive" :desc "Complete a livestock delivery to Scandinavia." :pred cattle-drive} {:key :miner :name "Miner" :desc "Deliver to all quarries in Scandinavia (Nordic Stenbrott, MS Stein)." :pred miner}]} :baltic {:name "Beyond the Baltic Sea" :achievements [{:key :concrete-jungle :name "Concrete Jungle" :desc "Complete 10 deliveries from concrete plants (Radus, Радус)" :pred concrete-jungle} {:key :industry-standard :name "Industry Standard" :desc (str "Complete 2 deliveries to every paper mill, loco factory, and" "furniture maker in the Baltic region (LVR, Renat, Viljo " "Paperitehdas Oy, Estonian Paper AS, VPF).") :pred industry-standard} {:key :exclave-transit :name "Exclave Transit" :desc "Complete 5 deliveries from Kaliningrad to any other Russian city." :pred exclave-transit} {:key :like-a-farmer :name "Like a Farmer" :desc "Deliver to each farm in the Baltic. (Agrominta UAB, Eviksi, Maatila Egres, Onnelik Talu, Zelenye Polja)" :pred like-a-farmer}]} :black-sea {:name "Road to the Black Sea" :achievements [{:key :turkish-delight :name "Turkish Delight" :desc "Complete 3 deliveries from Istanbul which are at least 2500km long." :pred turkish-delight} {:key :along-the-black-sea :name "Along the Black Sea" :desc "Complete perfect deliveries in any order or direction between these coastal cities." :pred along-the-black-sea} {:key :orient-express :name "Orient Express" :desc "Complete deliveries between the following cities, in order: Paris, Strasbourg, Munich, Vienna, Budapest, Bucharest, Istanbul. (Requires Going East as well!)" :pred orient-express}]} :italia {:name "Italia" :achievements [{:key :captain :name "Captain" :desc "Deliver to all Italian shipyards. (Cantiare Navale)" :pred captain} {:key :michaelangelo :name "Michaelangelo" :desc "Deliver from the Carrara quarry (Marmo SpA in Livorno)." :pred michaelangelo}]} :vive-la-france {:name "Vive la France" :achievements [{:key :go-nuclear :name "Go Nuclear" :desc "Deliver to five nuclear power plants in France. (Nucleon)" :pred go-nuclear} {:key :check-in-check-out :name "Check in, Check out" :desc "Deliver to all cargo airport terminals in France (FLE)." :pred check-in-check-out} {:key :gas-must-flow :name "Gas Must Flow" :desc "Deliver diesel, LPG or gasoline/petrol to all truck stops in France. (Eco)" :pred gas-must-flow}]} :iberia {:name "Iberia" :achievements [{:key :lets-get-shipping :name "Let's Get Shipping" :desc "Deliver to all container ports in Iberia (TS Atlas)." :pred lets-get-shipping} {:key :fleet-builder :name "Fleet Builder" :desc "Deliver to all shipyards in Iberia (Ocean Solution Group)." :pred fleet-builder} {:key :taste-the-sun :name "Taste the Sun" :desc "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." :pred taste-the-sun} {:key :iberian-pilgrimage :name "Iberian Pilgrimage" :desc "Deliver to A Coruña from Lisbon, Seville and Pamplona." :pred iberian-pilgrimage}]}}) (defn- ets-open-achievements [] true) (def ets-meta {:regions ets-regions :open ets-open-achievements})
68313
(ns ets.jobs.ets2.achievements (:require [ets.jobs.ets2.map :as map])) (defn baltic? [city-slug] (#{"EST" "FI" "LT" "LV" "RU"} (:c (map/cities city-slug)))) (defn concrete-jungle [{:keys [sender origin]}] (and (baltic? origin) (= "radus" sender))) (defn industry-standard "2 deliveries to every paper mill, loco factory, and furniture factory in the Baltic states. Those are LVR, Renat, Viljo Paperitehdas Oy, Estonian Paper AS, and VPF (lvr, renat, viljo_paper, ee_paper, viln_paper)." [{:keys [recipient]}] (#{"lvr" "renat" "viljo_paper" "ee_paper" "viln_paper"} recipient)) (def russian-main-cities #{"luga" "pskov" "petersburg" "sosnovy_bor" "vyborg"}) (defn exclave-transit "Delivery from Kaliningrad to other Russian cities." [{:keys [origin destination]}] (and (= "kaliningrad" origin) (russian-main-cities destination))) (defn like-a-farmer "Deliver to each farm in the Baltic region. Agrominta UAB (agrominta, agrominta_a; both near Utena LT) Eviksi (eviksi, eviksi_a; (double near Liepaja LV)) Maatila Egres (egres) Onnelik talu (onnelik, onnelik_a; double near Parna EST) Zelenye Polja (zelenye, zelenye_a)" [{:keys [recipient]}] (#{"agrominta" "agrominta_a" "eviksi" "eviksi_a" "egres" "onnelik" "onnelik_a" "zelenye" "zelenye_a"} recipient)) (defn turkish-delight [{:keys [origin distance]}] (and (>= distance 2500) (= "istanbul" origin))) (defn along-the-black-sea "Perfect deliveries either direction between these pairs: Istanbul-Burgas Burgas-Varna Varna-Mangalia Mangalia-Constanta" [{:keys [origin destination]}] (or (and (= origin "istanbul") (= destination "burgas")) (and (= origin "burgas") (= destination "istanbul")) (and (= origin "burgas") (= destination "varna")) (and (= origin "varna") (= destination "burgas")) (and (= origin "varna") (= destination "mangalia")) (and (= origin "mangalia") (= destination "varna")) (and (= origin "mangalia") (= destination "constanta")) (and (= origin "constanta") (= destination "mangalia")))) (defn orient-express [{:keys [origin destination]}] (or (and (= origin "paris") (= destination "strasbourg")) (and (= origin "strasbourg") (= destination "munchen")) (and (= origin "munchen") (= destination "wien")) (and (= origin "wien") (= destination "budapest")) (and (= origin "budapest") (= destination "bucuresti")) (and (= origin "bucuresti") (= destination "istanbul")))) (defn lets-get-shipping "Deliver to all container ports in Iberia (TS Atlas)." [{:keys [recipient]}] (= "ts_atlas" recipient)) (defn fleet-builder "Deliver to all shipyards in Iberia (Ocean Solution Group, ocean_sol)." [{:keys [recipient]}] (= "ocean_sol" recipient)) (defn iberian-pilgrimage "Deliver from Lisbon, Seville and Pamplona to A Coruna." [{:keys [origin destination]}] (and (= destination "a_coruna") (#{"lisboa" "sevilla" "pamplona"} origin))) (defn taste-the-sun "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." [{:keys [cargo recipient]}] (and (= "engeron" recipient) (:adr (map/cargos cargo)))) ; TODO Test this one - no jobs found. (defn volvo-trucks-lover "Deliver trucks from the Volvo factory to a dealer." [{:keys [cargo sender]}] (and (= "volvo_fac" sender) (= "trucks" cargo))) ; TODO Test this one - no jobs found. (defn scania-trucks-lover "Deliver trucks from Scania factory to a dealer." [{:keys [cargo sender]}] (and (= "scania_fac" sender) (= "trucks" cargo))) (def scandinavia-cities #{; Denmark "aalborg" "esbjerg" "frederikshavn" "gedser" "hirtshals" "kobenhavn" "odense" ; Norway "bergen" "kristiansand" "oslo" "stavanger" ; Sweden "goteborg" "helsingborg" "jonkoping" "kalmar" "kapellskar" "karlskrona" "linkoping" "malmo" "nynashamn" "orebro" "stockholm" "sodertalje" "trelleborg" "uppsala" "vasteraas" "vaxjo"}) (defn sailor "Deliver yachts to all Scandinavian marinas (marina)." [{:keys [cargo destination recipient]}] (and (scandinavia-cities destination) (= "marina" recipient) (= "yacht" cargo))) (defn cattle-drive "Complete a livestock delivery to Scandinavia." [{:keys [destination cargo]}] (and (= "livestock" cargo) (scandinavia-cities destination))) (defn whatever-floats-your-boat "Deliver to all container ports in Scandinavia (cont_port)." [{:keys [destination recipient]}] (and (= "cont_port" recipient) (scandinavia-cities destination))) (defn miner "Deliver to all quarries in Scandinavia (nord_sten, ms_stein)." [{:keys [destination recipient]}] (and (#{"nord_sten" "ms_stein"} recipient) (scandinavia-cities destination))) ; France (def french-reactors #{"civaux" "golfech" "paluel" "alban" "laurent"}) (defn go-nuclear "Deliver to 5 nuclear plants in France (nucleon)." [{:keys [destination recipient]}] (and (= "nucleon" recipient) (french-reactors destination))) (def french-airports #{"bastia" "brest" "calvi" "clermont" "montpellier" "nantes" "paris" "toulouse"}) (defn check-in-check-out "Deliver to all cargo airport terminals in France (fle, in France.)" [{:keys [destination recipient]}] (and (= "fle" recipient) (french-airports destination))) ; TODO Implement this one once I can see a "gas must flow" job. (defn gas-must-flow "Deliver petrol/gasoline, diesel, or LPG to all truck stops in France." [_] false) ; Italy (defn captain "Deliver to all Italian shipyards (c_navale)." [{:keys [recipient]}] (= "c_navale" recipient)) (defn michaelangelo "Deliver from the Carrara quarry (marmo in Livorno)." [{:keys [origin sender]}] (and (= "marmo" sender) (= "livorno" origin))) (def ^:private ets-regions {:scandinavia {:name "Scandinavia" :achievements [{:key :whatever-floats-your-boat :name "Whatever Floats Your Boat" :desc "Deliver to all container ports in Scandinavia (Container Port)." :pred whatever-floats-your-boat} {:key :sailor :name "Sailor" :desc "Deliver yachts to all Scandinavian marinas (boat symbol)." :pred sailor} {:key :volvo-trucks-lover :name "Volvo Trucks Lover" :desc "Deliver trucks from the Volvo factory." :pred volvo-trucks-lover} {:key :scania-trucks-lover :name "Scania Trucks Lover" :desc "Deliver trucks from the Scania factory." :pred scania-trucks-lover} {:key :cattle-drive :name "Cattle Drive" :desc "Complete a livestock delivery to Scandinavia." :pred cattle-drive} {:key :miner :name "Miner" :desc "Deliver to all quarries in Scandinavia (Nordic Stenbro<NAME>, MS Stein)." :pred miner}]} :baltic {:name "Beyond the Baltic Sea" :achievements [{:key :concrete-jungle :name "Concrete Jungle" :desc "Complete 10 deliveries from concrete plants (Radus, Радус)" :pred concrete-jungle} {:key :industry-standard :name "Industry Standard" :desc (str "Complete 2 deliveries to every paper mill, loco factory, and" "furniture maker in the Baltic region (LVR, Renat, Viljo " "Paperitehdas Oy, Estonian Paper AS, VPF).") :pred industry-standard} {:key :exclave-transit :name "Exclave Transit" :desc "Complete 5 deliveries from Kaliningrad to any other Russian city." :pred exclave-transit} {:key :like-a-farmer :name "Like a Farmer" :desc "Deliver to each farm in the Baltic. (Agrominta UAB, Eviksi, Maatila Egres, Onnelik Talu, Zelenye Polja)" :pred like-a-farmer}]} :black-sea {:name "Road to the Black Sea" :achievements [{:key :turkish-delight :name "Turkish Delight" :desc "Complete 3 deliveries from Istanbul which are at least 2500km long." :pred turkish-delight} {:key :along-the-black-sea :name "Along the Black Sea" :desc "Complete perfect deliveries in any order or direction between these coastal cities." :pred along-the-black-sea} {:key :orient-express :name "Orient Express" :desc "Complete deliveries between the following cities, in order: Paris, Strasbourg, Munich, Vienna, Budapest, Bucharest, Istanbul. (Requires Going East as well!)" :pred orient-express}]} :italia {:name "Italia" :achievements [{:key :captain :name "Captain" :desc "Deliver to all Italian shipyards. (Cantiare Navale)" :pred captain} {:key :michaelangelo :name "<NAME>" :desc "Deliver from the Carrara quarry (Marmo SpA in Livorno)." :pred michaelangelo}]} :vive-la-france {:name "Vive la France" :achievements [{:key :go-nuclear :name "Go Nuclear" :desc "Deliver to five nuclear power plants in France. (Nucleon)" :pred go-nuclear} {:key :check-in-check-out :name "Check in, Check out" :desc "Deliver to all cargo airport terminals in France (FLE)." :pred check-in-check-out} {:key :gas-must-flow :name "Gas Must Flow" :desc "Deliver diesel, LPG or gasoline/petrol to all truck stops in France. (Eco)" :pred gas-must-flow}]} :iberia {:name "I<NAME>ia" :achievements [{:key :lets-get-shipping :name "Let's Get Shipping" :desc "Deliver to all container ports in Iberia (TS Atlas)." :pred lets-get-shipping} {:key :fleet-builder :name "Fleet Builder" :desc "Deliver to all shipyards in Iberia (Ocean Solution Group)." :pred fleet-builder} {:key :taste-the-sun :name "Taste the Sun" :desc "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." :pred taste-the-sun} {:key :iberian-pilgrimage :name "<NAME>" :desc "Deliver to A Coruña from Lisbon, Seville and Pamplona." :pred iberian-pilgrimage}]}}) (defn- ets-open-achievements [] true) (def ets-meta {:regions ets-regions :open ets-open-achievements})
true
(ns ets.jobs.ets2.achievements (:require [ets.jobs.ets2.map :as map])) (defn baltic? [city-slug] (#{"EST" "FI" "LT" "LV" "RU"} (:c (map/cities city-slug)))) (defn concrete-jungle [{:keys [sender origin]}] (and (baltic? origin) (= "radus" sender))) (defn industry-standard "2 deliveries to every paper mill, loco factory, and furniture factory in the Baltic states. Those are LVR, Renat, Viljo Paperitehdas Oy, Estonian Paper AS, and VPF (lvr, renat, viljo_paper, ee_paper, viln_paper)." [{:keys [recipient]}] (#{"lvr" "renat" "viljo_paper" "ee_paper" "viln_paper"} recipient)) (def russian-main-cities #{"luga" "pskov" "petersburg" "sosnovy_bor" "vyborg"}) (defn exclave-transit "Delivery from Kaliningrad to other Russian cities." [{:keys [origin destination]}] (and (= "kaliningrad" origin) (russian-main-cities destination))) (defn like-a-farmer "Deliver to each farm in the Baltic region. Agrominta UAB (agrominta, agrominta_a; both near Utena LT) Eviksi (eviksi, eviksi_a; (double near Liepaja LV)) Maatila Egres (egres) Onnelik talu (onnelik, onnelik_a; double near Parna EST) Zelenye Polja (zelenye, zelenye_a)" [{:keys [recipient]}] (#{"agrominta" "agrominta_a" "eviksi" "eviksi_a" "egres" "onnelik" "onnelik_a" "zelenye" "zelenye_a"} recipient)) (defn turkish-delight [{:keys [origin distance]}] (and (>= distance 2500) (= "istanbul" origin))) (defn along-the-black-sea "Perfect deliveries either direction between these pairs: Istanbul-Burgas Burgas-Varna Varna-Mangalia Mangalia-Constanta" [{:keys [origin destination]}] (or (and (= origin "istanbul") (= destination "burgas")) (and (= origin "burgas") (= destination "istanbul")) (and (= origin "burgas") (= destination "varna")) (and (= origin "varna") (= destination "burgas")) (and (= origin "varna") (= destination "mangalia")) (and (= origin "mangalia") (= destination "varna")) (and (= origin "mangalia") (= destination "constanta")) (and (= origin "constanta") (= destination "mangalia")))) (defn orient-express [{:keys [origin destination]}] (or (and (= origin "paris") (= destination "strasbourg")) (and (= origin "strasbourg") (= destination "munchen")) (and (= origin "munchen") (= destination "wien")) (and (= origin "wien") (= destination "budapest")) (and (= origin "budapest") (= destination "bucuresti")) (and (= origin "bucuresti") (= destination "istanbul")))) (defn lets-get-shipping "Deliver to all container ports in Iberia (TS Atlas)." [{:keys [recipient]}] (= "ts_atlas" recipient)) (defn fleet-builder "Deliver to all shipyards in Iberia (Ocean Solution Group, ocean_sol)." [{:keys [recipient]}] (= "ocean_sol" recipient)) (defn iberian-pilgrimage "Deliver from Lisbon, Seville and Pamplona to A Coruna." [{:keys [origin destination]}] (and (= destination "a_coruna") (#{"lisboa" "sevilla" "pamplona"} origin))) (defn taste-the-sun "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." [{:keys [cargo recipient]}] (and (= "engeron" recipient) (:adr (map/cargos cargo)))) ; TODO Test this one - no jobs found. (defn volvo-trucks-lover "Deliver trucks from the Volvo factory to a dealer." [{:keys [cargo sender]}] (and (= "volvo_fac" sender) (= "trucks" cargo))) ; TODO Test this one - no jobs found. (defn scania-trucks-lover "Deliver trucks from Scania factory to a dealer." [{:keys [cargo sender]}] (and (= "scania_fac" sender) (= "trucks" cargo))) (def scandinavia-cities #{; Denmark "aalborg" "esbjerg" "frederikshavn" "gedser" "hirtshals" "kobenhavn" "odense" ; Norway "bergen" "kristiansand" "oslo" "stavanger" ; Sweden "goteborg" "helsingborg" "jonkoping" "kalmar" "kapellskar" "karlskrona" "linkoping" "malmo" "nynashamn" "orebro" "stockholm" "sodertalje" "trelleborg" "uppsala" "vasteraas" "vaxjo"}) (defn sailor "Deliver yachts to all Scandinavian marinas (marina)." [{:keys [cargo destination recipient]}] (and (scandinavia-cities destination) (= "marina" recipient) (= "yacht" cargo))) (defn cattle-drive "Complete a livestock delivery to Scandinavia." [{:keys [destination cargo]}] (and (= "livestock" cargo) (scandinavia-cities destination))) (defn whatever-floats-your-boat "Deliver to all container ports in Scandinavia (cont_port)." [{:keys [destination recipient]}] (and (= "cont_port" recipient) (scandinavia-cities destination))) (defn miner "Deliver to all quarries in Scandinavia (nord_sten, ms_stein)." [{:keys [destination recipient]}] (and (#{"nord_sten" "ms_stein"} recipient) (scandinavia-cities destination))) ; France (def french-reactors #{"civaux" "golfech" "paluel" "alban" "laurent"}) (defn go-nuclear "Deliver to 5 nuclear plants in France (nucleon)." [{:keys [destination recipient]}] (and (= "nucleon" recipient) (french-reactors destination))) (def french-airports #{"bastia" "brest" "calvi" "clermont" "montpellier" "nantes" "paris" "toulouse"}) (defn check-in-check-out "Deliver to all cargo airport terminals in France (fle, in France.)" [{:keys [destination recipient]}] (and (= "fle" recipient) (french-airports destination))) ; TODO Implement this one once I can see a "gas must flow" job. (defn gas-must-flow "Deliver petrol/gasoline, diesel, or LPG to all truck stops in France." [_] false) ; Italy (defn captain "Deliver to all Italian shipyards (c_navale)." [{:keys [recipient]}] (= "c_navale" recipient)) (defn michaelangelo "Deliver from the Carrara quarry (marmo in Livorno)." [{:keys [origin sender]}] (and (= "marmo" sender) (= "livorno" origin))) (def ^:private ets-regions {:scandinavia {:name "Scandinavia" :achievements [{:key :whatever-floats-your-boat :name "Whatever Floats Your Boat" :desc "Deliver to all container ports in Scandinavia (Container Port)." :pred whatever-floats-your-boat} {:key :sailor :name "Sailor" :desc "Deliver yachts to all Scandinavian marinas (boat symbol)." :pred sailor} {:key :volvo-trucks-lover :name "Volvo Trucks Lover" :desc "Deliver trucks from the Volvo factory." :pred volvo-trucks-lover} {:key :scania-trucks-lover :name "Scania Trucks Lover" :desc "Deliver trucks from the Scania factory." :pred scania-trucks-lover} {:key :cattle-drive :name "Cattle Drive" :desc "Complete a livestock delivery to Scandinavia." :pred cattle-drive} {:key :miner :name "Miner" :desc "Deliver to all quarries in Scandinavia (Nordic StenbroPI:NAME:<NAME>END_PI, MS Stein)." :pred miner}]} :baltic {:name "Beyond the Baltic Sea" :achievements [{:key :concrete-jungle :name "Concrete Jungle" :desc "Complete 10 deliveries from concrete plants (Radus, Радус)" :pred concrete-jungle} {:key :industry-standard :name "Industry Standard" :desc (str "Complete 2 deliveries to every paper mill, loco factory, and" "furniture maker in the Baltic region (LVR, Renat, Viljo " "Paperitehdas Oy, Estonian Paper AS, VPF).") :pred industry-standard} {:key :exclave-transit :name "Exclave Transit" :desc "Complete 5 deliveries from Kaliningrad to any other Russian city." :pred exclave-transit} {:key :like-a-farmer :name "Like a Farmer" :desc "Deliver to each farm in the Baltic. (Agrominta UAB, Eviksi, Maatila Egres, Onnelik Talu, Zelenye Polja)" :pred like-a-farmer}]} :black-sea {:name "Road to the Black Sea" :achievements [{:key :turkish-delight :name "Turkish Delight" :desc "Complete 3 deliveries from Istanbul which are at least 2500km long." :pred turkish-delight} {:key :along-the-black-sea :name "Along the Black Sea" :desc "Complete perfect deliveries in any order or direction between these coastal cities." :pred along-the-black-sea} {:key :orient-express :name "Orient Express" :desc "Complete deliveries between the following cities, in order: Paris, Strasbourg, Munich, Vienna, Budapest, Bucharest, Istanbul. (Requires Going East as well!)" :pred orient-express}]} :italia {:name "Italia" :achievements [{:key :captain :name "Captain" :desc "Deliver to all Italian shipyards. (Cantiare Navale)" :pred captain} {:key :michaelangelo :name "PI:NAME:<NAME>END_PI" :desc "Deliver from the Carrara quarry (Marmo SpA in Livorno)." :pred michaelangelo}]} :vive-la-france {:name "Vive la France" :achievements [{:key :go-nuclear :name "Go Nuclear" :desc "Deliver to five nuclear power plants in France. (Nucleon)" :pred go-nuclear} {:key :check-in-check-out :name "Check in, Check out" :desc "Deliver to all cargo airport terminals in France (FLE)." :pred check-in-check-out} {:key :gas-must-flow :name "Gas Must Flow" :desc "Deliver diesel, LPG or gasoline/petrol to all truck stops in France. (Eco)" :pred gas-must-flow}]} :iberia {:name "IPI:NAME:<NAME>END_PIia" :achievements [{:key :lets-get-shipping :name "Let's Get Shipping" :desc "Deliver to all container ports in Iberia (TS Atlas)." :pred lets-get-shipping} {:key :fleet-builder :name "Fleet Builder" :desc "Deliver to all shipyards in Iberia (Ocean Solution Group)." :pred fleet-builder} {:key :taste-the-sun :name "Taste the Sun" :desc "Deliver ADR cargo to all solar power plants in Iberia (Engeron)." :pred taste-the-sun} {:key :iberian-pilgrimage :name "PI:NAME:<NAME>END_PI" :desc "Deliver to A Coruña from Lisbon, Seville and Pamplona." :pred iberian-pilgrimage}]}}) (defn- ets-open-achievements [] true) (def ets-meta {:regions ets-regions :open ets-open-achievements})
[ { "context": "s))\n\n(defn -main [& args]\n (println \"Hello, World daniel\"))", "end": 84, "score": 0.728374719619751, "start": 78, "tag": "NAME", "value": "daniel" } ]
integrationtest/src/main/clojure/helloworld.clj
CoenRijsdijk/Bytecoder
543
(ns helloworld (:gen-class)) (defn -main [& args] (println "Hello, World daniel"))
12369
(ns helloworld (:gen-class)) (defn -main [& args] (println "Hello, World <NAME>"))
true
(ns helloworld (:gen-class)) (defn -main [& args] (println "Hello, World PI:NAME:<NAME>END_PI"))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998452067375183, "start": 18, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/slackbot/routes/slack_event.clj
chrisrink10/slackbot-clj
0
;; Copyright 2018 Chris Rink ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.slack-event (:require [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.karma :as karma])) (defmulti handle-event-callback (fn [{{{:keys [type channel_type subtype]} :event} :body-params}] (let [event-type (keyword type)] (if (and (= :message event-type) (nil? subtype)) :message [event-type (keyword channel_type) (keyword subtype)])))) (defmethod handle-event-callback :message [{{{:keys [channel text]} :event team-id :team_id} :body-params tx :slackbot.database/tx token :slackbot.slack/oauth-access-token}] (karma/process-karma tx token team-id channel text) (-> (response/response nil) (response/status 200))) (defmethod handle-event-callback :default [{{{event-type :type channel-type :channel_type} :event} :body-params}] (timbre/info {:message "Received unsupported event callback" :event-type event-type :channel-type channel-type}) (-> (response/response nil) (response/status 200))) (defmulti handle (fn [{{event-type :type} :body-params}] (keyword event-type))) (defmethod handle :url_verification [{{:keys [challenge]} :body-params}] (-> challenge (response/response) (response/status 200) (response/content-type "text/plain"))) (defmethod handle :event_callback [req] (handle-event-callback req)) (defmethod handle :default [{{event-type :type} :body-params}] (timbre/info {:message "Received unsupported event" :event-type event-type}) (-> (response/response nil) (response/status 200)))
104613
;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.slack-event (:require [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.karma :as karma])) (defmulti handle-event-callback (fn [{{{:keys [type channel_type subtype]} :event} :body-params}] (let [event-type (keyword type)] (if (and (= :message event-type) (nil? subtype)) :message [event-type (keyword channel_type) (keyword subtype)])))) (defmethod handle-event-callback :message [{{{:keys [channel text]} :event team-id :team_id} :body-params tx :slackbot.database/tx token :slackbot.slack/oauth-access-token}] (karma/process-karma tx token team-id channel text) (-> (response/response nil) (response/status 200))) (defmethod handle-event-callback :default [{{{event-type :type channel-type :channel_type} :event} :body-params}] (timbre/info {:message "Received unsupported event callback" :event-type event-type :channel-type channel-type}) (-> (response/response nil) (response/status 200))) (defmulti handle (fn [{{event-type :type} :body-params}] (keyword event-type))) (defmethod handle :url_verification [{{:keys [challenge]} :body-params}] (-> challenge (response/response) (response/status 200) (response/content-type "text/plain"))) (defmethod handle :event_callback [req] (handle-event-callback req)) (defmethod handle :default [{{event-type :type} :body-params}] (timbre/info {:message "Received unsupported event" :event-type event-type}) (-> (response/response nil) (response/status 200)))
true
;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns slackbot.routes.slack-event (:require [ring.util.response :as response] [taoensso.timbre :as timbre] [slackbot.karma :as karma])) (defmulti handle-event-callback (fn [{{{:keys [type channel_type subtype]} :event} :body-params}] (let [event-type (keyword type)] (if (and (= :message event-type) (nil? subtype)) :message [event-type (keyword channel_type) (keyword subtype)])))) (defmethod handle-event-callback :message [{{{:keys [channel text]} :event team-id :team_id} :body-params tx :slackbot.database/tx token :slackbot.slack/oauth-access-token}] (karma/process-karma tx token team-id channel text) (-> (response/response nil) (response/status 200))) (defmethod handle-event-callback :default [{{{event-type :type channel-type :channel_type} :event} :body-params}] (timbre/info {:message "Received unsupported event callback" :event-type event-type :channel-type channel-type}) (-> (response/response nil) (response/status 200))) (defmulti handle (fn [{{event-type :type} :body-params}] (keyword event-type))) (defmethod handle :url_verification [{{:keys [challenge]} :body-params}] (-> challenge (response/response) (response/status 200) (response/content-type "text/plain"))) (defmethod handle :event_callback [req] (handle-event-callback req)) (defmethod handle :default [{{event-type :type} :body-params}] (timbre/info {:message "Received unsupported event" :event-type event-type}) (-> (response/response nil) (response/status 200)))
[ { "context": " :name name\n :password password}))))\n\n(defn- get-event-session-for-code [tracker-", "end": 3173, "score": 0.9984085559844971, "start": 3165, "tag": "PASSWORD", "value": "password" } ]
src/ruuvi_server/database/event_dao.clj
RuuviTracker/ruuvitracker_server
1
(ns ruuvi-server.database.event-dao (:require [ruuvi-server.configuration :as conf] [ruuvi-server.util :as util] [clojure.string :as string] [ruuvi-server.cache :as cache] [clojure.java.jdbc :as sql] ) (:use [korma.db :only (transaction)] [korma.core :only (select where insert update values set-fields with limit order fields)] [ruuvi-server.database.entities :only (tracker event event-session event-extension-type event-extension-value event-location event-annotation)] [clj-time.core :only (date-time now)] [clj-time.coerce :only (to-timestamp)] [clojure.string :only (join)] [clojure.tools.logging :only (debug info warn error)] ) (:import [org.joda.time DateTime]) ) (defn- get-pk "Fetch primary key from just inserted row." [insert-result] ;; scope_identity is for H2 (some insert-result [:id (keyword "SCOPE_IDENTITY()") (keyword "scope_identity()")])) (defn- current-sql-timestamp [] (to-timestamp (now))) (defn get-trackers [ids] (select tracker (where (in :id ids)))) (defn get-tracker-by-code [tracker-code] (let [tracker-code (string/lower-case tracker-code)] (first (select tracker (where {:tracker_code tracker-code}))))) ;; TODO add caching (defn get-tracker-by-code! [tracker-code & tracker-name] (util/try-times 1 (let [tracker-code (string/lower-case tracker-code) existing-tracker (get-tracker-by-code tracker-code)] (if existing-tracker existing-tracker (insert tracker (values {:tracker_code tracker-code :name (or tracker-name tracker-code)})))))) ;; TODO needed (defn get-all-trackers [] (select tracker) ) (defn get-tracker [id] ;; TODO support also fetching with tracker_indentifier? ;; duplicate with get-trackers (first (select tracker (where {:id id})))) ;; TODO bad API (defn get-event-sessions [{:keys [tracker_ids event_session_ids]}] (let [tracker-ids-crit (when tracker_ids {:tracker_id ['in tracker_ids]}) session-ids-crit (when event_session_ids {:id ['in event_session_ids]}) conditions (filter identity (list tracker-ids-crit session-ids-crit))] (select event-session (where (apply and conditions))))) (defn- update-tracker-latest-activity [id] (update tracker (set-fields {:latest_activity (java.sql.Timestamp. (System/currentTimeMillis)) }) (where {:id id}))) (defn create-tracker [code name shared-secret password] (let [tracker-code (string/lower-case code)] (info "Create new tracker" name "(" tracker-code ")") (insert tracker (values {:tracker_code tracker-code :shared_secret shared-secret :name name :password password})))) (defn- get-event-session-for-code [tracker-id session-code] (first (select event-session (where {:tracker_id tracker-id :session_code session-code}))) ) (defn- get-event-session-for-code! [tracker-id session-code & timestamp] (util/try-times 1 (let [existing-session (get-event-session-for-code tracker-id session-code)] (if existing-session ;; update latest timestamp, if timestamp != null existing-session (insert event-session (values {:tracker_id tracker-id :session_code session-code :first_event_time timestamp :latest_event_time timestamp})))) )) (defn get-extension-type-by-id [id] (first (select event-extension-type (where {:name id})))) (defn get-extension-type-by-name [type-name] (first (select event-extension-type (where {:name (str (name type-name))})))) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extra-data 10000 (* 24 60 60 1000))) ;; TODO add caching (defn get-extension-type-by-name! [type-name] (util/try-times 1 (let [existing-extension-type (get-extension-type-by-name type-name)] (if existing-extension-type existing-extension-type (insert event-extension-type (values {:name (str (name type-name)) :description "Autogenerated"})) )))) (defn get-event [event_id] (first (select event (with tracker) (with event-location) (with event-extension-value) (where {:id event_id}))) ) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extension-type 10000 (* 24 60 60 1000))) ;; TODO cache access to event-extension-type (defn- get-event-extra-data [event-id] {:event_locations (select event-location (where {:event_id event-id})) :event_extension_values (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id event-id})) } ) (defn- max-search-result-size "Maximum number of events to return in event search" [conf criteria] (let [allowed-max-result-count (get-in conf [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in conf [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) ] result-limit)) ;; {:where "where a = ? and c = ?" :params [1 "2"]} (defn make-sql-crit [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (filter identity (:trackerIds criteria)) session-ids (filter identity (:sessionIds criteria)) params (filter identity (flatten [event-start event-end store-start store-end tracker-ids session-ids])) conds '[] conds (conj conds (when event-start "e.event_time >= ?")) conds (conj conds (when event-end "e.event_time <= ?")) conds (conj conds (when store-start "e.created_on >= ?")) conds (conj conds (when store-end "e.created_on <= ?")) conds (conj conds (when (not (empty? tracker-ids)) (let [tracker-id-binds (join "," (repeat (count tracker-ids) "?"))] (str "e.tracker_id in (" tracker-id-binds ")")))) conds (conj conds (when (not (empty? session-ids)) (let [session-id-binds (join "," (repeat (count session-ids) "?"))] (str "e.event_session_id in (" session-id-binds ")")))) conds (filter identity conds) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) "order by e.created_on desc" (= order-by-crit :latest-event-time) "order by e.event_time desc" :default "order by e.event_time asc") ] {:params params :conds (join " and " conds) :order-by order-by} )) (defn- make-search-results [rows] (map (fn [row] (let [event-data (select-keys row [:id :tracker_id :event_session_id :created_on :event_time]) loc-data (select-keys row [:latitude :longitude :speed :satellite_count :heading :altitude :horizontal_accuracy :vertical_accuracy]) event-id (:id event-data) extension-values (cache/lookup cache-event-extra-data event-id (fn [id] (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id id})))) ] (merge event-data {:event_locations [loc-data] :event_extension_values extension-values} ))) rows)) (defn search-events "Pure JDBC implementation of search" [criteria] (let [result-limit (max-search-result-size (conf/get-config) criteria) conn (get-in (conf/get-config) [:database]) opts {:result-type :forward-only :concurrency :read-only :fetch-size (min 1000 result-limit) :max-rows result-limit } conditions (make-sql-crit criteria) ] (if (not (empty? (:conds conditions))) (sql/with-connection conn (let [sql (str "select e.*, l.* from events e " "left outer join event_locations l on (e.id = l.event_id) " "where " (:conds conditions) " " (:order-by conditions) " limit " result-limit) params (:params conditions) sql-params (into [] (concat [opts sql] params)) ] (apply sql/with-query-results* [sql-params #(doall (make-search-results %))]) )) '()))) (defn search-events-2 "Search events: criteria is a map that can contain following keys. - :storeTimeStart <DateTime>, find events that are created (stored) to database later than given time (inclusive). - :storeTimeEnd <DateTime>, find events that are created (stored) to database earlier than given time (inclusive). - :eventTimeStart <DateTime>, find events that are created in tracker later than given time (inclusive). - :eventTimeEnd <DateTime>, find events that are created in tracker earlier than given time (inclusive). - :maxResults <Integer>, maximum number of events. Default and maximum is 50. TODO calculates milliseconds wrong (12:30:01.000 is rounded to 12:30:01 but 12:30:01.001 is rounded to 12:30:02) " [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (:trackerIds criteria) session-ids (:sessionIds criteria) allowed-max-result-count (get-in (conf/get-config) [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in (conf/get-config) [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) tracker-ids-crit (when tracker-ids {:tracker_id ['in tracker-ids]}) session-ids-crit (when session-ids {:event_session_id ['in session-ids]}) event-start-crit (when event-start {:event_time ['>= event-start]}) event-end-crit (when event-end {:event_time ['<= event-end]}) store-start-crit (when store-start {:created_on ['>= store-start]}) store-end-crit (when store-end {:created_on ['<= store-end]}) conditions (filter identity (list event-start-crit event-end-crit store-start-crit store-end-crit tracker-ids-crit session-ids-crit)) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) [:created_on :DESC] (= order-by-crit :latest-event-time) [:event_time :DESC] :default [:event_time :ASC]) ] (if (not (empty? conditions)) (let [results (select event (where (apply and conditions)) (order (order-by 0) (order-by 1)) (limit result-limit)) ] (map (fn [event] (let [event-id (:id event) extra-data (cache/lookup cache-event-extra-data event-id get-event-extra-data)] (merge event extra-data) )) results) ) '() ))) (defn get-events [ids] (select event (with event-location) (with event-extension-value (with event-extension-type (fields :name))) (where (in :id ids)) )) (defn get-all-events [] (select event (with event-location) (with event-extension-value) )) (defn create-event [data] (transaction (let [event-time (or (to-timestamp (:event_time data)) (current-sql-timestamp)) tracker (get-tracker-by-code! (:tracker_code data)) tracker-id (get-pk tracker) ;; TODO trim session_code to length of db field session-code (or (:session_code data) "default") event-session (get-event-session-for-code! tracker-id session-code event-time) event-session-id (get-pk event-session)] (update-tracker-latest-activity tracker-id) (let [extension-keys (filter (fn [key] (.startsWith (str (name key)) "X-")) (keys data)) latitude (:latitude data) longitude (:longitude data) event-entity (insert event (values {:tracker_id tracker-id :event_session_id event-session-id :event_time event-time })) event-id (get-pk event-entity) location-entity (when (and latitude longitude) (insert event-location (values {:event_id event-id :latitude latitude :longitude longitude :horizontal_accuracy (:horizontal_accuracy data) :vertical_accuracy (:vertical_accuracy data) :speed (:speed data) :heading (:heading data) :satellite_count (:satellite_count data) :altitude (:altitude data)}))) annotation-entity (when-let [annotation (:annotation data)] ;; TODO cut too long annotation value to match db field (insert event-annotation (values {:event_id event-id :annotation annotation}))) extension-entities (map (fn [key] (let [value-entity (insert event-extension-value (values {:event_id event-id :value (data key) :event_extension_type_id (:id (get-extension-type-by-name! key)) } ))] (select-keys (merge value-entity {:name key}) [:name :value]) )) extension-keys) ] ;; reconstruct event-entity to be same as entities returned by ;; search ;; TODO h2 db is not returning correct values when inserting, ;; so put event-id and tracker-id to result (merge event-entity {:event_locations (when location-entity [location-entity]) :event_annotations (when annotation-entity [annotation-entity]) :event_extension_values extension-entities :id event-id :tracker_id tracker-id}) ))))
44098
(ns ruuvi-server.database.event-dao (:require [ruuvi-server.configuration :as conf] [ruuvi-server.util :as util] [clojure.string :as string] [ruuvi-server.cache :as cache] [clojure.java.jdbc :as sql] ) (:use [korma.db :only (transaction)] [korma.core :only (select where insert update values set-fields with limit order fields)] [ruuvi-server.database.entities :only (tracker event event-session event-extension-type event-extension-value event-location event-annotation)] [clj-time.core :only (date-time now)] [clj-time.coerce :only (to-timestamp)] [clojure.string :only (join)] [clojure.tools.logging :only (debug info warn error)] ) (:import [org.joda.time DateTime]) ) (defn- get-pk "Fetch primary key from just inserted row." [insert-result] ;; scope_identity is for H2 (some insert-result [:id (keyword "SCOPE_IDENTITY()") (keyword "scope_identity()")])) (defn- current-sql-timestamp [] (to-timestamp (now))) (defn get-trackers [ids] (select tracker (where (in :id ids)))) (defn get-tracker-by-code [tracker-code] (let [tracker-code (string/lower-case tracker-code)] (first (select tracker (where {:tracker_code tracker-code}))))) ;; TODO add caching (defn get-tracker-by-code! [tracker-code & tracker-name] (util/try-times 1 (let [tracker-code (string/lower-case tracker-code) existing-tracker (get-tracker-by-code tracker-code)] (if existing-tracker existing-tracker (insert tracker (values {:tracker_code tracker-code :name (or tracker-name tracker-code)})))))) ;; TODO needed (defn get-all-trackers [] (select tracker) ) (defn get-tracker [id] ;; TODO support also fetching with tracker_indentifier? ;; duplicate with get-trackers (first (select tracker (where {:id id})))) ;; TODO bad API (defn get-event-sessions [{:keys [tracker_ids event_session_ids]}] (let [tracker-ids-crit (when tracker_ids {:tracker_id ['in tracker_ids]}) session-ids-crit (when event_session_ids {:id ['in event_session_ids]}) conditions (filter identity (list tracker-ids-crit session-ids-crit))] (select event-session (where (apply and conditions))))) (defn- update-tracker-latest-activity [id] (update tracker (set-fields {:latest_activity (java.sql.Timestamp. (System/currentTimeMillis)) }) (where {:id id}))) (defn create-tracker [code name shared-secret password] (let [tracker-code (string/lower-case code)] (info "Create new tracker" name "(" tracker-code ")") (insert tracker (values {:tracker_code tracker-code :shared_secret shared-secret :name name :password <PASSWORD>})))) (defn- get-event-session-for-code [tracker-id session-code] (first (select event-session (where {:tracker_id tracker-id :session_code session-code}))) ) (defn- get-event-session-for-code! [tracker-id session-code & timestamp] (util/try-times 1 (let [existing-session (get-event-session-for-code tracker-id session-code)] (if existing-session ;; update latest timestamp, if timestamp != null existing-session (insert event-session (values {:tracker_id tracker-id :session_code session-code :first_event_time timestamp :latest_event_time timestamp})))) )) (defn get-extension-type-by-id [id] (first (select event-extension-type (where {:name id})))) (defn get-extension-type-by-name [type-name] (first (select event-extension-type (where {:name (str (name type-name))})))) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extra-data 10000 (* 24 60 60 1000))) ;; TODO add caching (defn get-extension-type-by-name! [type-name] (util/try-times 1 (let [existing-extension-type (get-extension-type-by-name type-name)] (if existing-extension-type existing-extension-type (insert event-extension-type (values {:name (str (name type-name)) :description "Autogenerated"})) )))) (defn get-event [event_id] (first (select event (with tracker) (with event-location) (with event-extension-value) (where {:id event_id}))) ) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extension-type 10000 (* 24 60 60 1000))) ;; TODO cache access to event-extension-type (defn- get-event-extra-data [event-id] {:event_locations (select event-location (where {:event_id event-id})) :event_extension_values (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id event-id})) } ) (defn- max-search-result-size "Maximum number of events to return in event search" [conf criteria] (let [allowed-max-result-count (get-in conf [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in conf [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) ] result-limit)) ;; {:where "where a = ? and c = ?" :params [1 "2"]} (defn make-sql-crit [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (filter identity (:trackerIds criteria)) session-ids (filter identity (:sessionIds criteria)) params (filter identity (flatten [event-start event-end store-start store-end tracker-ids session-ids])) conds '[] conds (conj conds (when event-start "e.event_time >= ?")) conds (conj conds (when event-end "e.event_time <= ?")) conds (conj conds (when store-start "e.created_on >= ?")) conds (conj conds (when store-end "e.created_on <= ?")) conds (conj conds (when (not (empty? tracker-ids)) (let [tracker-id-binds (join "," (repeat (count tracker-ids) "?"))] (str "e.tracker_id in (" tracker-id-binds ")")))) conds (conj conds (when (not (empty? session-ids)) (let [session-id-binds (join "," (repeat (count session-ids) "?"))] (str "e.event_session_id in (" session-id-binds ")")))) conds (filter identity conds) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) "order by e.created_on desc" (= order-by-crit :latest-event-time) "order by e.event_time desc" :default "order by e.event_time asc") ] {:params params :conds (join " and " conds) :order-by order-by} )) (defn- make-search-results [rows] (map (fn [row] (let [event-data (select-keys row [:id :tracker_id :event_session_id :created_on :event_time]) loc-data (select-keys row [:latitude :longitude :speed :satellite_count :heading :altitude :horizontal_accuracy :vertical_accuracy]) event-id (:id event-data) extension-values (cache/lookup cache-event-extra-data event-id (fn [id] (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id id})))) ] (merge event-data {:event_locations [loc-data] :event_extension_values extension-values} ))) rows)) (defn search-events "Pure JDBC implementation of search" [criteria] (let [result-limit (max-search-result-size (conf/get-config) criteria) conn (get-in (conf/get-config) [:database]) opts {:result-type :forward-only :concurrency :read-only :fetch-size (min 1000 result-limit) :max-rows result-limit } conditions (make-sql-crit criteria) ] (if (not (empty? (:conds conditions))) (sql/with-connection conn (let [sql (str "select e.*, l.* from events e " "left outer join event_locations l on (e.id = l.event_id) " "where " (:conds conditions) " " (:order-by conditions) " limit " result-limit) params (:params conditions) sql-params (into [] (concat [opts sql] params)) ] (apply sql/with-query-results* [sql-params #(doall (make-search-results %))]) )) '()))) (defn search-events-2 "Search events: criteria is a map that can contain following keys. - :storeTimeStart <DateTime>, find events that are created (stored) to database later than given time (inclusive). - :storeTimeEnd <DateTime>, find events that are created (stored) to database earlier than given time (inclusive). - :eventTimeStart <DateTime>, find events that are created in tracker later than given time (inclusive). - :eventTimeEnd <DateTime>, find events that are created in tracker earlier than given time (inclusive). - :maxResults <Integer>, maximum number of events. Default and maximum is 50. TODO calculates milliseconds wrong (12:30:01.000 is rounded to 12:30:01 but 12:30:01.001 is rounded to 12:30:02) " [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (:trackerIds criteria) session-ids (:sessionIds criteria) allowed-max-result-count (get-in (conf/get-config) [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in (conf/get-config) [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) tracker-ids-crit (when tracker-ids {:tracker_id ['in tracker-ids]}) session-ids-crit (when session-ids {:event_session_id ['in session-ids]}) event-start-crit (when event-start {:event_time ['>= event-start]}) event-end-crit (when event-end {:event_time ['<= event-end]}) store-start-crit (when store-start {:created_on ['>= store-start]}) store-end-crit (when store-end {:created_on ['<= store-end]}) conditions (filter identity (list event-start-crit event-end-crit store-start-crit store-end-crit tracker-ids-crit session-ids-crit)) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) [:created_on :DESC] (= order-by-crit :latest-event-time) [:event_time :DESC] :default [:event_time :ASC]) ] (if (not (empty? conditions)) (let [results (select event (where (apply and conditions)) (order (order-by 0) (order-by 1)) (limit result-limit)) ] (map (fn [event] (let [event-id (:id event) extra-data (cache/lookup cache-event-extra-data event-id get-event-extra-data)] (merge event extra-data) )) results) ) '() ))) (defn get-events [ids] (select event (with event-location) (with event-extension-value (with event-extension-type (fields :name))) (where (in :id ids)) )) (defn get-all-events [] (select event (with event-location) (with event-extension-value) )) (defn create-event [data] (transaction (let [event-time (or (to-timestamp (:event_time data)) (current-sql-timestamp)) tracker (get-tracker-by-code! (:tracker_code data)) tracker-id (get-pk tracker) ;; TODO trim session_code to length of db field session-code (or (:session_code data) "default") event-session (get-event-session-for-code! tracker-id session-code event-time) event-session-id (get-pk event-session)] (update-tracker-latest-activity tracker-id) (let [extension-keys (filter (fn [key] (.startsWith (str (name key)) "X-")) (keys data)) latitude (:latitude data) longitude (:longitude data) event-entity (insert event (values {:tracker_id tracker-id :event_session_id event-session-id :event_time event-time })) event-id (get-pk event-entity) location-entity (when (and latitude longitude) (insert event-location (values {:event_id event-id :latitude latitude :longitude longitude :horizontal_accuracy (:horizontal_accuracy data) :vertical_accuracy (:vertical_accuracy data) :speed (:speed data) :heading (:heading data) :satellite_count (:satellite_count data) :altitude (:altitude data)}))) annotation-entity (when-let [annotation (:annotation data)] ;; TODO cut too long annotation value to match db field (insert event-annotation (values {:event_id event-id :annotation annotation}))) extension-entities (map (fn [key] (let [value-entity (insert event-extension-value (values {:event_id event-id :value (data key) :event_extension_type_id (:id (get-extension-type-by-name! key)) } ))] (select-keys (merge value-entity {:name key}) [:name :value]) )) extension-keys) ] ;; reconstruct event-entity to be same as entities returned by ;; search ;; TODO h2 db is not returning correct values when inserting, ;; so put event-id and tracker-id to result (merge event-entity {:event_locations (when location-entity [location-entity]) :event_annotations (when annotation-entity [annotation-entity]) :event_extension_values extension-entities :id event-id :tracker_id tracker-id}) ))))
true
(ns ruuvi-server.database.event-dao (:require [ruuvi-server.configuration :as conf] [ruuvi-server.util :as util] [clojure.string :as string] [ruuvi-server.cache :as cache] [clojure.java.jdbc :as sql] ) (:use [korma.db :only (transaction)] [korma.core :only (select where insert update values set-fields with limit order fields)] [ruuvi-server.database.entities :only (tracker event event-session event-extension-type event-extension-value event-location event-annotation)] [clj-time.core :only (date-time now)] [clj-time.coerce :only (to-timestamp)] [clojure.string :only (join)] [clojure.tools.logging :only (debug info warn error)] ) (:import [org.joda.time DateTime]) ) (defn- get-pk "Fetch primary key from just inserted row." [insert-result] ;; scope_identity is for H2 (some insert-result [:id (keyword "SCOPE_IDENTITY()") (keyword "scope_identity()")])) (defn- current-sql-timestamp [] (to-timestamp (now))) (defn get-trackers [ids] (select tracker (where (in :id ids)))) (defn get-tracker-by-code [tracker-code] (let [tracker-code (string/lower-case tracker-code)] (first (select tracker (where {:tracker_code tracker-code}))))) ;; TODO add caching (defn get-tracker-by-code! [tracker-code & tracker-name] (util/try-times 1 (let [tracker-code (string/lower-case tracker-code) existing-tracker (get-tracker-by-code tracker-code)] (if existing-tracker existing-tracker (insert tracker (values {:tracker_code tracker-code :name (or tracker-name tracker-code)})))))) ;; TODO needed (defn get-all-trackers [] (select tracker) ) (defn get-tracker [id] ;; TODO support also fetching with tracker_indentifier? ;; duplicate with get-trackers (first (select tracker (where {:id id})))) ;; TODO bad API (defn get-event-sessions [{:keys [tracker_ids event_session_ids]}] (let [tracker-ids-crit (when tracker_ids {:tracker_id ['in tracker_ids]}) session-ids-crit (when event_session_ids {:id ['in event_session_ids]}) conditions (filter identity (list tracker-ids-crit session-ids-crit))] (select event-session (where (apply and conditions))))) (defn- update-tracker-latest-activity [id] (update tracker (set-fields {:latest_activity (java.sql.Timestamp. (System/currentTimeMillis)) }) (where {:id id}))) (defn create-tracker [code name shared-secret password] (let [tracker-code (string/lower-case code)] (info "Create new tracker" name "(" tracker-code ")") (insert tracker (values {:tracker_code tracker-code :shared_secret shared-secret :name name :password PI:PASSWORD:<PASSWORD>END_PI})))) (defn- get-event-session-for-code [tracker-id session-code] (first (select event-session (where {:tracker_id tracker-id :session_code session-code}))) ) (defn- get-event-session-for-code! [tracker-id session-code & timestamp] (util/try-times 1 (let [existing-session (get-event-session-for-code tracker-id session-code)] (if existing-session ;; update latest timestamp, if timestamp != null existing-session (insert event-session (values {:tracker_id tracker-id :session_code session-code :first_event_time timestamp :latest_event_time timestamp})))) )) (defn get-extension-type-by-id [id] (first (select event-extension-type (where {:name id})))) (defn get-extension-type-by-name [type-name] (first (select event-extension-type (where {:name (str (name type-name))})))) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extra-data 10000 (* 24 60 60 1000))) ;; TODO add caching (defn get-extension-type-by-name! [type-name] (util/try-times 1 (let [existing-extension-type (get-extension-type-by-name type-name)] (if existing-extension-type existing-extension-type (insert event-extension-type (values {:name (str (name type-name)) :description "Autogenerated"})) )))) (defn get-event [event_id] (first (select event (with tracker) (with event-location) (with event-extension-value) (where {:id event_id}))) ) (def ^{:private true} cache-event-extra-data (cache/create-cache-region :event-extension-type 10000 (* 24 60 60 1000))) ;; TODO cache access to event-extension-type (defn- get-event-extra-data [event-id] {:event_locations (select event-location (where {:event_id event-id})) :event_extension_values (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id event-id})) } ) (defn- max-search-result-size "Maximum number of events to return in event search" [conf criteria] (let [allowed-max-result-count (get-in conf [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in conf [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) ] result-limit)) ;; {:where "where a = ? and c = ?" :params [1 "2"]} (defn make-sql-crit [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (filter identity (:trackerIds criteria)) session-ids (filter identity (:sessionIds criteria)) params (filter identity (flatten [event-start event-end store-start store-end tracker-ids session-ids])) conds '[] conds (conj conds (when event-start "e.event_time >= ?")) conds (conj conds (when event-end "e.event_time <= ?")) conds (conj conds (when store-start "e.created_on >= ?")) conds (conj conds (when store-end "e.created_on <= ?")) conds (conj conds (when (not (empty? tracker-ids)) (let [tracker-id-binds (join "," (repeat (count tracker-ids) "?"))] (str "e.tracker_id in (" tracker-id-binds ")")))) conds (conj conds (when (not (empty? session-ids)) (let [session-id-binds (join "," (repeat (count session-ids) "?"))] (str "e.event_session_id in (" session-id-binds ")")))) conds (filter identity conds) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) "order by e.created_on desc" (= order-by-crit :latest-event-time) "order by e.event_time desc" :default "order by e.event_time asc") ] {:params params :conds (join " and " conds) :order-by order-by} )) (defn- make-search-results [rows] (map (fn [row] (let [event-data (select-keys row [:id :tracker_id :event_session_id :created_on :event_time]) loc-data (select-keys row [:latitude :longitude :speed :satellite_count :heading :altitude :horizontal_accuracy :vertical_accuracy]) event-id (:id event-data) extension-values (cache/lookup cache-event-extra-data event-id (fn [id] (select event-extension-value (fields :value) (with event-extension-type (fields :name)) (where {:event_id id})))) ] (merge event-data {:event_locations [loc-data] :event_extension_values extension-values} ))) rows)) (defn search-events "Pure JDBC implementation of search" [criteria] (let [result-limit (max-search-result-size (conf/get-config) criteria) conn (get-in (conf/get-config) [:database]) opts {:result-type :forward-only :concurrency :read-only :fetch-size (min 1000 result-limit) :max-rows result-limit } conditions (make-sql-crit criteria) ] (if (not (empty? (:conds conditions))) (sql/with-connection conn (let [sql (str "select e.*, l.* from events e " "left outer join event_locations l on (e.id = l.event_id) " "where " (:conds conditions) " " (:order-by conditions) " limit " result-limit) params (:params conditions) sql-params (into [] (concat [opts sql] params)) ] (apply sql/with-query-results* [sql-params #(doall (make-search-results %))]) )) '()))) (defn search-events-2 "Search events: criteria is a map that can contain following keys. - :storeTimeStart <DateTime>, find events that are created (stored) to database later than given time (inclusive). - :storeTimeEnd <DateTime>, find events that are created (stored) to database earlier than given time (inclusive). - :eventTimeStart <DateTime>, find events that are created in tracker later than given time (inclusive). - :eventTimeEnd <DateTime>, find events that are created in tracker earlier than given time (inclusive). - :maxResults <Integer>, maximum number of events. Default and maximum is 50. TODO calculates milliseconds wrong (12:30:01.000 is rounded to 12:30:01 but 12:30:01.001 is rounded to 12:30:02) " [criteria] (let [event-start (to-timestamp (:eventTimeStart criteria)) event-end (to-timestamp (:eventTimeEnd criteria)) store-start (to-timestamp (:storeTimeStart criteria)) store-end (to-timestamp (:storeTimeEnd criteria)) tracker-ids (:trackerIds criteria) session-ids (:sessionIds criteria) allowed-max-result-count (get-in (conf/get-config) [:client-api :allowed-max-search-results] ) max-results (if (:maxResults criteria) (:maxResults criteria) (get-in (conf/get-config) [:client-api :default-max-search-results] 100)) result-limit (apply min (filter identity [allowed-max-result-count max-results])) tracker-ids-crit (when tracker-ids {:tracker_id ['in tracker-ids]}) session-ids-crit (when session-ids {:event_session_id ['in session-ids]}) event-start-crit (when event-start {:event_time ['>= event-start]}) event-end-crit (when event-end {:event_time ['<= event-end]}) store-start-crit (when store-start {:created_on ['>= store-start]}) store-end-crit (when store-end {:created_on ['<= store-end]}) conditions (filter identity (list event-start-crit event-end-crit store-start-crit store-end-crit tracker-ids-crit session-ids-crit)) order-by-crit (:orderBy criteria) order-by (cond (= order-by-crit :latest-store-time) [:created_on :DESC] (= order-by-crit :latest-event-time) [:event_time :DESC] :default [:event_time :ASC]) ] (if (not (empty? conditions)) (let [results (select event (where (apply and conditions)) (order (order-by 0) (order-by 1)) (limit result-limit)) ] (map (fn [event] (let [event-id (:id event) extra-data (cache/lookup cache-event-extra-data event-id get-event-extra-data)] (merge event extra-data) )) results) ) '() ))) (defn get-events [ids] (select event (with event-location) (with event-extension-value (with event-extension-type (fields :name))) (where (in :id ids)) )) (defn get-all-events [] (select event (with event-location) (with event-extension-value) )) (defn create-event [data] (transaction (let [event-time (or (to-timestamp (:event_time data)) (current-sql-timestamp)) tracker (get-tracker-by-code! (:tracker_code data)) tracker-id (get-pk tracker) ;; TODO trim session_code to length of db field session-code (or (:session_code data) "default") event-session (get-event-session-for-code! tracker-id session-code event-time) event-session-id (get-pk event-session)] (update-tracker-latest-activity tracker-id) (let [extension-keys (filter (fn [key] (.startsWith (str (name key)) "X-")) (keys data)) latitude (:latitude data) longitude (:longitude data) event-entity (insert event (values {:tracker_id tracker-id :event_session_id event-session-id :event_time event-time })) event-id (get-pk event-entity) location-entity (when (and latitude longitude) (insert event-location (values {:event_id event-id :latitude latitude :longitude longitude :horizontal_accuracy (:horizontal_accuracy data) :vertical_accuracy (:vertical_accuracy data) :speed (:speed data) :heading (:heading data) :satellite_count (:satellite_count data) :altitude (:altitude data)}))) annotation-entity (when-let [annotation (:annotation data)] ;; TODO cut too long annotation value to match db field (insert event-annotation (values {:event_id event-id :annotation annotation}))) extension-entities (map (fn [key] (let [value-entity (insert event-extension-value (values {:event_id event-id :value (data key) :event_extension_type_id (:id (get-extension-type-by-name! key)) } ))] (select-keys (merge value-entity {:name key}) [:name :value]) )) extension-keys) ] ;; reconstruct event-entity to be same as entities returned by ;; search ;; TODO h2 db is not returning correct values when inserting, ;; so put event-id and tracker-id to result (merge event-entity {:event_locations (when location-entity [location-entity]) :event_annotations (when annotation-entity [annotation-entity]) :event_extension_values extension-entities :id event-id :tracker_id tracker-id}) ))))
[ { "context": "s/forName \"org.h2.Driver\")\n (let [host \"127.0.0.1\"\n username \"sa\"\n password ", "end": 211, "score": 0.9997227787971497, "start": 202, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "t [host \"127.0.0.1\"\n username \"sa\"\n password nil\n conn-string ", "end": 238, "score": 0.9943525195121765, "start": 236, "tag": "USERNAME", "value": "sa" }, { "context": "\"\n username \"sa\"\n password nil\n conn-string (str \"jdbc:h2:tcp://\" host ", "end": 265, "score": 0.9129592180252075, "start": 262, "tag": "PASSWORD", "value": "nil" } ]
src/db_compare/db/h2.clj
mmcgrana/db-compare
0
(ns db-compare.db.h2 (:use (clojure.contrib [def :only (defvar-)]) (db-compare.db sql))) (defvar- h2-custom-impl { :init (fn [] (Class/forName "org.h2.Driver") (let [host "127.0.0.1" username "sa" password nil conn-string (str "jdbc:h2:tcp://" host "/benchdb;MULTI_THREADED=1")] {:host host :conn-string conn-string})) }) (def h2-impl (merge sql-impl h2-custom-impl))
22646
(ns db-compare.db.h2 (:use (clojure.contrib [def :only (defvar-)]) (db-compare.db sql))) (defvar- h2-custom-impl { :init (fn [] (Class/forName "org.h2.Driver") (let [host "127.0.0.1" username "sa" password <PASSWORD> conn-string (str "jdbc:h2:tcp://" host "/benchdb;MULTI_THREADED=1")] {:host host :conn-string conn-string})) }) (def h2-impl (merge sql-impl h2-custom-impl))
true
(ns db-compare.db.h2 (:use (clojure.contrib [def :only (defvar-)]) (db-compare.db sql))) (defvar- h2-custom-impl { :init (fn [] (Class/forName "org.h2.Driver") (let [host "127.0.0.1" username "sa" password PI:PASSWORD:<PASSWORD>END_PI conn-string (str "jdbc:h2:tcp://" host "/benchdb;MULTI_THREADED=1")] {:host host :conn-string conn-string})) }) (def h2-impl (merge sql-impl h2-custom-impl))
[ { "context": "(ns ^{:author \"Adam Berger\"} ulvm.fileserver\n \"Fileserver\"\n (:require [org", "end": 26, "score": 0.9998579621315002, "start": 15, "tag": "NAME", "value": "Adam Berger" } ]
src/ulvm/fileserver.clj
abrgr/ulvm
0
(ns ^{:author "Adam Berger"} ulvm.fileserver "Fileserver" (:require [org.httpkit.server :as h] [compojure.core :as c] [clojure.java.io :as io] [clojure.string :as string] [cats.core :as m] [cats.monad.either :as e] [ulvm.aws-auth :as aws-auth] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [ulvm.env-keypaths :as k]) (:import [java.net URI])) (defn- read-all [rdr size] (let [buf (char-array size)] (loop [offset 0] (let [bytes-read (.read rdr buf offset (- size offset)) total-read (+ offset bytes-read)] (cond (< bytes-read 0) buf (< total-read size) (recur total-read) :else buf))))) (defn- next-chunk "Reads chunked s3 uploads as described in: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html#sigv4-chunked-body-definition" [rdr] (let [preamble (.readLine rdr) [hex-size sig] (string/split preamble #";") size (Integer/parseInt hex-size 16)] (if (= 0 size) nil (read-all rdr size)))) (defn- store-obj "Store an object" [scopes {:keys [body verified-path]}] (let [file (io/file verified-path) rdr (io/reader body)] (->> file (.getParentFile) (.mkdirs)) (with-open [w (io/writer file)] (loop [buf (next-chunk rdr)] (when (some? buf) (.write w buf 0 (count buf))))) {:status 200})) (defn- get-obj "Get an object" [scopes {:keys [verified-path]}] {:status 200 :body (io/file verified-path)}) (defn- named-delimited-parts [name delim s] (-> s (string/replace-first (re-pattern (str "^" name)) "") (string/split (re-pattern delim)))) (defn- auth-parts [auth] (let [[method cred ssv-signed-headers sig] (string/split auth #" |, ") [access-key date region service _] (named-delimited-parts "Credential=" "/" cred) signed-headers (named-delimited-parts "SignedHeaders=" ";" ssv-signed-headers)] {:method method :access-key access-key :date date :region region :service service :signed-headers signed-headers :sig (string/replace-first sig #"^Signature=" "")})) (defn- resolve-bucket [req] (->> (get-in req [:headers "host"]) (re-matches #"^([^.]+)[.].*") (second))) (defn- path-prefix? [prefix path] (if (or (nil? prefix) (nil? path)) false (string/starts-with? path prefix))) (defn- with-verified-req [prj req scope-name app] (futil/mlet e/context [scopes (get-in prj [:entities :ulvm.core/scopes]) scope (get scopes scope-name) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) path (-> req (:uri) (URI.) (.getPath) (io/file) (.getCanonicalPath)) expected-src (get scope-cfg :ulvm.scopes/gen-src-dir) expected-build (get scope-cfg :ulvm.scopes/build-dir) valid-path? (or (path-prefix? expected-src path) (path-prefix? expected-build path))] (if (and (some? scope) valid-path?) (e/right (app (merge req {:verified-scope scope :verified-path path}))) (e/left "Unauthorized")))) (defn- verify-auth [prj app] (fn [req] (m/extract (m/bimap #(do (println "Unauthorized request" req %) {:status 403 :body "Unauthorized"}) identity (futil/mlet e/context [{:keys [headers uri request-method]} req auth-header (get headers "authorization") auth (auth-parts auth-header) req-method (-> request-method name string/upper-case) bucket (resolve-bucket req) scope-name (keyword bucket) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) secret (get scope-cfg :ulvm.scopes/fs-secret) calculated-auth (aws-auth/aws4-auth req-method uri headers (get auth :signed-headers) (get auth :region) "s3" (get auth :access-key) secret)] (if (= calculated-auth auth-header) (with-verified-req prj req scope-name app) (e/left "Unauthorized"))))))) (defn- routes [prj] (c/routes (c/POST "/*" [] (partial store-obj prj)) (c/PUT "/*" [] (partial store-obj prj)) (c/GET "/*" [] (partial get-obj prj)))) (defn- app [prj] (->> (routes prj) (verify-auth prj))) (defn start-server [prj] (futil/mlet e/context [uri (uprj/get-env prj (k/fileserver-base-uri)) port (->> uri (URI.) (.getPort))] (e/right (h/run-server (app prj) {:port port})))) (defmacro with-fs "Runs a local fileserver to accept requests from any scopes defined in project. Returns a function that will stop the fileserver." [prj & forms] `(futil/mlet e/context [stop-server# (start-server ~prj) res# (do ~@forms)] (stop-server#) (futil/lift-either res#)))
78168
(ns ^{:author "<NAME>"} ulvm.fileserver "Fileserver" (:require [org.httpkit.server :as h] [compojure.core :as c] [clojure.java.io :as io] [clojure.string :as string] [cats.core :as m] [cats.monad.either :as e] [ulvm.aws-auth :as aws-auth] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [ulvm.env-keypaths :as k]) (:import [java.net URI])) (defn- read-all [rdr size] (let [buf (char-array size)] (loop [offset 0] (let [bytes-read (.read rdr buf offset (- size offset)) total-read (+ offset bytes-read)] (cond (< bytes-read 0) buf (< total-read size) (recur total-read) :else buf))))) (defn- next-chunk "Reads chunked s3 uploads as described in: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html#sigv4-chunked-body-definition" [rdr] (let [preamble (.readLine rdr) [hex-size sig] (string/split preamble #";") size (Integer/parseInt hex-size 16)] (if (= 0 size) nil (read-all rdr size)))) (defn- store-obj "Store an object" [scopes {:keys [body verified-path]}] (let [file (io/file verified-path) rdr (io/reader body)] (->> file (.getParentFile) (.mkdirs)) (with-open [w (io/writer file)] (loop [buf (next-chunk rdr)] (when (some? buf) (.write w buf 0 (count buf))))) {:status 200})) (defn- get-obj "Get an object" [scopes {:keys [verified-path]}] {:status 200 :body (io/file verified-path)}) (defn- named-delimited-parts [name delim s] (-> s (string/replace-first (re-pattern (str "^" name)) "") (string/split (re-pattern delim)))) (defn- auth-parts [auth] (let [[method cred ssv-signed-headers sig] (string/split auth #" |, ") [access-key date region service _] (named-delimited-parts "Credential=" "/" cred) signed-headers (named-delimited-parts "SignedHeaders=" ";" ssv-signed-headers)] {:method method :access-key access-key :date date :region region :service service :signed-headers signed-headers :sig (string/replace-first sig #"^Signature=" "")})) (defn- resolve-bucket [req] (->> (get-in req [:headers "host"]) (re-matches #"^([^.]+)[.].*") (second))) (defn- path-prefix? [prefix path] (if (or (nil? prefix) (nil? path)) false (string/starts-with? path prefix))) (defn- with-verified-req [prj req scope-name app] (futil/mlet e/context [scopes (get-in prj [:entities :ulvm.core/scopes]) scope (get scopes scope-name) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) path (-> req (:uri) (URI.) (.getPath) (io/file) (.getCanonicalPath)) expected-src (get scope-cfg :ulvm.scopes/gen-src-dir) expected-build (get scope-cfg :ulvm.scopes/build-dir) valid-path? (or (path-prefix? expected-src path) (path-prefix? expected-build path))] (if (and (some? scope) valid-path?) (e/right (app (merge req {:verified-scope scope :verified-path path}))) (e/left "Unauthorized")))) (defn- verify-auth [prj app] (fn [req] (m/extract (m/bimap #(do (println "Unauthorized request" req %) {:status 403 :body "Unauthorized"}) identity (futil/mlet e/context [{:keys [headers uri request-method]} req auth-header (get headers "authorization") auth (auth-parts auth-header) req-method (-> request-method name string/upper-case) bucket (resolve-bucket req) scope-name (keyword bucket) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) secret (get scope-cfg :ulvm.scopes/fs-secret) calculated-auth (aws-auth/aws4-auth req-method uri headers (get auth :signed-headers) (get auth :region) "s3" (get auth :access-key) secret)] (if (= calculated-auth auth-header) (with-verified-req prj req scope-name app) (e/left "Unauthorized"))))))) (defn- routes [prj] (c/routes (c/POST "/*" [] (partial store-obj prj)) (c/PUT "/*" [] (partial store-obj prj)) (c/GET "/*" [] (partial get-obj prj)))) (defn- app [prj] (->> (routes prj) (verify-auth prj))) (defn start-server [prj] (futil/mlet e/context [uri (uprj/get-env prj (k/fileserver-base-uri)) port (->> uri (URI.) (.getPort))] (e/right (h/run-server (app prj) {:port port})))) (defmacro with-fs "Runs a local fileserver to accept requests from any scopes defined in project. Returns a function that will stop the fileserver." [prj & forms] `(futil/mlet e/context [stop-server# (start-server ~prj) res# (do ~@forms)] (stop-server#) (futil/lift-either res#)))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.fileserver "Fileserver" (:require [org.httpkit.server :as h] [compojure.core :as c] [clojure.java.io :as io] [clojure.string :as string] [cats.core :as m] [cats.monad.either :as e] [ulvm.aws-auth :as aws-auth] [ulvm.project :as uprj] [ulvm.func-utils :as futil] [ulvm.env-keypaths :as k]) (:import [java.net URI])) (defn- read-all [rdr size] (let [buf (char-array size)] (loop [offset 0] (let [bytes-read (.read rdr buf offset (- size offset)) total-read (+ offset bytes-read)] (cond (< bytes-read 0) buf (< total-read size) (recur total-read) :else buf))))) (defn- next-chunk "Reads chunked s3 uploads as described in: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html#sigv4-chunked-body-definition" [rdr] (let [preamble (.readLine rdr) [hex-size sig] (string/split preamble #";") size (Integer/parseInt hex-size 16)] (if (= 0 size) nil (read-all rdr size)))) (defn- store-obj "Store an object" [scopes {:keys [body verified-path]}] (let [file (io/file verified-path) rdr (io/reader body)] (->> file (.getParentFile) (.mkdirs)) (with-open [w (io/writer file)] (loop [buf (next-chunk rdr)] (when (some? buf) (.write w buf 0 (count buf))))) {:status 200})) (defn- get-obj "Get an object" [scopes {:keys [verified-path]}] {:status 200 :body (io/file verified-path)}) (defn- named-delimited-parts [name delim s] (-> s (string/replace-first (re-pattern (str "^" name)) "") (string/split (re-pattern delim)))) (defn- auth-parts [auth] (let [[method cred ssv-signed-headers sig] (string/split auth #" |, ") [access-key date region service _] (named-delimited-parts "Credential=" "/" cred) signed-headers (named-delimited-parts "SignedHeaders=" ";" ssv-signed-headers)] {:method method :access-key access-key :date date :region region :service service :signed-headers signed-headers :sig (string/replace-first sig #"^Signature=" "")})) (defn- resolve-bucket [req] (->> (get-in req [:headers "host"]) (re-matches #"^([^.]+)[.].*") (second))) (defn- path-prefix? [prefix path] (if (or (nil? prefix) (nil? path)) false (string/starts-with? path prefix))) (defn- with-verified-req [prj req scope-name app] (futil/mlet e/context [scopes (get-in prj [:entities :ulvm.core/scopes]) scope (get scopes scope-name) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) path (-> req (:uri) (URI.) (.getPath) (io/file) (.getCanonicalPath)) expected-src (get scope-cfg :ulvm.scopes/gen-src-dir) expected-build (get scope-cfg :ulvm.scopes/build-dir) valid-path? (or (path-prefix? expected-src path) (path-prefix? expected-build path))] (if (and (some? scope) valid-path?) (e/right (app (merge req {:verified-scope scope :verified-path path}))) (e/left "Unauthorized")))) (defn- verify-auth [prj app] (fn [req] (m/extract (m/bimap #(do (println "Unauthorized request" req %) {:status 403 :body "Unauthorized"}) identity (futil/mlet e/context [{:keys [headers uri request-method]} req auth-header (get headers "authorization") auth (auth-parts auth-header) req-method (-> request-method name string/upper-case) bucket (resolve-bucket req) scope-name (keyword bucket) scope-cfg (uprj/get-env prj (k/scope-config-keypath scope-name)) secret (get scope-cfg :ulvm.scopes/fs-secret) calculated-auth (aws-auth/aws4-auth req-method uri headers (get auth :signed-headers) (get auth :region) "s3" (get auth :access-key) secret)] (if (= calculated-auth auth-header) (with-verified-req prj req scope-name app) (e/left "Unauthorized"))))))) (defn- routes [prj] (c/routes (c/POST "/*" [] (partial store-obj prj)) (c/PUT "/*" [] (partial store-obj prj)) (c/GET "/*" [] (partial get-obj prj)))) (defn- app [prj] (->> (routes prj) (verify-auth prj))) (defn start-server [prj] (futil/mlet e/context [uri (uprj/get-env prj (k/fileserver-base-uri)) port (->> uri (URI.) (.getPort))] (e/right (h/run-server (app prj) {:port port})))) (defmacro with-fs "Runs a local fileserver to accept requests from any scopes defined in project. Returns a function that will stop the fileserver." [prj & forms] `(futil/mlet e/context [stop-server# (start-server ~prj) res# (do ~@forms)] (stop-server#) (futil/lift-either res#)))
[ { "context": ";; Copyright 2018 Chris Rink\n;;\n;; Licensed under the Apache License, Version ", "end": 28, "score": 0.9998441338539124, "start": 18, "tag": "NAME", "value": "Chris Rink" }, { "context": " \" by \"\n [:a {:href \"https://crink.io\"} \"Chris Rink\"]\n \". \"\n \"The source code is lice", "end": 2553, "score": 0.9998414516448975, "start": 2543, "tag": "NAME", "value": "Chris Rink" } ]
src/clojure/repopreview/template.clj
chrisrink10/repopreview
0
;; Copyright 2018 Chris Rink ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.template (:import com.google.common.io.Files) (:require [clojure.string :as str])) (def special-files {"dockerfile" "lang-docker" "makefile" "lang-makefile" "cmakelists.txt" "lang-cmake"}) (defn file-ext [filename] (-> (Files/getFileExtension filename) (str/lower-case))) (defn guess-css-class "Very roughly guess what CSS class should be applied to highlight a given file using the file extension and a few very simple heuristics for known common filenames which do not typically have extensions." [filename] (let [filename-lower (str/lower-case filename) extension (file-ext filename)] (cond (contains? special-files filename-lower) (get special-files filename-lower) (not (str/blank? extension)) (str "lang-" extension) :else "nohighlight"))) (defn code-file [{:keys [name sha content]}] (let [code-css-class (guess-css-class name)] [:div [:h4 {:id (str "file-" sha) :class "title is-4"} name] [:pre [:code (when code-css-class {:class code-css-class}) content]]])) (defn page [{:keys [title header content links scripts]}] `[:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title ~title] [:link {:rel "stylesheet" :type "text/css" :href "//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css" :integrity "sha256-2k1KVsNPRXxZOsXQ8aqcZ9GOOwmJTMoOB5o5Qp1d6/s=" :crossorigin "anonymous"}] ~@links] [:body ~header [:section {:class "section"} ~content] [:footer {:class "footer"} [:div {:class "container"} [:div {:class "content has-text-centered"} [:p [:strong "Repo Summary"] " by " [:a {:href "https://crink.io"} "Chris Rink"] ". " "The source code is licensed " [:a {:ref "http://opensource.org/licenses/mit-license.php"} "MIT"] "."]]]] [:script {:defer true :src "//use.fontawesome.com/releases/v5.0.6/js/all.js"}] ~@scripts]]) (defn header ([title] (header title nil)) ([title subtitle] (header title subtitle :dark)) ([title subtitle style] (let [style-class (case style :warning "is-warning" :danger "is-danger" "is-dark")] [:section {:class (str "hero " style-class)} [:div {:class "hero-body"} [:div {:class "container"} [:h1 {:class "title"} title] (when (some? subtitle) [:h2 {:class "subtitle"} subtitle])]]])))
56841
;; Copyright 2018 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.template (:import com.google.common.io.Files) (:require [clojure.string :as str])) (def special-files {"dockerfile" "lang-docker" "makefile" "lang-makefile" "cmakelists.txt" "lang-cmake"}) (defn file-ext [filename] (-> (Files/getFileExtension filename) (str/lower-case))) (defn guess-css-class "Very roughly guess what CSS class should be applied to highlight a given file using the file extension and a few very simple heuristics for known common filenames which do not typically have extensions." [filename] (let [filename-lower (str/lower-case filename) extension (file-ext filename)] (cond (contains? special-files filename-lower) (get special-files filename-lower) (not (str/blank? extension)) (str "lang-" extension) :else "nohighlight"))) (defn code-file [{:keys [name sha content]}] (let [code-css-class (guess-css-class name)] [:div [:h4 {:id (str "file-" sha) :class "title is-4"} name] [:pre [:code (when code-css-class {:class code-css-class}) content]]])) (defn page [{:keys [title header content links scripts]}] `[:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title ~title] [:link {:rel "stylesheet" :type "text/css" :href "//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css" :integrity "sha256-2k1KVsNPRXxZOsXQ8aqcZ9GOOwmJTMoOB5o5Qp1d6/s=" :crossorigin "anonymous"}] ~@links] [:body ~header [:section {:class "section"} ~content] [:footer {:class "footer"} [:div {:class "container"} [:div {:class "content has-text-centered"} [:p [:strong "Repo Summary"] " by " [:a {:href "https://crink.io"} "<NAME>"] ". " "The source code is licensed " [:a {:ref "http://opensource.org/licenses/mit-license.php"} "MIT"] "."]]]] [:script {:defer true :src "//use.fontawesome.com/releases/v5.0.6/js/all.js"}] ~@scripts]]) (defn header ([title] (header title nil)) ([title subtitle] (header title subtitle :dark)) ([title subtitle style] (let [style-class (case style :warning "is-warning" :danger "is-danger" "is-dark")] [:section {:class (str "hero " style-class)} [:div {:class "hero-body"} [:div {:class "container"} [:h1 {:class "title"} title] (when (some? subtitle) [:h2 {:class "subtitle"} subtitle])]]])))
true
;; Copyright 2018 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns repopreview.template (:import com.google.common.io.Files) (:require [clojure.string :as str])) (def special-files {"dockerfile" "lang-docker" "makefile" "lang-makefile" "cmakelists.txt" "lang-cmake"}) (defn file-ext [filename] (-> (Files/getFileExtension filename) (str/lower-case))) (defn guess-css-class "Very roughly guess what CSS class should be applied to highlight a given file using the file extension and a few very simple heuristics for known common filenames which do not typically have extensions." [filename] (let [filename-lower (str/lower-case filename) extension (file-ext filename)] (cond (contains? special-files filename-lower) (get special-files filename-lower) (not (str/blank? extension)) (str "lang-" extension) :else "nohighlight"))) (defn code-file [{:keys [name sha content]}] (let [code-css-class (guess-css-class name)] [:div [:h4 {:id (str "file-" sha) :class "title is-4"} name] [:pre [:code (when code-css-class {:class code-css-class}) content]]])) (defn page [{:keys [title header content links scripts]}] `[:html [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title ~title] [:link {:rel "stylesheet" :type "text/css" :href "//cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css" :integrity "sha256-2k1KVsNPRXxZOsXQ8aqcZ9GOOwmJTMoOB5o5Qp1d6/s=" :crossorigin "anonymous"}] ~@links] [:body ~header [:section {:class "section"} ~content] [:footer {:class "footer"} [:div {:class "container"} [:div {:class "content has-text-centered"} [:p [:strong "Repo Summary"] " by " [:a {:href "https://crink.io"} "PI:NAME:<NAME>END_PI"] ". " "The source code is licensed " [:a {:ref "http://opensource.org/licenses/mit-license.php"} "MIT"] "."]]]] [:script {:defer true :src "//use.fontawesome.com/releases/v5.0.6/js/all.js"}] ~@scripts]]) (defn header ([title] (header title nil)) ([title subtitle] (header title subtitle :dark)) ([title subtitle style] (let [style-class (case style :warning "is-warning" :danger "is-danger" "is-dark")] [:section {:class (str "hero " style-class)} [:div {:class "hero-body"} [:div {:class "container"} [:h1 {:class "title"} title] (when (some? subtitle) [:h2 {:class "subtitle"} subtitle])]]])))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.test.niou.core\n\n", "end": 597, "score": 0.9998575448989868, "start": 584, "tag": "NAME", "value": "Kenneth Leung" }, { "context": "(ensure?? \"normalize-email\"\n (.equals \"abc@abc.com\" (mi/normalize-email \"abc@ABC.cOm\")))\n\n (ensure?", "end": 14044, "score": 0.9999009370803833, "start": 14033, "tag": "EMAIL", "value": "abc@abc.com" }, { "context": " (.equals \"abc@abc.com\" (mi/normalize-email \"abc@ABC.cOm\")))\n\n (ensure?? \"is-signed?\"\n (mi/is-", "end": 14078, "score": 0.9839863777160645, "start": 14067, "tag": "EMAIL", "value": "abc@ABC.cOm" } ]
src/test/clojure/czlab/test/niou/core.clj
llnek/nettio
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.test.niou.core (:require [czlab.test.niou.mock :as m] [czlab.niou.webss :as ws] [czlab.niou.routes :as r] [czlab.niou.util :as ct] [czlab.niou.mime :as mi] [czlab.niou.core :as cc] [czlab.niou.upload :as cu] [clojure.string :as cs] [clojure.test :as t] [czlab.basal.io :as i] [czlab.basal.core :as c :refer [ensure?? ensure-thrown??]]) (:import [java.net HttpCookie URL URI] [czlab.basal XData] [czlab.niou Headers] [org.apache.commons.fileupload FileItem])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- phone-agents {:winphone " Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) " :safari_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17 " :chrome_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.155 Safari/537.22 " :ffox_linux " Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0 " :ie_win " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0) " :chrome_win " Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 " :kindle " Mozilla/5.0 (Linux; U; en-us; KFTT Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Silk/2.8 Safari/535.19 Silk-Accelerated=true " :iphone " Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipad " Mozilla/5.0 (iPad; CPU OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipod " Mozilla/5.0 (iPod; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :android_galaxy " Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; SAMSUNG-SGH-I747 Build/JRO03L) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 "}) (c/def- pkeybytes (i/x->bytes "mocker")) (c/def- ROUTES [{:XXXhandler "p1" :pattern "/{a}/{b}" :groups {:a "[a-z]+" :b "[0-9]+"} :verb :post :name :r1 :extras {:template "t1.html"}} {:pattern "/{yo}" :name :r2 :groups {:yo "favicon\\..+"}} {:XXXhandler "p2" :pattern "/{a}/zzz/{b}/c/{d}" :name :r3 :groups {:a "[A]+" :b "[B]+" :d "[D]+"} :verb :get} {:name :g1 :pattern "/a/{b}/c/{d}/e/{f}" :groups {:b "[a-z]+" :d "[0-9]+" :f "[A-Z]+"}} {:pattern "/4"}]) (c/def- RC (r/route-cracker<> ROUTES)) ;(println "routes = " (i/fmt->edn RC)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval '(mi/setup-cache (i/res->url "czlab/niou/etc/mime.properties"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- ^Headers HEADERS (doto (Headers.) (.add "he" "x") (.set "ha" "y") (.add "yo" "a") (.add "yo" "b"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-core (ensure?? "gist-header?" (and (.containsKey HEADERS "Yo") (not (.containsKey HEADERS "o")))) (ensure?? "gist-header" (.equals "a" (.getFirst HEADERS "yo"))) (ensure?? "gist-header-keys" (let [s (into #{} (.keySet HEADERS))] (and (contains? s "yo") (contains? s "he") (contains? s "ha")))) (ensure?? "gist-header-vals" (= ["a" "b"] (vec (.get HEADERS "yo")))) (ensure?? "init-test" (> (count ROUTES) 0)) (ensure?? "has-routes?" (r/has-routes? RC)) (ensure?? "parse-path" (let [[p c g] (r/regex-path "/{a}/{z}/{b}/c/{d}" {:a "foo" :b "man" :d "chu" :z nil})] (and (== 5 c) (== 1 (:a g)) (== 2 (:z g)) (== 3 (:b g)) (== 4 (:d g)) (.equals "/(foo)/([^/]+)/(man)/c/(chu)" p)))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/hello/007" :request-method :post})] (and R (= :r1 (:name info)) (.equals "hello" (:a params)) (.equals "007" (:b params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/favicon.hello" :request-method :get})] (and R (== 1 (count params)) (.equals "favicon.hello" (:yo params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/AAA/zzz/BBB/c/DDD" :request-method :get})] (and (== 3 (count params)) (.equals "AAA" (:a params)) (.equals "BBB" (:b params)) (.equals "DDD" (:d params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/4" :request-method :get})] (and info (empty? params)))) (ensure?? "crack-route" (nil? (r/crack-route RC {:request-method :get :uri "/1/1/1/1/1/1/14"}))) ;:pattern "/a/{b}/c/{d}/e/{f}" (ensure?? "gen-route/nil" (nil? (r/gen-route RC :ggg {}))) (ensure-thrown?? "gen-route/params" :any (r/gen-route RC :g1 {:d "911" :f "XYZ"})) (ensure-thrown?? "gen-route/malform" :any (r/gen-route RC :g1 {:b "xyz" :d "XXX" :f "XYZ"})) (ensure?? "gen-route/ok" (.equals "/a/xyz/c/911/e/XYZ" (first (r/gen-route RC :g1 {:b "xyz" :d "911" :f "XYZ"})))) (ensure?? "parse-form-post" (let [b (XData. cu/TEST-FORM-MULTIPART) gist {:clen (.size b) :ctype "multipart/form-data; boundary=---1234"} out (cu/parse-form-post gist b) rmap (when out (c/preduce<map> #(let [^FileItem i %2] (if-not (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getString i))) (.getString i)))) (cu/get-all-items out))) fmap (when out (c/preduce<map> #(let [^FileItem i %2] (if (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getName i))) (i/x->str (.get i))))) (cu/get-all-items out)))] (and (.equals "fieldValue" (:field+fieldValue rmap)) (.equals "value1" (:multi+value1 rmap)) (.equals "value2" (:multi+value2 rmap)) (.equals "file content(1)\n" (:file1+foo1.tab fmap)) (.equals "file content(2)\n" (:file2+foo2.tab fmap))))) (ensure?? "downstream" (let [req (m/mock-http-request pkeybytes false) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) c (get cs ws/session-cookie) v (.getValue ^HttpCookie c)] (== 6 (count (.split v "="))))) (ensure?? "upstream" (let [req (m/mock-http-request pkeybytes true) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) s (ws/upstream pkeybytes cs true)] (ws/validate?? s) (and (not (ws/is-session-null? s)) (not (ws/is-session-new? s))))) (ensure?? "parse-ie" (some? (ct/parse-ie (:winphone phone-agents)))) (ensure?? "parse-ie" (nil? (ct/parse-ie "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ie_win phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:winphone phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_osx phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_win phone-agents)))) (ensure?? "parse-chrome" (nil? (ct/parse-chrome "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_osx phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_win phone-agents)))) (ensure?? "parse-kindle" (some? (ct/parse-kindle (:kindle phone-agents)))) (ensure?? "parse-kindle" (nil? (ct/parse-kindle "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:kindle phone-agents)))) (ensure?? "parse-android" (some? (ct/parse-android (:android_galaxy phone-agents)))) (ensure?? "parse-android" (nil? (ct/parse-android "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:android_galaxy phone-agents)))) (ensure?? "parse-ffox" (some? (ct/parse-ffox (:ffox_linux phone-agents)))) (ensure?? "parse-ffox" (nil? (ct/parse-ffox "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ffox_linux phone-agents)))) (ensure?? "parse-safari" (some? (ct/parse-safari (:safari_osx phone-agents)))) (ensure?? "parse-safari" (nil? (ct/parse-safari "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:safari_osx phone-agents)))) (ensure?? "generate-nonce" (c/hgl? (ct/generate-nonce))) (ensure?? "generate-csrf" (c/hgl? (ct/generate-csrf))) (ensure?? "parse-basic-auth" (let [{:keys [principal credential]} (ct/parse-basic-auth " Basic QWxhZGRpbjpPcGVuU2VzYW1l ")] (and (.equals "Aladdin" principal) (.equals "OpenSesame" credential)))) (ensure?? "form-items<>" (let [bag (-> (cu/form-items<>) (cu/add-item (cu/file-item<> true "" nil "a1" "" nil)) (cu/add-item (cu/file-item<> false "" nil "f1" "" nil)) (cu/add-item (cu/file-item<> true "" nil "a2" "" nil)))] (and (== 1 (count (cu/get-all-files bag))) (== 2 (count (cu/get-all-fields bag)))))) (ensure?? "file-item<>" (let [f (cu/file-item<> true "" nil "a1" "" (XData. "hello")) b (.get f) n (.getFieldName f) f? (.isFormField f) s (.getString f) m? (.isInMemory f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (some? i) (.equals "a1" n) f? (.equals "hello" s) m?))) (ensure?? "file-item<>" (let [f (cu/file-item<> false "text/plain" nil "f1" "a.txt" (XData. "hello")) b (.get f) n (.getFieldName f) ct (.getContentType f) f? (not (.isFormField f)) s (.getString f) m? (.isInMemory f) nn (.getName f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (.equals "text/plain" ct) (some? i) (.equals "f1" n) (.equals "a.txt" nn) f? (.equals "hello" s) m?))) (ensure?? "mime-cache<>" (map? (mi/mime-cache<>))) (ensure?? "charset??" (.equals "utf-16" (mi/charset?? "text/plain; charset=utf-16"))) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx@@@ddddd")) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx")) (ensure?? "normalize-email" (.equals "abc@abc.com" (mi/normalize-email "abc@ABC.cOm"))) (ensure?? "is-signed?" (mi/is-signed? "saljas application/x-pkcs7-mime laslasdf lksalfkla multipart/signed signed-data ")) (ensure?? "is-encrypted?" (mi/is-encrypted? "saljas laslasdf lksalfkla application/x-pkcs7-mime enveloped-data ")) (ensure?? "is-compressed?" (mi/is-compressed? "saljas laslasdf lksalfkla application/pkcs7-mime compressed-data")) (ensure?? "is-mdn?" (mi/is-mdn? "saljas laslasdf lksalfkla multipart/report disposition-notification ")) (ensure?? "guess-mime-type" (cs/includes? (mi/guess-mime-type "/tmp/abc.jpeg") "image/")) (ensure?? "guess-content-type" (cs/includes? (mi/guess-content-type "/tmp/abc.pdf") "/pdf")) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (t/deftest ^:test-niou niou-test-core (t/is (c/clj-test?? test-core))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
71678
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.test.niou.core (:require [czlab.test.niou.mock :as m] [czlab.niou.webss :as ws] [czlab.niou.routes :as r] [czlab.niou.util :as ct] [czlab.niou.mime :as mi] [czlab.niou.core :as cc] [czlab.niou.upload :as cu] [clojure.string :as cs] [clojure.test :as t] [czlab.basal.io :as i] [czlab.basal.core :as c :refer [ensure?? ensure-thrown??]]) (:import [java.net HttpCookie URL URI] [czlab.basal XData] [czlab.niou Headers] [org.apache.commons.fileupload FileItem])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- phone-agents {:winphone " Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) " :safari_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17 " :chrome_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.155 Safari/537.22 " :ffox_linux " Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0 " :ie_win " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0) " :chrome_win " Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 " :kindle " Mozilla/5.0 (Linux; U; en-us; KFTT Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Silk/2.8 Safari/535.19 Silk-Accelerated=true " :iphone " Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipad " Mozilla/5.0 (iPad; CPU OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipod " Mozilla/5.0 (iPod; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :android_galaxy " Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; SAMSUNG-SGH-I747 Build/JRO03L) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 "}) (c/def- pkeybytes (i/x->bytes "mocker")) (c/def- ROUTES [{:XXXhandler "p1" :pattern "/{a}/{b}" :groups {:a "[a-z]+" :b "[0-9]+"} :verb :post :name :r1 :extras {:template "t1.html"}} {:pattern "/{yo}" :name :r2 :groups {:yo "favicon\\..+"}} {:XXXhandler "p2" :pattern "/{a}/zzz/{b}/c/{d}" :name :r3 :groups {:a "[A]+" :b "[B]+" :d "[D]+"} :verb :get} {:name :g1 :pattern "/a/{b}/c/{d}/e/{f}" :groups {:b "[a-z]+" :d "[0-9]+" :f "[A-Z]+"}} {:pattern "/4"}]) (c/def- RC (r/route-cracker<> ROUTES)) ;(println "routes = " (i/fmt->edn RC)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval '(mi/setup-cache (i/res->url "czlab/niou/etc/mime.properties"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- ^Headers HEADERS (doto (Headers.) (.add "he" "x") (.set "ha" "y") (.add "yo" "a") (.add "yo" "b"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-core (ensure?? "gist-header?" (and (.containsKey HEADERS "Yo") (not (.containsKey HEADERS "o")))) (ensure?? "gist-header" (.equals "a" (.getFirst HEADERS "yo"))) (ensure?? "gist-header-keys" (let [s (into #{} (.keySet HEADERS))] (and (contains? s "yo") (contains? s "he") (contains? s "ha")))) (ensure?? "gist-header-vals" (= ["a" "b"] (vec (.get HEADERS "yo")))) (ensure?? "init-test" (> (count ROUTES) 0)) (ensure?? "has-routes?" (r/has-routes? RC)) (ensure?? "parse-path" (let [[p c g] (r/regex-path "/{a}/{z}/{b}/c/{d}" {:a "foo" :b "man" :d "chu" :z nil})] (and (== 5 c) (== 1 (:a g)) (== 2 (:z g)) (== 3 (:b g)) (== 4 (:d g)) (.equals "/(foo)/([^/]+)/(man)/c/(chu)" p)))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/hello/007" :request-method :post})] (and R (= :r1 (:name info)) (.equals "hello" (:a params)) (.equals "007" (:b params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/favicon.hello" :request-method :get})] (and R (== 1 (count params)) (.equals "favicon.hello" (:yo params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/AAA/zzz/BBB/c/DDD" :request-method :get})] (and (== 3 (count params)) (.equals "AAA" (:a params)) (.equals "BBB" (:b params)) (.equals "DDD" (:d params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/4" :request-method :get})] (and info (empty? params)))) (ensure?? "crack-route" (nil? (r/crack-route RC {:request-method :get :uri "/1/1/1/1/1/1/14"}))) ;:pattern "/a/{b}/c/{d}/e/{f}" (ensure?? "gen-route/nil" (nil? (r/gen-route RC :ggg {}))) (ensure-thrown?? "gen-route/params" :any (r/gen-route RC :g1 {:d "911" :f "XYZ"})) (ensure-thrown?? "gen-route/malform" :any (r/gen-route RC :g1 {:b "xyz" :d "XXX" :f "XYZ"})) (ensure?? "gen-route/ok" (.equals "/a/xyz/c/911/e/XYZ" (first (r/gen-route RC :g1 {:b "xyz" :d "911" :f "XYZ"})))) (ensure?? "parse-form-post" (let [b (XData. cu/TEST-FORM-MULTIPART) gist {:clen (.size b) :ctype "multipart/form-data; boundary=---1234"} out (cu/parse-form-post gist b) rmap (when out (c/preduce<map> #(let [^FileItem i %2] (if-not (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getString i))) (.getString i)))) (cu/get-all-items out))) fmap (when out (c/preduce<map> #(let [^FileItem i %2] (if (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getName i))) (i/x->str (.get i))))) (cu/get-all-items out)))] (and (.equals "fieldValue" (:field+fieldValue rmap)) (.equals "value1" (:multi+value1 rmap)) (.equals "value2" (:multi+value2 rmap)) (.equals "file content(1)\n" (:file1+foo1.tab fmap)) (.equals "file content(2)\n" (:file2+foo2.tab fmap))))) (ensure?? "downstream" (let [req (m/mock-http-request pkeybytes false) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) c (get cs ws/session-cookie) v (.getValue ^HttpCookie c)] (== 6 (count (.split v "="))))) (ensure?? "upstream" (let [req (m/mock-http-request pkeybytes true) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) s (ws/upstream pkeybytes cs true)] (ws/validate?? s) (and (not (ws/is-session-null? s)) (not (ws/is-session-new? s))))) (ensure?? "parse-ie" (some? (ct/parse-ie (:winphone phone-agents)))) (ensure?? "parse-ie" (nil? (ct/parse-ie "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ie_win phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:winphone phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_osx phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_win phone-agents)))) (ensure?? "parse-chrome" (nil? (ct/parse-chrome "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_osx phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_win phone-agents)))) (ensure?? "parse-kindle" (some? (ct/parse-kindle (:kindle phone-agents)))) (ensure?? "parse-kindle" (nil? (ct/parse-kindle "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:kindle phone-agents)))) (ensure?? "parse-android" (some? (ct/parse-android (:android_galaxy phone-agents)))) (ensure?? "parse-android" (nil? (ct/parse-android "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:android_galaxy phone-agents)))) (ensure?? "parse-ffox" (some? (ct/parse-ffox (:ffox_linux phone-agents)))) (ensure?? "parse-ffox" (nil? (ct/parse-ffox "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ffox_linux phone-agents)))) (ensure?? "parse-safari" (some? (ct/parse-safari (:safari_osx phone-agents)))) (ensure?? "parse-safari" (nil? (ct/parse-safari "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:safari_osx phone-agents)))) (ensure?? "generate-nonce" (c/hgl? (ct/generate-nonce))) (ensure?? "generate-csrf" (c/hgl? (ct/generate-csrf))) (ensure?? "parse-basic-auth" (let [{:keys [principal credential]} (ct/parse-basic-auth " Basic QWxhZGRpbjpPcGVuU2VzYW1l ")] (and (.equals "Aladdin" principal) (.equals "OpenSesame" credential)))) (ensure?? "form-items<>" (let [bag (-> (cu/form-items<>) (cu/add-item (cu/file-item<> true "" nil "a1" "" nil)) (cu/add-item (cu/file-item<> false "" nil "f1" "" nil)) (cu/add-item (cu/file-item<> true "" nil "a2" "" nil)))] (and (== 1 (count (cu/get-all-files bag))) (== 2 (count (cu/get-all-fields bag)))))) (ensure?? "file-item<>" (let [f (cu/file-item<> true "" nil "a1" "" (XData. "hello")) b (.get f) n (.getFieldName f) f? (.isFormField f) s (.getString f) m? (.isInMemory f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (some? i) (.equals "a1" n) f? (.equals "hello" s) m?))) (ensure?? "file-item<>" (let [f (cu/file-item<> false "text/plain" nil "f1" "a.txt" (XData. "hello")) b (.get f) n (.getFieldName f) ct (.getContentType f) f? (not (.isFormField f)) s (.getString f) m? (.isInMemory f) nn (.getName f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (.equals "text/plain" ct) (some? i) (.equals "f1" n) (.equals "a.txt" nn) f? (.equals "hello" s) m?))) (ensure?? "mime-cache<>" (map? (mi/mime-cache<>))) (ensure?? "charset??" (.equals "utf-16" (mi/charset?? "text/plain; charset=utf-16"))) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx@@@ddddd")) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx")) (ensure?? "normalize-email" (.equals "<EMAIL>" (mi/normalize-email "<EMAIL>"))) (ensure?? "is-signed?" (mi/is-signed? "saljas application/x-pkcs7-mime laslasdf lksalfkla multipart/signed signed-data ")) (ensure?? "is-encrypted?" (mi/is-encrypted? "saljas laslasdf lksalfkla application/x-pkcs7-mime enveloped-data ")) (ensure?? "is-compressed?" (mi/is-compressed? "saljas laslasdf lksalfkla application/pkcs7-mime compressed-data")) (ensure?? "is-mdn?" (mi/is-mdn? "saljas laslasdf lksalfkla multipart/report disposition-notification ")) (ensure?? "guess-mime-type" (cs/includes? (mi/guess-mime-type "/tmp/abc.jpeg") "image/")) (ensure?? "guess-content-type" (cs/includes? (mi/guess-content-type "/tmp/abc.pdf") "/pdf")) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (t/deftest ^:test-niou niou-test-core (t/is (c/clj-test?? test-core))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.test.niou.core (:require [czlab.test.niou.mock :as m] [czlab.niou.webss :as ws] [czlab.niou.routes :as r] [czlab.niou.util :as ct] [czlab.niou.mime :as mi] [czlab.niou.core :as cc] [czlab.niou.upload :as cu] [clojure.string :as cs] [clojure.test :as t] [czlab.basal.io :as i] [czlab.basal.core :as c :refer [ensure?? ensure-thrown??]]) (:import [java.net HttpCookie URL URI] [czlab.basal XData] [czlab.niou Headers] [org.apache.commons.fileupload FileItem])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- phone-agents {:winphone " Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920) " :safari_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17 " :chrome_osx " Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.155 Safari/537.22 " :ffox_linux " Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:19.0) Gecko/20100101 Firefox/19.0 " :ie_win " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0) " :chrome_win " Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.97 Safari/537.22 " :kindle " Mozilla/5.0 (Linux; U; en-us; KFTT Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Silk/2.8 Safari/535.19 Silk-Accelerated=true " :iphone " Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipad " Mozilla/5.0 (iPad; CPU OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :ipod " Mozilla/5.0 (iPod; CPU iPhone OS 6_1_2 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B146 Safari/8536.25 " :android_galaxy " Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; SAMSUNG-SGH-I747 Build/JRO03L) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 "}) (c/def- pkeybytes (i/x->bytes "mocker")) (c/def- ROUTES [{:XXXhandler "p1" :pattern "/{a}/{b}" :groups {:a "[a-z]+" :b "[0-9]+"} :verb :post :name :r1 :extras {:template "t1.html"}} {:pattern "/{yo}" :name :r2 :groups {:yo "favicon\\..+"}} {:XXXhandler "p2" :pattern "/{a}/zzz/{b}/c/{d}" :name :r3 :groups {:a "[A]+" :b "[B]+" :d "[D]+"} :verb :get} {:name :g1 :pattern "/a/{b}/c/{d}/e/{f}" :groups {:b "[a-z]+" :d "[0-9]+" :f "[A-Z]+"}} {:pattern "/4"}]) (c/def- RC (r/route-cracker<> ROUTES)) ;(println "routes = " (i/fmt->edn RC)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (eval '(mi/setup-cache (i/res->url "czlab/niou/etc/mime.properties"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/def- ^Headers HEADERS (doto (Headers.) (.add "he" "x") (.set "ha" "y") (.add "yo" "a") (.add "yo" "b"))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/deftest test-core (ensure?? "gist-header?" (and (.containsKey HEADERS "Yo") (not (.containsKey HEADERS "o")))) (ensure?? "gist-header" (.equals "a" (.getFirst HEADERS "yo"))) (ensure?? "gist-header-keys" (let [s (into #{} (.keySet HEADERS))] (and (contains? s "yo") (contains? s "he") (contains? s "ha")))) (ensure?? "gist-header-vals" (= ["a" "b"] (vec (.get HEADERS "yo")))) (ensure?? "init-test" (> (count ROUTES) 0)) (ensure?? "has-routes?" (r/has-routes? RC)) (ensure?? "parse-path" (let [[p c g] (r/regex-path "/{a}/{z}/{b}/c/{d}" {:a "foo" :b "man" :d "chu" :z nil})] (and (== 5 c) (== 1 (:a g)) (== 2 (:z g)) (== 3 (:b g)) (== 4 (:d g)) (.equals "/(foo)/([^/]+)/(man)/c/(chu)" p)))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/hello/007" :request-method :post})] (and R (= :r1 (:name info)) (.equals "hello" (:a params)) (.equals "007" (:b params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/favicon.hello" :request-method :get})] (and R (== 1 (count params)) (.equals "favicon.hello" (:yo params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/AAA/zzz/BBB/c/DDD" :request-method :get})] (and (== 3 (count params)) (.equals "AAA" (:a params)) (.equals "BBB" (:b params)) (.equals "DDD" (:d params))))) (ensure?? "crack-route" (let [{:as R :keys [info params]} (r/crack-route RC {:uri "/4" :request-method :get})] (and info (empty? params)))) (ensure?? "crack-route" (nil? (r/crack-route RC {:request-method :get :uri "/1/1/1/1/1/1/14"}))) ;:pattern "/a/{b}/c/{d}/e/{f}" (ensure?? "gen-route/nil" (nil? (r/gen-route RC :ggg {}))) (ensure-thrown?? "gen-route/params" :any (r/gen-route RC :g1 {:d "911" :f "XYZ"})) (ensure-thrown?? "gen-route/malform" :any (r/gen-route RC :g1 {:b "xyz" :d "XXX" :f "XYZ"})) (ensure?? "gen-route/ok" (.equals "/a/xyz/c/911/e/XYZ" (first (r/gen-route RC :g1 {:b "xyz" :d "911" :f "XYZ"})))) (ensure?? "parse-form-post" (let [b (XData. cu/TEST-FORM-MULTIPART) gist {:clen (.size b) :ctype "multipart/form-data; boundary=---1234"} out (cu/parse-form-post gist b) rmap (when out (c/preduce<map> #(let [^FileItem i %2] (if-not (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getString i))) (.getString i)))) (cu/get-all-items out))) fmap (when out (c/preduce<map> #(let [^FileItem i %2] (if (.isFormField i) %1 (assoc! %1 (keyword (str (.getFieldName i) "+" (.getName i))) (i/x->str (.get i))))) (cu/get-all-items out)))] (and (.equals "fieldValue" (:field+fieldValue rmap)) (.equals "value1" (:multi+value1 rmap)) (.equals "value2" (:multi+value2 rmap)) (.equals "file content(1)\n" (:file1+foo1.tab fmap)) (.equals "file content(2)\n" (:file2+foo2.tab fmap))))) (ensure?? "downstream" (let [req (m/mock-http-request pkeybytes false) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) c (get cs ws/session-cookie) v (.getValue ^HttpCookie c)] (== 6 (count (.split v "="))))) (ensure?? "upstream" (let [req (m/mock-http-request pkeybytes true) res (m/mock-http-result req) res (ws/downstream res) cs (:cookies res) s (ws/upstream pkeybytes cs true)] (ws/validate?? s) (and (not (ws/is-session-null? s)) (not (ws/is-session-new? s))))) (ensure?? "parse-ie" (some? (ct/parse-ie (:winphone phone-agents)))) (ensure?? "parse-ie" (nil? (ct/parse-ie "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ie_win phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:winphone phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_osx phone-agents)))) (ensure?? "parse-chrome" (some? (ct/parse-chrome (:chrome_win phone-agents)))) (ensure?? "parse-chrome" (nil? (ct/parse-chrome "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_osx phone-agents)))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:chrome_win phone-agents)))) (ensure?? "parse-kindle" (some? (ct/parse-kindle (:kindle phone-agents)))) (ensure?? "parse-kindle" (nil? (ct/parse-kindle "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:kindle phone-agents)))) (ensure?? "parse-android" (some? (ct/parse-android (:android_galaxy phone-agents)))) (ensure?? "parse-android" (nil? (ct/parse-android "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:android_galaxy phone-agents)))) (ensure?? "parse-ffox" (some? (ct/parse-ffox (:ffox_linux phone-agents)))) (ensure?? "parse-ffox" (nil? (ct/parse-ffox "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:ffox_linux phone-agents)))) (ensure?? "parse-safari" (some? (ct/parse-safari (:safari_osx phone-agents)))) (ensure?? "parse-safari" (nil? (ct/parse-safari "some crap"))) (ensure?? "parse-user-agent-line" (some? (ct/parse-user-agent-line (:safari_osx phone-agents)))) (ensure?? "generate-nonce" (c/hgl? (ct/generate-nonce))) (ensure?? "generate-csrf" (c/hgl? (ct/generate-csrf))) (ensure?? "parse-basic-auth" (let [{:keys [principal credential]} (ct/parse-basic-auth " Basic QWxhZGRpbjpPcGVuU2VzYW1l ")] (and (.equals "Aladdin" principal) (.equals "OpenSesame" credential)))) (ensure?? "form-items<>" (let [bag (-> (cu/form-items<>) (cu/add-item (cu/file-item<> true "" nil "a1" "" nil)) (cu/add-item (cu/file-item<> false "" nil "f1" "" nil)) (cu/add-item (cu/file-item<> true "" nil "a2" "" nil)))] (and (== 1 (count (cu/get-all-files bag))) (== 2 (count (cu/get-all-fields bag)))))) (ensure?? "file-item<>" (let [f (cu/file-item<> true "" nil "a1" "" (XData. "hello")) b (.get f) n (.getFieldName f) f? (.isFormField f) s (.getString f) m? (.isInMemory f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (some? i) (.equals "a1" n) f? (.equals "hello" s) m?))) (ensure?? "file-item<>" (let [f (cu/file-item<> false "text/plain" nil "f1" "a.txt" (XData. "hello")) b (.get f) n (.getFieldName f) ct (.getContentType f) f? (not (.isFormField f)) s (.getString f) m? (.isInMemory f) nn (.getName f) z (.getSize f) i (.getInputStream f)] (i/klose i) (and (== z (alength b)) (.equals "text/plain" ct) (some? i) (.equals "f1" n) (.equals "a.txt" nn) f? (.equals "hello" s) m?))) (ensure?? "mime-cache<>" (map? (mi/mime-cache<>))) (ensure?? "charset??" (.equals "utf-16" (mi/charset?? "text/plain; charset=utf-16"))) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx@@@ddddd")) (ensure-thrown?? "normalize-email" :any (mi/normalize-email "xxxx")) (ensure?? "normalize-email" (.equals "PI:EMAIL:<EMAIL>END_PI" (mi/normalize-email "PI:EMAIL:<EMAIL>END_PI"))) (ensure?? "is-signed?" (mi/is-signed? "saljas application/x-pkcs7-mime laslasdf lksalfkla multipart/signed signed-data ")) (ensure?? "is-encrypted?" (mi/is-encrypted? "saljas laslasdf lksalfkla application/x-pkcs7-mime enveloped-data ")) (ensure?? "is-compressed?" (mi/is-compressed? "saljas laslasdf lksalfkla application/pkcs7-mime compressed-data")) (ensure?? "is-mdn?" (mi/is-mdn? "saljas laslasdf lksalfkla multipart/report disposition-notification ")) (ensure?? "guess-mime-type" (cs/includes? (mi/guess-mime-type "/tmp/abc.jpeg") "image/")) (ensure?? "guess-content-type" (cs/includes? (mi/guess-content-type "/tmp/abc.pdf") "/pdf")) (ensure?? "test-end" (== 1 1))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (t/deftest ^:test-niou niou-test-core (t/is (c/clj-test?? test-core))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": " \"There are only two feelings, love and fear.\n \n Michael Leunig\"\n\n (let [intro (with bassline (all :up true arpe", "end": 6044, "score": 0.9993294477462769, "start": 6030, "tag": "NAME", "value": "Michael Leunig" } ]
src/whelmed/songs/love_and_fear.clj
ctford/whelmed
32
(ns whelmed.songs.love-and-fear (:require [leipzig.melody :refer :all] [leipzig.live :refer :all] [leipzig.canon :refer :all] [whelmed.melody :refer :all] [leipzig.scale :refer :all] [leipzig.chord :refer :all] [whelmed.instrument :refer :all] [leipzig.temperament :as temperament] [overtone.live :as overtone])) (defn harmonise [f notes] (->> notes (all :part ::melody) (canon (comp (partial all :part ::harmony) f) ))) (defn tap [drum times length] (map #(zipmap [:time :duration :drum] [%1 (- length %1) drum]) times)) (def beata (->> (reduce with [(tap :tock [1 3 5 7] 8) (tap :tick [15/4 30/4] 8) (tap :kick [0 3/4 6/4 10/4 14/4 16/4 19/4 22/4 26/4] 8)]) (all :part ::beat))) (def beatb (->> (reduce with [(tap :tick [4/4 6/4 12/4 20/4 22/4 28/4] 8) (tap :kick [0 1/4 2/4 3/4 8/4 9/4 10/4 11/4 16/4 19/4 24/4 27/4] 8)]) (all :part ::beat))) (defn base [chord element] (-> chord (assoc :bass (-> chord element lower)))) (defn arpeggiate [chord ks duration] (map (fn [k time] {:time time :pitch (chord k) :duration duration}) ks (reductions + 0 (repeat duration)))) (def progression (map base [(-> seventh (root 0)) (-> triad (assoc :v- -3) (root 2)) (-> ninth (root -2))] [:i :v- :i])) (def bassline (let [one (phrase (concat [1 1/2 1/2 1 1/2 1/2] (repeat 8 1/2)) [0 0 -3 -1 -1 -3 -2 -5 -2 -5 -2 -5 -2 -1]) two (phrase [1 1/2 1/2 1 1/2 9/2] [0 0 2 -1 -3 -2])] (->> one (then two) (times 2) (where :pitch lower) (all :part ::bass)))) (def vanilla-bass (->> (phrase [0 -1 -2] [4 4 8]) (where :pitch (comp lower lower)) (times 2) (all :part ::bass))) (def chords (->> (phrase [2 2 4] progression) (times 2) (with (->> (phrase [2 2 4] [6 6 7]) (where :pitch raise) (after 8))) (where :pitch lower) (all :part ::chords) (with vanilla-bass))) (def arpeggios (let [one (->> progression (mapthen #(arpeggiate %2 %1 1/2) [[:i :iii :v :vii] [:v- :i :iii :v] [:i :v :vii :ix :vii :iii]]) (wherever #(-> % :time (= 11/2)), :duration (is 1)) (wherever #(-> % :time (> 11/2)), :time (from 1/2)) (wherever #(-> % :time ( = 7)), :duration (is 1))) two (->> one (but 2 8 (phrase [1/2 1/2 1/2 1/2 4] [5 4 2 -1 0])))] (->> one (then two) (times 2) (but 27 32 (phrase [1 3] [7 6])) (all :part ::arpeggios)))) (def theme (->> (phrase [2 2 9/2] [6 6 7]) (all :part ::melody) (harmonise (interval -2)))) (def modified-theme (->> theme (wherever (between? 0 2), :duration (is 3/2)) (wherever (between? 2 5), :time (from -1/2)))) (def melodya (let [aaaaand [1 2] rhythm [1/2 3/2 1/2 1 1 1 1] there-are-only-two-feelings (->> (phrase (concat aaaaand rhythm) [4 6 6 6 6 7 6 5 6]) (after -2) (harmonise (partial all :pitch 2)) (then theme) ) love-and-fear (->> (phrase rhythm [9 9 8 7 6 4 6]) (after 1) (harmonise (partial all :pitch 2)) (then theme))] (->> there-are-only-two-feelings (then love-and-fear)))) (def melodyb (let [there-are (->> (phrase [1/2 1/2 1/4 1/4 1 1/4 1/4 1/4 1/4 1 9/2] [2 3 triad 3 2 4 3 (-> triad (root 2) (inversion 2)) 3 2 (-> triad (root -2))]) (after -1)) only-two-activities (->> (phrase [1/2 3/2 1/2 1/2 1 1/2 9/2] [2 3 4 3 2 1 2]) (after -1))] (->> there-are (then only-two-activities) (times 2) (all :part ::melody)))) (def melody (->> melodya (then melodyb))) (def two-motives (let [two (phrase [1/2 1/2 3/2] [2 1 0]) motives (->> two (then (phrase [1/2 1 1/2 1 5/2] [0 0 0 1 0]))) procedures ( ->> two (then (phrase [1/2 1 1/2 7/2] [-1 0 -1 -3]))) results (->> two (then (phrase [1/2 1 1/2 1 1 1 1 3/2 1/2 1 1/2 5] [0 0 0 1 0 -1 0 0 -1 0 -1 -3])))] (->> motives (then procedures) (then results) (after -1) (all :part ::melody) (with (->> chords (times 2) (all :part ::blurt)))))) (defn ring [rate] (->> (repeatedly #([-3 -1 2 4 6 7 9 11] (rand-int 7))) (phrase (repeat (int (/ 48 rate)) rate)))) (def ringing (with (all :part ::melody (ring 1)) (all :part ::harmony (ring 1/2)))) ; Arrangement (defmethod play-note ::melody [{hz :pitch s :duration}] (some-> hz (bell s :volume 1 :position 1/9 :wet 0.4 :room 0.1 :low 400)) (some-> hz (* 2) (bell (* 4/3 s) :volume 0.7 :position 1/7 :wet 0.9 :room 0.9)) (some-> hz (sing s :volume 0.4 :position -1/9 :wet 0.8 :room 0.9))) (defmethod play-note ::harmony [{hz :pitch s :duration}] (some-> hz (bell 6 :volume 0.7 :position -1/2 :wet 0.8 :room 0.9)) (some-> hz (sing s :volume 0.4 :position 1/2 :wet 0.8 :room 0.9))) (defmethod play-note ::chords [{hz :pitch, length :duration}] (some-> hz (corgan length 0.8 :vol 0.1 :vibrato 2/3 :depth 0.4 :pan 1/4 :room 0.9))) (defmethod play-note ::blurt [{:keys [pitch duration]}] (some-> pitch (corgan duration :depth 1 :vibrato 4/3 :vol 0.15 :pan -1/3 :room 0.9))) (defmethod play-note ::bass [{:keys [duration pitch]}] (some-> pitch (corgan duration :vibrato 2/3 :limit 700 :depth 0 :pan -1/3 :depth 0 :vol 0.3 :room 0.9))) (defn praise [p up] (if up (* p 2) p)) (defmethod play-note ::arpeggios [{:keys [pitch duration up]}] (some-> pitch (praise up) (brassy :dur duration :p 2/3 :noise 10 :pan -1/3 :wet 0.8 :vol 0.4 :p 8/6 :room 0.9)) (some-> pitch (corgan duration :vibrato 2/3 :vol 0.2 :depth 0.2 :limit 2000 :pan 1/3 :room 0.9))) (defmethod play-note ::beat [note] ((-> note :drum kit) :amp 0.3)) (def love-and-fear "There are only two feelings, love and fear. Michael Leunig" (let [intro (with bassline (all :up true arpeggios)) statement (->> melody (with (times 4 beata)) (with (times 2 chords)) (with (after 32 (->> arpeggios (with bassline) (with (times 4 beatb)))))) oh-love-and-fear (->> (phrase [1/2 1/2 1 1/2 1/2 1 1/2 1/2 4] [2 1 0 0 -1 0 2 3 2]) (after -1) (harmonise (interval 7))) outro (->> chords (with (->> modified-theme (with oh-love-and-fear) (times 2))) (times 2) (with (times 4 beata) ringing) (then (take 6 oh-love-and-fear)))] (->> intro (then statement) ;(then statement) Vary? (then two-motives) (then (->> melodyb (where :pitch lower) (with (times 4 beatb)) (with (->> (times 2 chords) (all :part ::blurt))))) (then outro) (tempo (bpm 80)) (where :pitch (comp temperament/equal G minor)) #_(with [{:time 0 :duration 0 :part ::vocals}])))) #_(overtone/defsynth treated-vocals [] (let [lead (overtone/load-sample "vocals/love-lead.wav") dry (+ (overtone/pan2 (overtone/play-buf 1 lead) 1/3)) delayed (overtone/delay-c dry :delay-time 0.05) delayed2 (* 0.3 (overtone/delay-c dry :delay-time 8/6)) wet (overtone/free-verb (+ dry delayed delayed2) :mix 0.4 :room 0.9 :damp 1)] (overtone/out 0 (-> (overtone/compander wet wet) (* 10) (overtone/lpf 3000) (overtone/hpf 1000) overtone/pan2)))) #_(defmethod play-note ::vocals [_] (treated-vocals)) (comment (jam (var love-and-fear)) (play love-and-fear) (overtone/recording-stop) (overtone/recording-start "love-vocals1.wav"))
37908
(ns whelmed.songs.love-and-fear (:require [leipzig.melody :refer :all] [leipzig.live :refer :all] [leipzig.canon :refer :all] [whelmed.melody :refer :all] [leipzig.scale :refer :all] [leipzig.chord :refer :all] [whelmed.instrument :refer :all] [leipzig.temperament :as temperament] [overtone.live :as overtone])) (defn harmonise [f notes] (->> notes (all :part ::melody) (canon (comp (partial all :part ::harmony) f) ))) (defn tap [drum times length] (map #(zipmap [:time :duration :drum] [%1 (- length %1) drum]) times)) (def beata (->> (reduce with [(tap :tock [1 3 5 7] 8) (tap :tick [15/4 30/4] 8) (tap :kick [0 3/4 6/4 10/4 14/4 16/4 19/4 22/4 26/4] 8)]) (all :part ::beat))) (def beatb (->> (reduce with [(tap :tick [4/4 6/4 12/4 20/4 22/4 28/4] 8) (tap :kick [0 1/4 2/4 3/4 8/4 9/4 10/4 11/4 16/4 19/4 24/4 27/4] 8)]) (all :part ::beat))) (defn base [chord element] (-> chord (assoc :bass (-> chord element lower)))) (defn arpeggiate [chord ks duration] (map (fn [k time] {:time time :pitch (chord k) :duration duration}) ks (reductions + 0 (repeat duration)))) (def progression (map base [(-> seventh (root 0)) (-> triad (assoc :v- -3) (root 2)) (-> ninth (root -2))] [:i :v- :i])) (def bassline (let [one (phrase (concat [1 1/2 1/2 1 1/2 1/2] (repeat 8 1/2)) [0 0 -3 -1 -1 -3 -2 -5 -2 -5 -2 -5 -2 -1]) two (phrase [1 1/2 1/2 1 1/2 9/2] [0 0 2 -1 -3 -2])] (->> one (then two) (times 2) (where :pitch lower) (all :part ::bass)))) (def vanilla-bass (->> (phrase [0 -1 -2] [4 4 8]) (where :pitch (comp lower lower)) (times 2) (all :part ::bass))) (def chords (->> (phrase [2 2 4] progression) (times 2) (with (->> (phrase [2 2 4] [6 6 7]) (where :pitch raise) (after 8))) (where :pitch lower) (all :part ::chords) (with vanilla-bass))) (def arpeggios (let [one (->> progression (mapthen #(arpeggiate %2 %1 1/2) [[:i :iii :v :vii] [:v- :i :iii :v] [:i :v :vii :ix :vii :iii]]) (wherever #(-> % :time (= 11/2)), :duration (is 1)) (wherever #(-> % :time (> 11/2)), :time (from 1/2)) (wherever #(-> % :time ( = 7)), :duration (is 1))) two (->> one (but 2 8 (phrase [1/2 1/2 1/2 1/2 4] [5 4 2 -1 0])))] (->> one (then two) (times 2) (but 27 32 (phrase [1 3] [7 6])) (all :part ::arpeggios)))) (def theme (->> (phrase [2 2 9/2] [6 6 7]) (all :part ::melody) (harmonise (interval -2)))) (def modified-theme (->> theme (wherever (between? 0 2), :duration (is 3/2)) (wherever (between? 2 5), :time (from -1/2)))) (def melodya (let [aaaaand [1 2] rhythm [1/2 3/2 1/2 1 1 1 1] there-are-only-two-feelings (->> (phrase (concat aaaaand rhythm) [4 6 6 6 6 7 6 5 6]) (after -2) (harmonise (partial all :pitch 2)) (then theme) ) love-and-fear (->> (phrase rhythm [9 9 8 7 6 4 6]) (after 1) (harmonise (partial all :pitch 2)) (then theme))] (->> there-are-only-two-feelings (then love-and-fear)))) (def melodyb (let [there-are (->> (phrase [1/2 1/2 1/4 1/4 1 1/4 1/4 1/4 1/4 1 9/2] [2 3 triad 3 2 4 3 (-> triad (root 2) (inversion 2)) 3 2 (-> triad (root -2))]) (after -1)) only-two-activities (->> (phrase [1/2 3/2 1/2 1/2 1 1/2 9/2] [2 3 4 3 2 1 2]) (after -1))] (->> there-are (then only-two-activities) (times 2) (all :part ::melody)))) (def melody (->> melodya (then melodyb))) (def two-motives (let [two (phrase [1/2 1/2 3/2] [2 1 0]) motives (->> two (then (phrase [1/2 1 1/2 1 5/2] [0 0 0 1 0]))) procedures ( ->> two (then (phrase [1/2 1 1/2 7/2] [-1 0 -1 -3]))) results (->> two (then (phrase [1/2 1 1/2 1 1 1 1 3/2 1/2 1 1/2 5] [0 0 0 1 0 -1 0 0 -1 0 -1 -3])))] (->> motives (then procedures) (then results) (after -1) (all :part ::melody) (with (->> chords (times 2) (all :part ::blurt)))))) (defn ring [rate] (->> (repeatedly #([-3 -1 2 4 6 7 9 11] (rand-int 7))) (phrase (repeat (int (/ 48 rate)) rate)))) (def ringing (with (all :part ::melody (ring 1)) (all :part ::harmony (ring 1/2)))) ; Arrangement (defmethod play-note ::melody [{hz :pitch s :duration}] (some-> hz (bell s :volume 1 :position 1/9 :wet 0.4 :room 0.1 :low 400)) (some-> hz (* 2) (bell (* 4/3 s) :volume 0.7 :position 1/7 :wet 0.9 :room 0.9)) (some-> hz (sing s :volume 0.4 :position -1/9 :wet 0.8 :room 0.9))) (defmethod play-note ::harmony [{hz :pitch s :duration}] (some-> hz (bell 6 :volume 0.7 :position -1/2 :wet 0.8 :room 0.9)) (some-> hz (sing s :volume 0.4 :position 1/2 :wet 0.8 :room 0.9))) (defmethod play-note ::chords [{hz :pitch, length :duration}] (some-> hz (corgan length 0.8 :vol 0.1 :vibrato 2/3 :depth 0.4 :pan 1/4 :room 0.9))) (defmethod play-note ::blurt [{:keys [pitch duration]}] (some-> pitch (corgan duration :depth 1 :vibrato 4/3 :vol 0.15 :pan -1/3 :room 0.9))) (defmethod play-note ::bass [{:keys [duration pitch]}] (some-> pitch (corgan duration :vibrato 2/3 :limit 700 :depth 0 :pan -1/3 :depth 0 :vol 0.3 :room 0.9))) (defn praise [p up] (if up (* p 2) p)) (defmethod play-note ::arpeggios [{:keys [pitch duration up]}] (some-> pitch (praise up) (brassy :dur duration :p 2/3 :noise 10 :pan -1/3 :wet 0.8 :vol 0.4 :p 8/6 :room 0.9)) (some-> pitch (corgan duration :vibrato 2/3 :vol 0.2 :depth 0.2 :limit 2000 :pan 1/3 :room 0.9))) (defmethod play-note ::beat [note] ((-> note :drum kit) :amp 0.3)) (def love-and-fear "There are only two feelings, love and fear. <NAME>" (let [intro (with bassline (all :up true arpeggios)) statement (->> melody (with (times 4 beata)) (with (times 2 chords)) (with (after 32 (->> arpeggios (with bassline) (with (times 4 beatb)))))) oh-love-and-fear (->> (phrase [1/2 1/2 1 1/2 1/2 1 1/2 1/2 4] [2 1 0 0 -1 0 2 3 2]) (after -1) (harmonise (interval 7))) outro (->> chords (with (->> modified-theme (with oh-love-and-fear) (times 2))) (times 2) (with (times 4 beata) ringing) (then (take 6 oh-love-and-fear)))] (->> intro (then statement) ;(then statement) Vary? (then two-motives) (then (->> melodyb (where :pitch lower) (with (times 4 beatb)) (with (->> (times 2 chords) (all :part ::blurt))))) (then outro) (tempo (bpm 80)) (where :pitch (comp temperament/equal G minor)) #_(with [{:time 0 :duration 0 :part ::vocals}])))) #_(overtone/defsynth treated-vocals [] (let [lead (overtone/load-sample "vocals/love-lead.wav") dry (+ (overtone/pan2 (overtone/play-buf 1 lead) 1/3)) delayed (overtone/delay-c dry :delay-time 0.05) delayed2 (* 0.3 (overtone/delay-c dry :delay-time 8/6)) wet (overtone/free-verb (+ dry delayed delayed2) :mix 0.4 :room 0.9 :damp 1)] (overtone/out 0 (-> (overtone/compander wet wet) (* 10) (overtone/lpf 3000) (overtone/hpf 1000) overtone/pan2)))) #_(defmethod play-note ::vocals [_] (treated-vocals)) (comment (jam (var love-and-fear)) (play love-and-fear) (overtone/recording-stop) (overtone/recording-start "love-vocals1.wav"))
true
(ns whelmed.songs.love-and-fear (:require [leipzig.melody :refer :all] [leipzig.live :refer :all] [leipzig.canon :refer :all] [whelmed.melody :refer :all] [leipzig.scale :refer :all] [leipzig.chord :refer :all] [whelmed.instrument :refer :all] [leipzig.temperament :as temperament] [overtone.live :as overtone])) (defn harmonise [f notes] (->> notes (all :part ::melody) (canon (comp (partial all :part ::harmony) f) ))) (defn tap [drum times length] (map #(zipmap [:time :duration :drum] [%1 (- length %1) drum]) times)) (def beata (->> (reduce with [(tap :tock [1 3 5 7] 8) (tap :tick [15/4 30/4] 8) (tap :kick [0 3/4 6/4 10/4 14/4 16/4 19/4 22/4 26/4] 8)]) (all :part ::beat))) (def beatb (->> (reduce with [(tap :tick [4/4 6/4 12/4 20/4 22/4 28/4] 8) (tap :kick [0 1/4 2/4 3/4 8/4 9/4 10/4 11/4 16/4 19/4 24/4 27/4] 8)]) (all :part ::beat))) (defn base [chord element] (-> chord (assoc :bass (-> chord element lower)))) (defn arpeggiate [chord ks duration] (map (fn [k time] {:time time :pitch (chord k) :duration duration}) ks (reductions + 0 (repeat duration)))) (def progression (map base [(-> seventh (root 0)) (-> triad (assoc :v- -3) (root 2)) (-> ninth (root -2))] [:i :v- :i])) (def bassline (let [one (phrase (concat [1 1/2 1/2 1 1/2 1/2] (repeat 8 1/2)) [0 0 -3 -1 -1 -3 -2 -5 -2 -5 -2 -5 -2 -1]) two (phrase [1 1/2 1/2 1 1/2 9/2] [0 0 2 -1 -3 -2])] (->> one (then two) (times 2) (where :pitch lower) (all :part ::bass)))) (def vanilla-bass (->> (phrase [0 -1 -2] [4 4 8]) (where :pitch (comp lower lower)) (times 2) (all :part ::bass))) (def chords (->> (phrase [2 2 4] progression) (times 2) (with (->> (phrase [2 2 4] [6 6 7]) (where :pitch raise) (after 8))) (where :pitch lower) (all :part ::chords) (with vanilla-bass))) (def arpeggios (let [one (->> progression (mapthen #(arpeggiate %2 %1 1/2) [[:i :iii :v :vii] [:v- :i :iii :v] [:i :v :vii :ix :vii :iii]]) (wherever #(-> % :time (= 11/2)), :duration (is 1)) (wherever #(-> % :time (> 11/2)), :time (from 1/2)) (wherever #(-> % :time ( = 7)), :duration (is 1))) two (->> one (but 2 8 (phrase [1/2 1/2 1/2 1/2 4] [5 4 2 -1 0])))] (->> one (then two) (times 2) (but 27 32 (phrase [1 3] [7 6])) (all :part ::arpeggios)))) (def theme (->> (phrase [2 2 9/2] [6 6 7]) (all :part ::melody) (harmonise (interval -2)))) (def modified-theme (->> theme (wherever (between? 0 2), :duration (is 3/2)) (wherever (between? 2 5), :time (from -1/2)))) (def melodya (let [aaaaand [1 2] rhythm [1/2 3/2 1/2 1 1 1 1] there-are-only-two-feelings (->> (phrase (concat aaaaand rhythm) [4 6 6 6 6 7 6 5 6]) (after -2) (harmonise (partial all :pitch 2)) (then theme) ) love-and-fear (->> (phrase rhythm [9 9 8 7 6 4 6]) (after 1) (harmonise (partial all :pitch 2)) (then theme))] (->> there-are-only-two-feelings (then love-and-fear)))) (def melodyb (let [there-are (->> (phrase [1/2 1/2 1/4 1/4 1 1/4 1/4 1/4 1/4 1 9/2] [2 3 triad 3 2 4 3 (-> triad (root 2) (inversion 2)) 3 2 (-> triad (root -2))]) (after -1)) only-two-activities (->> (phrase [1/2 3/2 1/2 1/2 1 1/2 9/2] [2 3 4 3 2 1 2]) (after -1))] (->> there-are (then only-two-activities) (times 2) (all :part ::melody)))) (def melody (->> melodya (then melodyb))) (def two-motives (let [two (phrase [1/2 1/2 3/2] [2 1 0]) motives (->> two (then (phrase [1/2 1 1/2 1 5/2] [0 0 0 1 0]))) procedures ( ->> two (then (phrase [1/2 1 1/2 7/2] [-1 0 -1 -3]))) results (->> two (then (phrase [1/2 1 1/2 1 1 1 1 3/2 1/2 1 1/2 5] [0 0 0 1 0 -1 0 0 -1 0 -1 -3])))] (->> motives (then procedures) (then results) (after -1) (all :part ::melody) (with (->> chords (times 2) (all :part ::blurt)))))) (defn ring [rate] (->> (repeatedly #([-3 -1 2 4 6 7 9 11] (rand-int 7))) (phrase (repeat (int (/ 48 rate)) rate)))) (def ringing (with (all :part ::melody (ring 1)) (all :part ::harmony (ring 1/2)))) ; Arrangement (defmethod play-note ::melody [{hz :pitch s :duration}] (some-> hz (bell s :volume 1 :position 1/9 :wet 0.4 :room 0.1 :low 400)) (some-> hz (* 2) (bell (* 4/3 s) :volume 0.7 :position 1/7 :wet 0.9 :room 0.9)) (some-> hz (sing s :volume 0.4 :position -1/9 :wet 0.8 :room 0.9))) (defmethod play-note ::harmony [{hz :pitch s :duration}] (some-> hz (bell 6 :volume 0.7 :position -1/2 :wet 0.8 :room 0.9)) (some-> hz (sing s :volume 0.4 :position 1/2 :wet 0.8 :room 0.9))) (defmethod play-note ::chords [{hz :pitch, length :duration}] (some-> hz (corgan length 0.8 :vol 0.1 :vibrato 2/3 :depth 0.4 :pan 1/4 :room 0.9))) (defmethod play-note ::blurt [{:keys [pitch duration]}] (some-> pitch (corgan duration :depth 1 :vibrato 4/3 :vol 0.15 :pan -1/3 :room 0.9))) (defmethod play-note ::bass [{:keys [duration pitch]}] (some-> pitch (corgan duration :vibrato 2/3 :limit 700 :depth 0 :pan -1/3 :depth 0 :vol 0.3 :room 0.9))) (defn praise [p up] (if up (* p 2) p)) (defmethod play-note ::arpeggios [{:keys [pitch duration up]}] (some-> pitch (praise up) (brassy :dur duration :p 2/3 :noise 10 :pan -1/3 :wet 0.8 :vol 0.4 :p 8/6 :room 0.9)) (some-> pitch (corgan duration :vibrato 2/3 :vol 0.2 :depth 0.2 :limit 2000 :pan 1/3 :room 0.9))) (defmethod play-note ::beat [note] ((-> note :drum kit) :amp 0.3)) (def love-and-fear "There are only two feelings, love and fear. PI:NAME:<NAME>END_PI" (let [intro (with bassline (all :up true arpeggios)) statement (->> melody (with (times 4 beata)) (with (times 2 chords)) (with (after 32 (->> arpeggios (with bassline) (with (times 4 beatb)))))) oh-love-and-fear (->> (phrase [1/2 1/2 1 1/2 1/2 1 1/2 1/2 4] [2 1 0 0 -1 0 2 3 2]) (after -1) (harmonise (interval 7))) outro (->> chords (with (->> modified-theme (with oh-love-and-fear) (times 2))) (times 2) (with (times 4 beata) ringing) (then (take 6 oh-love-and-fear)))] (->> intro (then statement) ;(then statement) Vary? (then two-motives) (then (->> melodyb (where :pitch lower) (with (times 4 beatb)) (with (->> (times 2 chords) (all :part ::blurt))))) (then outro) (tempo (bpm 80)) (where :pitch (comp temperament/equal G minor)) #_(with [{:time 0 :duration 0 :part ::vocals}])))) #_(overtone/defsynth treated-vocals [] (let [lead (overtone/load-sample "vocals/love-lead.wav") dry (+ (overtone/pan2 (overtone/play-buf 1 lead) 1/3)) delayed (overtone/delay-c dry :delay-time 0.05) delayed2 (* 0.3 (overtone/delay-c dry :delay-time 8/6)) wet (overtone/free-verb (+ dry delayed delayed2) :mix 0.4 :room 0.9 :damp 1)] (overtone/out 0 (-> (overtone/compander wet wet) (* 10) (overtone/lpf 3000) (overtone/hpf 1000) overtone/pan2)))) #_(defmethod play-note ::vocals [_] (treated-vocals)) (comment (jam (var love-and-fear)) (play love-and-fear) (overtone/recording-stop) (overtone/recording-start "love-vocals1.wav"))
[ { "context": " t-conn\n {:name \"Bob\"\n :message \"Hello, World\"\n ", "end": 707, "score": 0.9973488450050354, "start": 704, "tag": "NAME", "value": "Bob" }, { "context": "n t-conn})))\n (is (=\n {:name \"Bob\"\n :message \"Hello, World\"\n ", "end": 871, "score": 0.9950685501098633, "start": 868, "tag": "NAME", "value": "Bob" } ]
clojure/wdc-2e/guestbook/test/clj/guestbook/test/db/core.clj
mdssjc/mds-lisp
0
(ns guestbook.test.db.core (:require [guestbook.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [guestbook.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'guestbook.config/env #'guestbook.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-messages (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [timestamp (java.util.Date.)] (is (= 1 (db/save-message! t-conn {:name "Bob" :message "Hello, World" :timestamp timestamp} {:connection t-conn}))) (is (= {:name "Bob" :message "Hello, World" :timestamp timestamp} (-> (db/get-messages t-conn {}) (first) (select-keys [:name :message :timestamp])))))))
9439
(ns guestbook.test.db.core (:require [guestbook.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [guestbook.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'guestbook.config/env #'guestbook.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-messages (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [timestamp (java.util.Date.)] (is (= 1 (db/save-message! t-conn {:name "<NAME>" :message "Hello, World" :timestamp timestamp} {:connection t-conn}))) (is (= {:name "<NAME>" :message "Hello, World" :timestamp timestamp} (-> (db/get-messages t-conn {}) (first) (select-keys [:name :message :timestamp])))))))
true
(ns guestbook.test.db.core (:require [guestbook.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [guestbook.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'guestbook.config/env #'guestbook.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-messages (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [timestamp (java.util.Date.)] (is (= 1 (db/save-message! t-conn {:name "PI:NAME:<NAME>END_PI" :message "Hello, World" :timestamp timestamp} {:connection t-conn}))) (is (= {:name "PI:NAME:<NAME>END_PI" :message "Hello, World" :timestamp timestamp} (-> (db/get-messages t-conn {}) (first) (select-keys [:name :message :timestamp])))))))
[ { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\"\n :doc\n \"Logging librar", "end": 28, "score": 0.9998547434806824, "start": 15, "tag": "NAME", "value": "Bruno Bonacci" }, { "context": "(ns ^{:author \"Bruno Bonacci (@BrunoBonacci)\"\n :doc\n \"Logging library designed to l", "end": 43, "score": 0.9990215301513672, "start": 29, "tag": "USERNAME", "value": "(@BrunoBonacci" } ]
mulog-core/src/com/brunobonacci/mulog/core.clj
emlyn/mulog
0
(ns ^{:author "Bruno Bonacci (@BrunoBonacci)" :doc "Logging library designed to log data events instead of plain words." :no-doc true} com.brunobonacci.mulog.core (:require [com.brunobonacci.mulog.buffer :as rb] [com.brunobonacci.mulog.publisher :as p] [com.brunobonacci.mulog.flakes :refer [snowflake]]) (:import [com.brunobonacci.mulog.publisher PPublisher])) (def ^:const PUBLISH-INTERVAL 200) (defn dequeue! [buffer offset] (swap! buffer rb/dequeue offset)) (defn enqueue! [buffer value] (swap! buffer rb/enqueue value)) ;; ;; Stores the registered publishers ;; id -> {buffer, publisher, ?stopper} ;; (defonce publishers (atom {})) (defn register-publisher! [buffer publisher] (let [id (snowflake)] (swap! publishers assoc id {:buffer buffer :publisher publisher}) id)) (defn deregister-publisher! [id] (swap! publishers dissoc id)) (defn registered-publishers [] (->> @publishers (map (fn [[id {:keys [publisher]}]] {:id id :publisher publisher})) (sort-by :id))) (defn- merge-pairs [& pairs] (into {} (mapcat (fn [v] (if (sequential? v) (map vec (partition 2 v)) v)) pairs))) (defonce dispatch-publishers (rb/recurring-task PUBLISH-INTERVAL (fn [] (try (let [pubs @publishers ;; group-by buffer pubs (group-by :buffer (map second pubs))] (doseq [[buf dests] pubs] ;; for every buffer (let [items (rb/items @buf) offset (-> items last first)] (when (seq items) (doseq [{pub :publisher} dests] ;; and each destination ;; send to the agent-buffer (send (p/agent-buffer pub) (partial reduce rb/enqueue) (->> items (map second) (map (partial apply merge-pairs))))) ;; remove items up to the offset (swap! buf rb/dequeue offset))))) (catch Exception x ;; TODO: (.printStackTrace x)))))) (defn start-publisher! [buffer config] (let [^PPublisher publisher (p/publisher-factory config) period (p/publish-delay publisher) period (max (or period PUBLISH-INTERVAL) PUBLISH-INTERVAL) ;; register publisher in dispatch list publisher-id (register-publisher! buffer publisher) deregister (fn [] (deregister-publisher! publisher-id)) publish (fn [] (send-off (p/agent-buffer publisher) (partial p/publish publisher))) ;; register periodic call publish stop (rb/recurring-task period publish) ;; prepare a stop function stopper (fn stop-publisher [] ;; remove publisher from listeners (deregister) ;; stop recurring calls to publisher (stop) ;; flush buffer (publish) ;; close publisher (when (instance? java.io.Closeable publisher) (send-off (p/agent-buffer publisher) (fn [_] (.close ^java.io.Closeable publisher)))) :stopped)] ;; register the stop function (swap! publishers assoc-in [publisher-id :stopper] stopper) ;; return the stop function stopper)) (defn stop-publisher! [publisher-id] ((get-in @publishers [publisher-id :stopper] (constantly :stopped)))) (defmacro on-error "internal utility macro" [default & body] `(try ~@body (catch Exception _# ~default))) (defmacro log-trace "internal utility macro" [event-name tid ptid duration ts outcome & pairs] `(com.brunobonacci.mulog/log ~event-name :mulog/trace-id ~tid :mulog/parent-trace ~ptid :mulog/duration ~duration :mulog/timestamp ~ts :mulog/outcome ~outcome ~@pairs)) (defmacro log-trace-capture "internal utility macro" [event-name tid ptid duration ts outcome capture result & pairs] (when capture `(com.brunobonacci.mulog/with-context (on-error {:mulog/capture :error} (~capture ~result)) (log-trace ~event-name ~tid ~ptid ~duration ~ts ~outcome ~@pairs))))
70595
(ns ^{:author "<NAME> (@BrunoBonacci)" :doc "Logging library designed to log data events instead of plain words." :no-doc true} com.brunobonacci.mulog.core (:require [com.brunobonacci.mulog.buffer :as rb] [com.brunobonacci.mulog.publisher :as p] [com.brunobonacci.mulog.flakes :refer [snowflake]]) (:import [com.brunobonacci.mulog.publisher PPublisher])) (def ^:const PUBLISH-INTERVAL 200) (defn dequeue! [buffer offset] (swap! buffer rb/dequeue offset)) (defn enqueue! [buffer value] (swap! buffer rb/enqueue value)) ;; ;; Stores the registered publishers ;; id -> {buffer, publisher, ?stopper} ;; (defonce publishers (atom {})) (defn register-publisher! [buffer publisher] (let [id (snowflake)] (swap! publishers assoc id {:buffer buffer :publisher publisher}) id)) (defn deregister-publisher! [id] (swap! publishers dissoc id)) (defn registered-publishers [] (->> @publishers (map (fn [[id {:keys [publisher]}]] {:id id :publisher publisher})) (sort-by :id))) (defn- merge-pairs [& pairs] (into {} (mapcat (fn [v] (if (sequential? v) (map vec (partition 2 v)) v)) pairs))) (defonce dispatch-publishers (rb/recurring-task PUBLISH-INTERVAL (fn [] (try (let [pubs @publishers ;; group-by buffer pubs (group-by :buffer (map second pubs))] (doseq [[buf dests] pubs] ;; for every buffer (let [items (rb/items @buf) offset (-> items last first)] (when (seq items) (doseq [{pub :publisher} dests] ;; and each destination ;; send to the agent-buffer (send (p/agent-buffer pub) (partial reduce rb/enqueue) (->> items (map second) (map (partial apply merge-pairs))))) ;; remove items up to the offset (swap! buf rb/dequeue offset))))) (catch Exception x ;; TODO: (.printStackTrace x)))))) (defn start-publisher! [buffer config] (let [^PPublisher publisher (p/publisher-factory config) period (p/publish-delay publisher) period (max (or period PUBLISH-INTERVAL) PUBLISH-INTERVAL) ;; register publisher in dispatch list publisher-id (register-publisher! buffer publisher) deregister (fn [] (deregister-publisher! publisher-id)) publish (fn [] (send-off (p/agent-buffer publisher) (partial p/publish publisher))) ;; register periodic call publish stop (rb/recurring-task period publish) ;; prepare a stop function stopper (fn stop-publisher [] ;; remove publisher from listeners (deregister) ;; stop recurring calls to publisher (stop) ;; flush buffer (publish) ;; close publisher (when (instance? java.io.Closeable publisher) (send-off (p/agent-buffer publisher) (fn [_] (.close ^java.io.Closeable publisher)))) :stopped)] ;; register the stop function (swap! publishers assoc-in [publisher-id :stopper] stopper) ;; return the stop function stopper)) (defn stop-publisher! [publisher-id] ((get-in @publishers [publisher-id :stopper] (constantly :stopped)))) (defmacro on-error "internal utility macro" [default & body] `(try ~@body (catch Exception _# ~default))) (defmacro log-trace "internal utility macro" [event-name tid ptid duration ts outcome & pairs] `(com.brunobonacci.mulog/log ~event-name :mulog/trace-id ~tid :mulog/parent-trace ~ptid :mulog/duration ~duration :mulog/timestamp ~ts :mulog/outcome ~outcome ~@pairs)) (defmacro log-trace-capture "internal utility macro" [event-name tid ptid duration ts outcome capture result & pairs] (when capture `(com.brunobonacci.mulog/with-context (on-error {:mulog/capture :error} (~capture ~result)) (log-trace ~event-name ~tid ~ptid ~duration ~ts ~outcome ~@pairs))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI (@BrunoBonacci)" :doc "Logging library designed to log data events instead of plain words." :no-doc true} com.brunobonacci.mulog.core (:require [com.brunobonacci.mulog.buffer :as rb] [com.brunobonacci.mulog.publisher :as p] [com.brunobonacci.mulog.flakes :refer [snowflake]]) (:import [com.brunobonacci.mulog.publisher PPublisher])) (def ^:const PUBLISH-INTERVAL 200) (defn dequeue! [buffer offset] (swap! buffer rb/dequeue offset)) (defn enqueue! [buffer value] (swap! buffer rb/enqueue value)) ;; ;; Stores the registered publishers ;; id -> {buffer, publisher, ?stopper} ;; (defonce publishers (atom {})) (defn register-publisher! [buffer publisher] (let [id (snowflake)] (swap! publishers assoc id {:buffer buffer :publisher publisher}) id)) (defn deregister-publisher! [id] (swap! publishers dissoc id)) (defn registered-publishers [] (->> @publishers (map (fn [[id {:keys [publisher]}]] {:id id :publisher publisher})) (sort-by :id))) (defn- merge-pairs [& pairs] (into {} (mapcat (fn [v] (if (sequential? v) (map vec (partition 2 v)) v)) pairs))) (defonce dispatch-publishers (rb/recurring-task PUBLISH-INTERVAL (fn [] (try (let [pubs @publishers ;; group-by buffer pubs (group-by :buffer (map second pubs))] (doseq [[buf dests] pubs] ;; for every buffer (let [items (rb/items @buf) offset (-> items last first)] (when (seq items) (doseq [{pub :publisher} dests] ;; and each destination ;; send to the agent-buffer (send (p/agent-buffer pub) (partial reduce rb/enqueue) (->> items (map second) (map (partial apply merge-pairs))))) ;; remove items up to the offset (swap! buf rb/dequeue offset))))) (catch Exception x ;; TODO: (.printStackTrace x)))))) (defn start-publisher! [buffer config] (let [^PPublisher publisher (p/publisher-factory config) period (p/publish-delay publisher) period (max (or period PUBLISH-INTERVAL) PUBLISH-INTERVAL) ;; register publisher in dispatch list publisher-id (register-publisher! buffer publisher) deregister (fn [] (deregister-publisher! publisher-id)) publish (fn [] (send-off (p/agent-buffer publisher) (partial p/publish publisher))) ;; register periodic call publish stop (rb/recurring-task period publish) ;; prepare a stop function stopper (fn stop-publisher [] ;; remove publisher from listeners (deregister) ;; stop recurring calls to publisher (stop) ;; flush buffer (publish) ;; close publisher (when (instance? java.io.Closeable publisher) (send-off (p/agent-buffer publisher) (fn [_] (.close ^java.io.Closeable publisher)))) :stopped)] ;; register the stop function (swap! publishers assoc-in [publisher-id :stopper] stopper) ;; return the stop function stopper)) (defn stop-publisher! [publisher-id] ((get-in @publishers [publisher-id :stopper] (constantly :stopped)))) (defmacro on-error "internal utility macro" [default & body] `(try ~@body (catch Exception _# ~default))) (defmacro log-trace "internal utility macro" [event-name tid ptid duration ts outcome & pairs] `(com.brunobonacci.mulog/log ~event-name :mulog/trace-id ~tid :mulog/parent-trace ~ptid :mulog/duration ~duration :mulog/timestamp ~ts :mulog/outcome ~outcome ~@pairs)) (defmacro log-trace-capture "internal utility macro" [event-name tid ptid duration ts outcome capture result & pairs] (when capture `(com.brunobonacci.mulog/with-context (on-error {:mulog/capture :error} (~capture ~result)) (log-trace ~event-name ~tid ~ptid ~duration ~ts ~outcome ~@pairs))))
[ { "context": "Mapping von DB Types auf Java Types\r\n;;\r\n;; Autor: Christian Meichsner\r\n\r\n(ns org.lambdaroyal.util.db.dbcrud\r\n (:requir", "end": 199, "score": 0.9998791813850403, "start": 180, "tag": "NAME", "value": "Christian Meichsner" }, { "context": "alues])))\r\n\r\n;; Thanks to https://gist.github.com/joodie/373677\r\n(defn insert-record \r\n \"Equivalent of cl", "end": 1690, "score": 0.9995513558387756, "start": 1684, "tag": "USERNAME", "value": "joodie" } ]
src/main/clojure/org/lambdaroyal/util/db/dbcrud.clj
gixxi/clojure-util
1
;; Aspekt Hilfsfunktionen für Grundlegende Operationen wie ;; Einfügen, Löschen, Update, Records Einfügen mit Id Rückgabe, ;; Mapping von DB Types auf Java Types ;; ;; Autor: Christian Meichsner (ns org.lambdaroyal.util.db.dbcrud (:require [org.lambdaroyal.util.db.dbconfig :as dbconfig]) (:require [clojure.java.jdbc :as sql]) (:import [java.text SimpleDateFormat] [org.lambdaroyal.util ConsoleProgress]) (:import [java.util Date]) (:import [org.apache.tomcat.jdbc.pool DataSource]) (:import [org.lambdaroyal.util ConsoleProgress]) (:gen-class)) ;; the following is mostly from ;; http://gist.github.com/373564#file_sql.clj ;;==== Internal functions ====================================================== (defn- join "Joins the items in the given collection into a single string separated with the string separator." [separator col] (apply str (interpose separator col))) (defn- sql-for-insert "Converts a table identifier (keyword or string) and a hash identifying a record into an sql insert statement compatible with prepareStatement Returns [sql values-to-insert]" [table record] (let [table-name (if (instance? clojure.lang.Keyword table) (.getName table) table) columns (map #(if (instance? clojure.lang.Keyword %1) (.getName %1) %1) (keys record)) values (vals record) n (count columns) template (join "," (replicate n "?")) column-names (join "," columns) sql (format "insert into %s (%s) values (%s)" table-name column-names template)] (do [sql values]))) ;; Thanks to https://gist.github.com/joodie/373677 (defn insert-record "Equivalent of clojure.contrib.sql/insert-records that only inserts a single record but returns the autogenerated id of that record if available." [table record] (let [[sql values] (sql-for-insert table record)] (with-open [statement (.prepareStatement (sql/connection) sql)] (doseq [[index value] (map vector (iterate inc 1) values)] (.setObject statement index value)) (.execute statement) (let [rs (.getGeneratedKeys statement)] (if (.next rs) (if-let [id (.getObject rs 1)] id nil)) nil) nil))) ;; Thanks to http://stackoverflow.com/questions/3632260/clojure-how-to-insert-a-blob-in-database (defn doPrepared "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of the parameters. This is a modified version of clojure.contrib.sql/do-prepared with special handling of byte arrays." [sql & param-groups] (with-open [stmt (.prepareStatement (sql/connection) sql)] (doseq [param-group param-groups] (doseq [[index value] (map vector (iterate inc 1) param-group)] (cond (= (class value) (class (.getBytes ""))) (.setBytes stmt index value) (= (class value) java.io.ObjectInputStream) (.setBlob stmt index value) :else (.setObject stmt index value))) (.addBatch stmt)) (sql/transaction (seq (.executeBatch stmt))))) ;; ;; Hilfsfunktionen für das Mapping auf Zieldatentypen ;; (defn doubleStringToLong [x] "rundet die Double Interpretation von x" (Math/round (Double/parseDouble (.trim x)))) (defn stringToInt [x] (cond (nil? x) nil (= "" x) nil :else (java.lang.Integer/parseInt (.trim x)))) (defn stringToString [x] (.trim x)) (defn ^Date parse-date [s fm] (.parse (SimpleDateFormat. fm) s)) (defn stringToNumber [x f] "Parses the number string <x> using format <f> (DecimalFormat)" (let [formatter (new java.text.DecimalFormat f)] (.parse formatter (.trim x)))) (defn stringToNumberDouble [x f] (.doubleValue (stringToNumber x f))) (defn stringToNumberLong [x f] (.longValue (stringToNumber x f))) (defn stringToDecimal ([x] "Wandelt einen String _unreflektiert_ in eine BigDecimal um" (new java.math.BigDecimal (.trim x))) ([x ^String f ^Integer s ^java.math.RoundingMode r] "Wandelt einen String zuerst per stringToNumberDouble in eine Gleitkommazahl um und anschliessend wird eine Scalierung auf <s> Nachkommastellen mit einem Rundung r vorgenommen" (.setScale (new java.math.BigDecimal (stringToNumberDouble x f)) s r))) (defn select [^DataSource datasource select] "Gibt den letzten record zurück, welcher durch ein select geliefert wird" (sql/with-connection {:datasource datasource} (sql/with-query-results res [select] (into {} res))))
81973
;; Aspekt Hilfsfunktionen für Grundlegende Operationen wie ;; Einfügen, Löschen, Update, Records Einfügen mit Id Rückgabe, ;; Mapping von DB Types auf Java Types ;; ;; Autor: <NAME> (ns org.lambdaroyal.util.db.dbcrud (:require [org.lambdaroyal.util.db.dbconfig :as dbconfig]) (:require [clojure.java.jdbc :as sql]) (:import [java.text SimpleDateFormat] [org.lambdaroyal.util ConsoleProgress]) (:import [java.util Date]) (:import [org.apache.tomcat.jdbc.pool DataSource]) (:import [org.lambdaroyal.util ConsoleProgress]) (:gen-class)) ;; the following is mostly from ;; http://gist.github.com/373564#file_sql.clj ;;==== Internal functions ====================================================== (defn- join "Joins the items in the given collection into a single string separated with the string separator." [separator col] (apply str (interpose separator col))) (defn- sql-for-insert "Converts a table identifier (keyword or string) and a hash identifying a record into an sql insert statement compatible with prepareStatement Returns [sql values-to-insert]" [table record] (let [table-name (if (instance? clojure.lang.Keyword table) (.getName table) table) columns (map #(if (instance? clojure.lang.Keyword %1) (.getName %1) %1) (keys record)) values (vals record) n (count columns) template (join "," (replicate n "?")) column-names (join "," columns) sql (format "insert into %s (%s) values (%s)" table-name column-names template)] (do [sql values]))) ;; Thanks to https://gist.github.com/joodie/373677 (defn insert-record "Equivalent of clojure.contrib.sql/insert-records that only inserts a single record but returns the autogenerated id of that record if available." [table record] (let [[sql values] (sql-for-insert table record)] (with-open [statement (.prepareStatement (sql/connection) sql)] (doseq [[index value] (map vector (iterate inc 1) values)] (.setObject statement index value)) (.execute statement) (let [rs (.getGeneratedKeys statement)] (if (.next rs) (if-let [id (.getObject rs 1)] id nil)) nil) nil))) ;; Thanks to http://stackoverflow.com/questions/3632260/clojure-how-to-insert-a-blob-in-database (defn doPrepared "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of the parameters. This is a modified version of clojure.contrib.sql/do-prepared with special handling of byte arrays." [sql & param-groups] (with-open [stmt (.prepareStatement (sql/connection) sql)] (doseq [param-group param-groups] (doseq [[index value] (map vector (iterate inc 1) param-group)] (cond (= (class value) (class (.getBytes ""))) (.setBytes stmt index value) (= (class value) java.io.ObjectInputStream) (.setBlob stmt index value) :else (.setObject stmt index value))) (.addBatch stmt)) (sql/transaction (seq (.executeBatch stmt))))) ;; ;; Hilfsfunktionen für das Mapping auf Zieldatentypen ;; (defn doubleStringToLong [x] "rundet die Double Interpretation von x" (Math/round (Double/parseDouble (.trim x)))) (defn stringToInt [x] (cond (nil? x) nil (= "" x) nil :else (java.lang.Integer/parseInt (.trim x)))) (defn stringToString [x] (.trim x)) (defn ^Date parse-date [s fm] (.parse (SimpleDateFormat. fm) s)) (defn stringToNumber [x f] "Parses the number string <x> using format <f> (DecimalFormat)" (let [formatter (new java.text.DecimalFormat f)] (.parse formatter (.trim x)))) (defn stringToNumberDouble [x f] (.doubleValue (stringToNumber x f))) (defn stringToNumberLong [x f] (.longValue (stringToNumber x f))) (defn stringToDecimal ([x] "Wandelt einen String _unreflektiert_ in eine BigDecimal um" (new java.math.BigDecimal (.trim x))) ([x ^String f ^Integer s ^java.math.RoundingMode r] "Wandelt einen String zuerst per stringToNumberDouble in eine Gleitkommazahl um und anschliessend wird eine Scalierung auf <s> Nachkommastellen mit einem Rundung r vorgenommen" (.setScale (new java.math.BigDecimal (stringToNumberDouble x f)) s r))) (defn select [^DataSource datasource select] "Gibt den letzten record zurück, welcher durch ein select geliefert wird" (sql/with-connection {:datasource datasource} (sql/with-query-results res [select] (into {} res))))
true
;; Aspekt Hilfsfunktionen für Grundlegende Operationen wie ;; Einfügen, Löschen, Update, Records Einfügen mit Id Rückgabe, ;; Mapping von DB Types auf Java Types ;; ;; Autor: PI:NAME:<NAME>END_PI (ns org.lambdaroyal.util.db.dbcrud (:require [org.lambdaroyal.util.db.dbconfig :as dbconfig]) (:require [clojure.java.jdbc :as sql]) (:import [java.text SimpleDateFormat] [org.lambdaroyal.util ConsoleProgress]) (:import [java.util Date]) (:import [org.apache.tomcat.jdbc.pool DataSource]) (:import [org.lambdaroyal.util ConsoleProgress]) (:gen-class)) ;; the following is mostly from ;; http://gist.github.com/373564#file_sql.clj ;;==== Internal functions ====================================================== (defn- join "Joins the items in the given collection into a single string separated with the string separator." [separator col] (apply str (interpose separator col))) (defn- sql-for-insert "Converts a table identifier (keyword or string) and a hash identifying a record into an sql insert statement compatible with prepareStatement Returns [sql values-to-insert]" [table record] (let [table-name (if (instance? clojure.lang.Keyword table) (.getName table) table) columns (map #(if (instance? clojure.lang.Keyword %1) (.getName %1) %1) (keys record)) values (vals record) n (count columns) template (join "," (replicate n "?")) column-names (join "," columns) sql (format "insert into %s (%s) values (%s)" table-name column-names template)] (do [sql values]))) ;; Thanks to https://gist.github.com/joodie/373677 (defn insert-record "Equivalent of clojure.contrib.sql/insert-records that only inserts a single record but returns the autogenerated id of that record if available." [table record] (let [[sql values] (sql-for-insert table record)] (with-open [statement (.prepareStatement (sql/connection) sql)] (doseq [[index value] (map vector (iterate inc 1) values)] (.setObject statement index value)) (.execute statement) (let [rs (.getGeneratedKeys statement)] (if (.next rs) (if-let [id (.getObject rs 1)] id nil)) nil) nil))) ;; Thanks to http://stackoverflow.com/questions/3632260/clojure-how-to-insert-a-blob-in-database (defn doPrepared "Executes an (optionally parameterized) SQL prepared statement on the open database connection. Each param-group is a seq of values for all of the parameters. This is a modified version of clojure.contrib.sql/do-prepared with special handling of byte arrays." [sql & param-groups] (with-open [stmt (.prepareStatement (sql/connection) sql)] (doseq [param-group param-groups] (doseq [[index value] (map vector (iterate inc 1) param-group)] (cond (= (class value) (class (.getBytes ""))) (.setBytes stmt index value) (= (class value) java.io.ObjectInputStream) (.setBlob stmt index value) :else (.setObject stmt index value))) (.addBatch stmt)) (sql/transaction (seq (.executeBatch stmt))))) ;; ;; Hilfsfunktionen für das Mapping auf Zieldatentypen ;; (defn doubleStringToLong [x] "rundet die Double Interpretation von x" (Math/round (Double/parseDouble (.trim x)))) (defn stringToInt [x] (cond (nil? x) nil (= "" x) nil :else (java.lang.Integer/parseInt (.trim x)))) (defn stringToString [x] (.trim x)) (defn ^Date parse-date [s fm] (.parse (SimpleDateFormat. fm) s)) (defn stringToNumber [x f] "Parses the number string <x> using format <f> (DecimalFormat)" (let [formatter (new java.text.DecimalFormat f)] (.parse formatter (.trim x)))) (defn stringToNumberDouble [x f] (.doubleValue (stringToNumber x f))) (defn stringToNumberLong [x f] (.longValue (stringToNumber x f))) (defn stringToDecimal ([x] "Wandelt einen String _unreflektiert_ in eine BigDecimal um" (new java.math.BigDecimal (.trim x))) ([x ^String f ^Integer s ^java.math.RoundingMode r] "Wandelt einen String zuerst per stringToNumberDouble in eine Gleitkommazahl um und anschliessend wird eine Scalierung auf <s> Nachkommastellen mit einem Rundung r vorgenommen" (.setScale (new java.math.BigDecimal (stringToNumberDouble x f)) s r))) (defn select [^DataSource datasource select] "Gibt den letzten record zurück, welcher durch ein select geliefert wird" (sql/with-connection {:datasource datasource} (sql/with-query-results res [select] (into {} res))))
[ { "context": "f (or\n (= input \"fork@form.com\")\n (= input \"for", "end": 2470, "score": 0.9999233484268188, "start": 2457, "tag": "EMAIL", "value": "fork@form.com" }, { "context": "com\")\n (= input \"fork@clojure.com\")\n (= input \"for", "end": 2533, "score": 0.9999235272407532, "start": 2517, "tag": "EMAIL", "value": "fork@clojure.com" }, { "context": "com\")\n (= input \"fork@cljs.com\"))\n {:validation fa", "end": 2593, "score": 0.9999251365661621, "start": 2580, "tag": "EMAIL", "value": "fork@cljs.com" } ]
fork.forms/src/fork/forms/web.clj
luciodale/fork-website
0
(ns fork.forms.web (:require [aleph.http :as http] [byte-streams :as bs] [cheshire.core :refer [parse-string]] [fork.forms.env :as env] [integrant.core :as ig] [manifold.deferred :as d] [yada.yada :as yada])) (defn manage-blank [coll] (if (= 2 (-> coll :double-space inc)) (-> coll (update :data conj nil) (assoc :double-space 0) (update :index inc)) (update coll :double-space inc))) (defn reset-double-space [coll] (assoc coll :double-space 0)) (defn attach-str [coll this] (update coll :data (fn [data] (update data (:index coll) #(str % this "\n"))))) (defn parse-snippets [snippets] (with-open [file (clojure.java.io/reader (clojure.java.io/input-stream (clojure.java.io/resource snippets)))] (:data (reduce (fn [{:keys [double-space data] :as coll} this] (cond-> coll (empty? this) manage-blank (not-empty this) reset-double-space true (attach-str this))) {:double-space 0 :data [] :index 0} (line-seq file))))) (defmethod ig/init-key ::docs [_ file] (yada/resource {:id ::snippets :methods {:get {:produces ["application/transit+json"] :response (fn [ctx] (parse-snippets file))}}})) ;; just for testing (defmethod ig/init-key ::server-validation [_ _] (yada/resource {:id ::server-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :input)] (prn "in endpoint input:" input) (Thread/sleep 2000) (if (= input "server-input") {:validation true} {:validation false})))}}})) (defmethod ig/init-key ::reg-validation [_ _] (yada/resource {:id ::reg-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :email)] (if (or (= input "fork@form.com") (= input "fork@clojure.com") (= input "fork@cljs.com")) {:validation false} {:validation true})))}}})) (defmethod ig/init-key ::weather [_ _] (yada/resource {:id ::weather :methods {:get {:produces ["application/json"] :response (fn [ctx] (let [lat ((-> ctx :parameters :query) "lat") lng ((-> ctx :parameters :query) "lng")] (d/chain (http/get (str "http://api.openweathermap.org/data/2.5/weather" "?lat=" lat "&lon=" lng "&units=metric" "&APPID="env/weather-key)) #(:body %) #(bs/to-string %) #(parse-string % true))))}}}))
114560
(ns fork.forms.web (:require [aleph.http :as http] [byte-streams :as bs] [cheshire.core :refer [parse-string]] [fork.forms.env :as env] [integrant.core :as ig] [manifold.deferred :as d] [yada.yada :as yada])) (defn manage-blank [coll] (if (= 2 (-> coll :double-space inc)) (-> coll (update :data conj nil) (assoc :double-space 0) (update :index inc)) (update coll :double-space inc))) (defn reset-double-space [coll] (assoc coll :double-space 0)) (defn attach-str [coll this] (update coll :data (fn [data] (update data (:index coll) #(str % this "\n"))))) (defn parse-snippets [snippets] (with-open [file (clojure.java.io/reader (clojure.java.io/input-stream (clojure.java.io/resource snippets)))] (:data (reduce (fn [{:keys [double-space data] :as coll} this] (cond-> coll (empty? this) manage-blank (not-empty this) reset-double-space true (attach-str this))) {:double-space 0 :data [] :index 0} (line-seq file))))) (defmethod ig/init-key ::docs [_ file] (yada/resource {:id ::snippets :methods {:get {:produces ["application/transit+json"] :response (fn [ctx] (parse-snippets file))}}})) ;; just for testing (defmethod ig/init-key ::server-validation [_ _] (yada/resource {:id ::server-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :input)] (prn "in endpoint input:" input) (Thread/sleep 2000) (if (= input "server-input") {:validation true} {:validation false})))}}})) (defmethod ig/init-key ::reg-validation [_ _] (yada/resource {:id ::reg-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :email)] (if (or (= input "<EMAIL>") (= input "<EMAIL>") (= input "<EMAIL>")) {:validation false} {:validation true})))}}})) (defmethod ig/init-key ::weather [_ _] (yada/resource {:id ::weather :methods {:get {:produces ["application/json"] :response (fn [ctx] (let [lat ((-> ctx :parameters :query) "lat") lng ((-> ctx :parameters :query) "lng")] (d/chain (http/get (str "http://api.openweathermap.org/data/2.5/weather" "?lat=" lat "&lon=" lng "&units=metric" "&APPID="env/weather-key)) #(:body %) #(bs/to-string %) #(parse-string % true))))}}}))
true
(ns fork.forms.web (:require [aleph.http :as http] [byte-streams :as bs] [cheshire.core :refer [parse-string]] [fork.forms.env :as env] [integrant.core :as ig] [manifold.deferred :as d] [yada.yada :as yada])) (defn manage-blank [coll] (if (= 2 (-> coll :double-space inc)) (-> coll (update :data conj nil) (assoc :double-space 0) (update :index inc)) (update coll :double-space inc))) (defn reset-double-space [coll] (assoc coll :double-space 0)) (defn attach-str [coll this] (update coll :data (fn [data] (update data (:index coll) #(str % this "\n"))))) (defn parse-snippets [snippets] (with-open [file (clojure.java.io/reader (clojure.java.io/input-stream (clojure.java.io/resource snippets)))] (:data (reduce (fn [{:keys [double-space data] :as coll} this] (cond-> coll (empty? this) manage-blank (not-empty this) reset-double-space true (attach-str this))) {:double-space 0 :data [] :index 0} (line-seq file))))) (defmethod ig/init-key ::docs [_ file] (yada/resource {:id ::snippets :methods {:get {:produces ["application/transit+json"] :response (fn [ctx] (parse-snippets file))}}})) ;; just for testing (defmethod ig/init-key ::server-validation [_ _] (yada/resource {:id ::server-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :input)] (prn "in endpoint input:" input) (Thread/sleep 2000) (if (= input "server-input") {:validation true} {:validation false})))}}})) (defmethod ig/init-key ::reg-validation [_ _] (yada/resource {:id ::reg-validation :methods {:post {:consumes ["application/transit+json"] :produces ["application/transit+json"] :response (fn [ctx] (let [input (-> ctx :body :email)] (if (or (= input "PI:EMAIL:<EMAIL>END_PI") (= input "PI:EMAIL:<EMAIL>END_PI") (= input "PI:EMAIL:<EMAIL>END_PI")) {:validation false} {:validation true})))}}})) (defmethod ig/init-key ::weather [_ _] (yada/resource {:id ::weather :methods {:get {:produces ["application/json"] :response (fn [ctx] (let [lat ((-> ctx :parameters :query) "lat") lng ((-> ctx :parameters :query) "lng")] (d/chain (http/get (str "http://api.openweathermap.org/data/2.5/weather" "?lat=" lat "&lon=" lng "&units=metric" "&APPID="env/weather-key)) #(:body %) #(bs/to-string %) #(parse-string % true))))}}}))
[ { "context": ":dynamic *throw-exceptions* false)\n(def username \"p1-rabbit\")\n(def password \"p1-rabbit-testpwd\")\n\n(defn load-", "end": 367, "score": 0.9046329855918884, "start": 358, "tag": "USERNAME", "value": "p1-rabbit" }, { "context": " false)\n(def username \"p1-rabbit\")\n(def password \"p1-rabbit-testpwd\")\n\n(defn load-config!\n [^String relative-resourc", "end": 402, "score": 0.9994276165962219, "start": 385, "tag": "PASSWORD", "value": "p1-rabbit-testpwd" }, { "context": " (json/decode (:body (httpc/put (format \"%s://127.0.0.1:4567/%s\" scheme path)\n ", "end": 1993, "score": 0.9689444303512573, "start": 1984, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "body] :as options}]\n (httpc/put (format \"%s://127.0.0.1:4567/%s\" scheme path)\n (merge opti", "end": 2571, "score": 0.9980625510215759, "start": 2562, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " (json/decode (:body (httpc/delete (format \"%s://127.0.0.1:4567/%s\" scheme path)\n ", "end": 3082, "score": 0.9945933222770691, "start": 3073, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "y] :as options}]\n (httpc/delete (format \"%s://127.0.0.1:4567/%s\" scheme path)\n (merge o", "end": 3684, "score": 0.999038577079773, "start": 3675, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
src/rabbitmq-broker/test/io/pivotal/pcf/rabbitmq/test_helpers.clj
making/cf-rabbitmq-multitenant-broker-release
1
(ns io.pivotal.pcf.rabbitmq.test-helpers (:refer-clojure :exclude [get]) (:require [clojure.java.io :as io] [langohr.http :as hc] [clj-yaml.core :as yaml] [clojure.test :refer :all] [clj-http.client :as httpc] [cheshire.core :as json])) (def ^:dynamic *throw-exceptions* false) (def username "p1-rabbit") (def password "p1-rabbit-testpwd") (defn load-config! [^String relative-resource-path] (yaml/parse-string (slurp (io/resource relative-resource-path)))) (def load-config (memoize load-config!)) (defn has-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (nil? (:error policy))) (is (nil? (:reason policy))) (is (= (:name policy) policy-name))))) (defn has-no-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (:error policy)) (is (:reason policy))))) (defn has-policy-with-definition? [^String vhost ^String policy-name policy-definition policy-priority] (has-policy? vhost policy-name) (testing "policy has valid pattern, ha-mode and ha-sync-mode" (let [policy (hc/get-policies vhost policy-name)] (is (= (:pattern policy) ".*")) (is (= (:apply-to policy) "all")) (is (= (:definition policy) policy-definition)) (is (= (:priority policy) policy-priority))))) (defn get ([^String path] (get path "http")) ([^String path ^String scheme] (json/decode (:body (httpc/get (format "%s://127.0.0.1:4567/%s" scheme path) {:basic-auth [username password]})) true))) (defn put ([^String path] (put path "http" {})) ([^String path ^String scheme] (put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-put ([^String path] (raw-put path "http" {})) ([^String path ^String scheme] (raw-put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*})))) (defn delete ([^String path] (delete path "http" {})) ([^String path ^String scheme] (delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-delete ([^String path] (raw-delete path "http" {})) ([^String path ^String scheme] (raw-delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))))
79689
(ns io.pivotal.pcf.rabbitmq.test-helpers (:refer-clojure :exclude [get]) (:require [clojure.java.io :as io] [langohr.http :as hc] [clj-yaml.core :as yaml] [clojure.test :refer :all] [clj-http.client :as httpc] [cheshire.core :as json])) (def ^:dynamic *throw-exceptions* false) (def username "p1-rabbit") (def password "<PASSWORD>") (defn load-config! [^String relative-resource-path] (yaml/parse-string (slurp (io/resource relative-resource-path)))) (def load-config (memoize load-config!)) (defn has-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (nil? (:error policy))) (is (nil? (:reason policy))) (is (= (:name policy) policy-name))))) (defn has-no-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (:error policy)) (is (:reason policy))))) (defn has-policy-with-definition? [^String vhost ^String policy-name policy-definition policy-priority] (has-policy? vhost policy-name) (testing "policy has valid pattern, ha-mode and ha-sync-mode" (let [policy (hc/get-policies vhost policy-name)] (is (= (:pattern policy) ".*")) (is (= (:apply-to policy) "all")) (is (= (:definition policy) policy-definition)) (is (= (:priority policy) policy-priority))))) (defn get ([^String path] (get path "http")) ([^String path ^String scheme] (json/decode (:body (httpc/get (format "%s://127.0.0.1:4567/%s" scheme path) {:basic-auth [username password]})) true))) (defn put ([^String path] (put path "http" {})) ([^String path ^String scheme] (put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-put ([^String path] (raw-put path "http" {})) ([^String path ^String scheme] (raw-put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*})))) (defn delete ([^String path] (delete path "http" {})) ([^String path ^String scheme] (delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-delete ([^String path] (raw-delete path "http" {})) ([^String path ^String scheme] (raw-delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))))
true
(ns io.pivotal.pcf.rabbitmq.test-helpers (:refer-clojure :exclude [get]) (:require [clojure.java.io :as io] [langohr.http :as hc] [clj-yaml.core :as yaml] [clojure.test :refer :all] [clj-http.client :as httpc] [cheshire.core :as json])) (def ^:dynamic *throw-exceptions* false) (def username "p1-rabbit") (def password "PI:PASSWORD:<PASSWORD>END_PI") (defn load-config! [^String relative-resource-path] (yaml/parse-string (slurp (io/resource relative-resource-path)))) (def load-config (memoize load-config!)) (defn has-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (nil? (:error policy))) (is (nil? (:reason policy))) (is (= (:name policy) policy-name))))) (defn has-no-policy? [^String vhost ^String policy-name] (let [policy (hc/get-policies vhost policy-name)] (testing "policy exists" (is (:error policy)) (is (:reason policy))))) (defn has-policy-with-definition? [^String vhost ^String policy-name policy-definition policy-priority] (has-policy? vhost policy-name) (testing "policy has valid pattern, ha-mode and ha-sync-mode" (let [policy (hc/get-policies vhost policy-name)] (is (= (:pattern policy) ".*")) (is (= (:apply-to policy) "all")) (is (= (:definition policy) policy-definition)) (is (= (:priority policy) policy-priority))))) (defn get ([^String path] (get path "http")) ([^String path ^String scheme] (json/decode (:body (httpc/get (format "%s://127.0.0.1:4567/%s" scheme path) {:basic-auth [username password]})) true))) (defn put ([^String path] (put path "http" {})) ([^String path ^String scheme] (put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-put ([^String path] (raw-put path "http" {})) ([^String path ^String scheme] (raw-put path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/put (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*})))) (defn delete ([^String path] (delete path "http" {})) ([^String path ^String scheme] (delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (json/decode (:body (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))) true))) (defn raw-delete ([^String path] (raw-delete path "http" {})) ([^String path ^String scheme] (raw-delete path scheme {})) ([^String path ^String scheme {:keys [body] :as options}] (httpc/delete (format "%s://127.0.0.1:4567/%s" scheme path) (merge options {:basic-auth [username password] :accept :json :body (json/encode body) :throw-exceptions *throw-exceptions*}))))
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.bixby.plugs.mail", "end": 597, "score": 0.9998586773872375, "start": 584, "tag": "NAME", "value": "Kenneth Leung" }, { "context": " :delete-msg? false\n :username \"joe\"\n :passwd \"secret\"\n :interval-s", "end": 6567, "score": 0.9996455311775208, "start": 6564, "tag": "USERNAME", "value": "joe" }, { "context": "alse\n :username \"joe\"\n :passwd \"secret\"\n :interval-secs 300\n :delay-se", "end": 6594, "score": 0.9993805289268494, "start": 6588, "tag": "PASSWORD", "value": "secret" }, { "context": "? false\n :ssl? true\n :username \"joe\"\n :passwd \"secret\"\n :interval-s", "end": 8510, "score": 0.9993157386779785, "start": 8507, "tag": "USERNAME", "value": "joe" }, { "context": "true\n :username \"joe\"\n :passwd \"secret\"\n :interval-secs 300\n :delay-se", "end": 8537, "score": 0.9995077848434448, "start": 8531, "tag": "PASSWORD", "value": "secret" } ]
src/main/clojure/czlab/bixby/plugs/mails.clj
llnek/skaro
0
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, Kenneth Leung. All rights reserved. (ns czlab.bixby.plugs.mails "Implementation for email services." (:require [czlab.bixby.core :as b] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.twisty.codec :as co] [czlab.bixby.plugs.loops :as l]) (:import [javax.mail.internet MimeMessage] [clojure.lang APersistentMap] [javax.mail Flags$Flag Flags Store Folder Session Provider Provider$Type] [java.util Properties] [java.io IOException])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:dynamic *mock-mail-provider* {:pop3s "czlab.bixby.mock.mail.MockPop3SSLStore" :imaps "czlab.bixby.mock.mail.MockIMapSSLStore" :pop3 "czlab.bixby.mock.mail.MockPop3Store" :imap "czlab.bixby.mock.mail.MockIMapStore"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POP3 (c/def- cz-pop3s "com.sun.mail.pop3.POP3SSLStore") (c/def- cz-pop3 "com.sun.mail.pop3.POP3Store") (c/def- pop3s "pop3s") (c/def- pop3 "pop3") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IMAP (c/def- cz-imaps "com.sun.mail.imap.IMAPSSLStore") (c/def- cz-imap "com.sun.mail.imap.IMAPStore") (c/def- imaps "imaps") (c/def- imap "imap") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-folder [^Folder fd] (and fd (c/try! (if (.isOpen fd) (.close fd true))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-store [^Store store] (c/try! (some-> store .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailMsg [] c/Idable (id [_] (:id _)) c/Hierarchical (parent [me] (:source me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- evt<> [co msg] (c/object<> MailMsg :source co :message msg :id (str "MailMsg#" (u/seqint2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sanitize [pkey {:keys [port delete-msg? host user ssl? passwd] :as cfg0}] (-> cfg0 (assoc :ssl? (c/!false? ssl?)) (assoc :delete-msg? (true? delete-msg?)) (assoc :host (str host)) (assoc :port (if (c/spos? port) port 995)) (assoc :user (str user)) (assoc :passwd (co/pw-text (co/pwd<> passwd pkey))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- init2 [plug [cz proto :as arg]] (let [mockp (u/get-sys-prop "bixby.mock.mail.proto") demo? (c/hgl? mockp) cz (name cz) proto (name (if demo? mockp proto)) demop ((keyword proto) *mock-mail-provider*) ss (Session/getInstance (doto (Properties.) (.put "mail.store.protocol" proto)) nil) [^Provider sun ^String pz] (if demo? [(Provider. Provider$Type/STORE proto demop "czlab" "1.1.7") demop] [(some #(if (c/eq? cz (.getClassName ^Provider %)) %) (.getProviders ss)) cz])] (u/assert-IOE (some? sun) "Failed to find store: %s" pz) (c/info "mail store impl = %s" sun) (.setProvider ss sun) (assoc plug :proto proto :pz pz :session ss))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailPlugin [server _id info conf wakerFunc] c/Connectable (disconnect [_] _) (connect [_] (c/connect _ nil)) (connect [me _] (let [{:keys [proto session]} me {:keys [host user port passwd]} conf s (.getStore ^Session session ^String proto)] (if (nil? s) (c/do->nil (c/warn "failed to get session store [%s]." proto)) (let [_ (c/debug "connecting to session store [%s]..." proto) _ (.connect s ^String host ^long port ^String user (c/stror (i/x->str passwd) nil)) fd (some-> (.getDefaultFolder s) (.getFolder "INBOX"))] (when (or (nil? fd) (not (.exists fd))) (c/warn "bad mail store folder#%s." proto) (c/try! (.close s)) (u/throw-IOE "Cannot find inbox!")) [s fd])))) c/Hierarchical (parent [_] server) c/Idable (id [_] _id) c/Initable (init [me arg] (let [{:keys [sslvars vars]} me pk (i/x->chars (-> me c/parent b/pkey))] (-> (update-in me [:conf] #(sanitize pk (-> (c/merge+ % arg) b/expand-vars* b/prevar-cfg))) (init2 (if (:ssl? conf) sslvars vars))))) c/Finzable (finz [_] (c/stop _)) c/Startable (stop [me] (l/stop-threaded-loop! (:loopy me)) me) (start [_] (c/start _ nil)) (start [me _] (assoc me :loopy (l/schedule-threaded-loop me wakerFunc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- email-xxx [server id {:keys [info conf]} sslvars vars wakerFunc] (-> (MailPlugin. server id info conf wakerFunc) (assoc :sslvars sslvars :vars vars))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} POP3Spec {:info {:name "POP3 Client" :version "1.0.0"} :conf {:$pluggable ::pop3<> :host "pop.gmail.com" :port 995 :delete-msg? false :username "joe" :passwd "secret" :interval-secs 300 :delay-secs 0 :ssl? true :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan* [plug ^Store store ^Folder folder] (letfn [(read* [msgs] (let [d? (get-in plug [:conf :delete-msg?])] (doseq [^MimeMessage mm msgs] (doto mm .getAllHeaders .getContent) (when d? (.setFlag mm Flags$Flag/DELETED true)) (b/dispatch (evt<> plug mm)))))] (when folder (if-not (.isOpen folder) (.open folder Folder/READ_WRITE))) (when (.isOpen folder) (try (let [cnt (.getMessageCount folder)] (c/debug "count of new mail-messages: %d." cnt) (if (c/spos? cnt) (read* (.getMessages folder)))) (finally (c/try! (.close folder true))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-pop3 [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-imap [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} IMAPSpec {:info {:name "IMAP Client" :version "1.0.0"} :conf {:$pluggable ::imap<> :host "imap.gmail.com" :port 993 :delete-msg? false :ssl? true :username "joe" :passwd "secret" :interval-secs 300 :delay-secs 0 :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn imap<> "Create a IMAP Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (imap _ id IMAPSpec)) ([_ id spec] (email-xxx _ id spec [cz-imaps imaps] [cz-imap imap] wake-imap))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pop3<> "Create a POP3 Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (pop3<> _ id POP3Spec)) ([_ id spec] (email-xxx _ id spec [cz-pop3s pop3s] [cz-pop3 pop3] wake-pop3))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
74424
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, <NAME>. All rights reserved. (ns czlab.bixby.plugs.mails "Implementation for email services." (:require [czlab.bixby.core :as b] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.twisty.codec :as co] [czlab.bixby.plugs.loops :as l]) (:import [javax.mail.internet MimeMessage] [clojure.lang APersistentMap] [javax.mail Flags$Flag Flags Store Folder Session Provider Provider$Type] [java.util Properties] [java.io IOException])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:dynamic *mock-mail-provider* {:pop3s "czlab.bixby.mock.mail.MockPop3SSLStore" :imaps "czlab.bixby.mock.mail.MockIMapSSLStore" :pop3 "czlab.bixby.mock.mail.MockPop3Store" :imap "czlab.bixby.mock.mail.MockIMapStore"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POP3 (c/def- cz-pop3s "com.sun.mail.pop3.POP3SSLStore") (c/def- cz-pop3 "com.sun.mail.pop3.POP3Store") (c/def- pop3s "pop3s") (c/def- pop3 "pop3") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IMAP (c/def- cz-imaps "com.sun.mail.imap.IMAPSSLStore") (c/def- cz-imap "com.sun.mail.imap.IMAPStore") (c/def- imaps "imaps") (c/def- imap "imap") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-folder [^Folder fd] (and fd (c/try! (if (.isOpen fd) (.close fd true))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-store [^Store store] (c/try! (some-> store .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailMsg [] c/Idable (id [_] (:id _)) c/Hierarchical (parent [me] (:source me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- evt<> [co msg] (c/object<> MailMsg :source co :message msg :id (str "MailMsg#" (u/seqint2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sanitize [pkey {:keys [port delete-msg? host user ssl? passwd] :as cfg0}] (-> cfg0 (assoc :ssl? (c/!false? ssl?)) (assoc :delete-msg? (true? delete-msg?)) (assoc :host (str host)) (assoc :port (if (c/spos? port) port 995)) (assoc :user (str user)) (assoc :passwd (co/pw-text (co/pwd<> passwd pkey))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- init2 [plug [cz proto :as arg]] (let [mockp (u/get-sys-prop "bixby.mock.mail.proto") demo? (c/hgl? mockp) cz (name cz) proto (name (if demo? mockp proto)) demop ((keyword proto) *mock-mail-provider*) ss (Session/getInstance (doto (Properties.) (.put "mail.store.protocol" proto)) nil) [^Provider sun ^String pz] (if demo? [(Provider. Provider$Type/STORE proto demop "czlab" "1.1.7") demop] [(some #(if (c/eq? cz (.getClassName ^Provider %)) %) (.getProviders ss)) cz])] (u/assert-IOE (some? sun) "Failed to find store: %s" pz) (c/info "mail store impl = %s" sun) (.setProvider ss sun) (assoc plug :proto proto :pz pz :session ss))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailPlugin [server _id info conf wakerFunc] c/Connectable (disconnect [_] _) (connect [_] (c/connect _ nil)) (connect [me _] (let [{:keys [proto session]} me {:keys [host user port passwd]} conf s (.getStore ^Session session ^String proto)] (if (nil? s) (c/do->nil (c/warn "failed to get session store [%s]." proto)) (let [_ (c/debug "connecting to session store [%s]..." proto) _ (.connect s ^String host ^long port ^String user (c/stror (i/x->str passwd) nil)) fd (some-> (.getDefaultFolder s) (.getFolder "INBOX"))] (when (or (nil? fd) (not (.exists fd))) (c/warn "bad mail store folder#%s." proto) (c/try! (.close s)) (u/throw-IOE "Cannot find inbox!")) [s fd])))) c/Hierarchical (parent [_] server) c/Idable (id [_] _id) c/Initable (init [me arg] (let [{:keys [sslvars vars]} me pk (i/x->chars (-> me c/parent b/pkey))] (-> (update-in me [:conf] #(sanitize pk (-> (c/merge+ % arg) b/expand-vars* b/prevar-cfg))) (init2 (if (:ssl? conf) sslvars vars))))) c/Finzable (finz [_] (c/stop _)) c/Startable (stop [me] (l/stop-threaded-loop! (:loopy me)) me) (start [_] (c/start _ nil)) (start [me _] (assoc me :loopy (l/schedule-threaded-loop me wakerFunc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- email-xxx [server id {:keys [info conf]} sslvars vars wakerFunc] (-> (MailPlugin. server id info conf wakerFunc) (assoc :sslvars sslvars :vars vars))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} POP3Spec {:info {:name "POP3 Client" :version "1.0.0"} :conf {:$pluggable ::pop3<> :host "pop.gmail.com" :port 995 :delete-msg? false :username "joe" :passwd "<PASSWORD>" :interval-secs 300 :delay-secs 0 :ssl? true :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan* [plug ^Store store ^Folder folder] (letfn [(read* [msgs] (let [d? (get-in plug [:conf :delete-msg?])] (doseq [^MimeMessage mm msgs] (doto mm .getAllHeaders .getContent) (when d? (.setFlag mm Flags$Flag/DELETED true)) (b/dispatch (evt<> plug mm)))))] (when folder (if-not (.isOpen folder) (.open folder Folder/READ_WRITE))) (when (.isOpen folder) (try (let [cnt (.getMessageCount folder)] (c/debug "count of new mail-messages: %d." cnt) (if (c/spos? cnt) (read* (.getMessages folder)))) (finally (c/try! (.close folder true))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-pop3 [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-imap [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} IMAPSpec {:info {:name "IMAP Client" :version "1.0.0"} :conf {:$pluggable ::imap<> :host "imap.gmail.com" :port 993 :delete-msg? false :ssl? true :username "joe" :passwd "<PASSWORD>" :interval-secs 300 :delay-secs 0 :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn imap<> "Create a IMAP Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (imap _ id IMAPSpec)) ([_ id spec] (email-xxx _ id spec [cz-imaps imaps] [cz-imap imap] wake-imap))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pop3<> "Create a POP3 Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (pop3<> _ id POP3Spec)) ([_ id spec] (email-xxx _ id spec [cz-pop3s pop3s] [cz-pop3 pop3] wake-pop3))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
true
;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved. (ns czlab.bixby.plugs.mails "Implementation for email services." (:require [czlab.bixby.core :as b] [czlab.basal.io :as i] [czlab.basal.core :as c] [czlab.basal.util :as u] [czlab.twisty.codec :as co] [czlab.bixby.plugs.loops :as l]) (:import [javax.mail.internet MimeMessage] [clojure.lang APersistentMap] [javax.mail Flags$Flag Flags Store Folder Session Provider Provider$Type] [java.util Properties] [java.io IOException])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^:dynamic *mock-mail-provider* {:pop3s "czlab.bixby.mock.mail.MockPop3SSLStore" :imaps "czlab.bixby.mock.mail.MockIMapSSLStore" :pop3 "czlab.bixby.mock.mail.MockPop3Store" :imap "czlab.bixby.mock.mail.MockIMapStore"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; POP3 (c/def- cz-pop3s "com.sun.mail.pop3.POP3SSLStore") (c/def- cz-pop3 "com.sun.mail.pop3.POP3Store") (c/def- pop3s "pop3s") (c/def- pop3 "pop3") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; IMAP (c/def- cz-imaps "com.sun.mail.imap.IMAPSSLStore") (c/def- cz-imap "com.sun.mail.imap.IMAPStore") (c/def- imaps "imaps") (c/def- imap "imap") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-folder [^Folder fd] (and fd (c/try! (if (.isOpen fd) (.close fd true))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- close-store [^Store store] (c/try! (some-> store .close))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailMsg [] c/Idable (id [_] (:id _)) c/Hierarchical (parent [me] (:source me))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- evt<> [co msg] (c/object<> MailMsg :source co :message msg :id (str "MailMsg#" (u/seqint2)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- sanitize [pkey {:keys [port delete-msg? host user ssl? passwd] :as cfg0}] (-> cfg0 (assoc :ssl? (c/!false? ssl?)) (assoc :delete-msg? (true? delete-msg?)) (assoc :host (str host)) (assoc :port (if (c/spos? port) port 995)) (assoc :user (str user)) (assoc :passwd (co/pw-text (co/pwd<> passwd pkey))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- init2 [plug [cz proto :as arg]] (let [mockp (u/get-sys-prop "bixby.mock.mail.proto") demo? (c/hgl? mockp) cz (name cz) proto (name (if demo? mockp proto)) demop ((keyword proto) *mock-mail-provider*) ss (Session/getInstance (doto (Properties.) (.put "mail.store.protocol" proto)) nil) [^Provider sun ^String pz] (if demo? [(Provider. Provider$Type/STORE proto demop "czlab" "1.1.7") demop] [(some #(if (c/eq? cz (.getClassName ^Provider %)) %) (.getProviders ss)) cz])] (u/assert-IOE (some? sun) "Failed to find store: %s" pz) (c/info "mail store impl = %s" sun) (.setProvider ss sun) (assoc plug :proto proto :pz pz :session ss))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defrecord MailPlugin [server _id info conf wakerFunc] c/Connectable (disconnect [_] _) (connect [_] (c/connect _ nil)) (connect [me _] (let [{:keys [proto session]} me {:keys [host user port passwd]} conf s (.getStore ^Session session ^String proto)] (if (nil? s) (c/do->nil (c/warn "failed to get session store [%s]." proto)) (let [_ (c/debug "connecting to session store [%s]..." proto) _ (.connect s ^String host ^long port ^String user (c/stror (i/x->str passwd) nil)) fd (some-> (.getDefaultFolder s) (.getFolder "INBOX"))] (when (or (nil? fd) (not (.exists fd))) (c/warn "bad mail store folder#%s." proto) (c/try! (.close s)) (u/throw-IOE "Cannot find inbox!")) [s fd])))) c/Hierarchical (parent [_] server) c/Idable (id [_] _id) c/Initable (init [me arg] (let [{:keys [sslvars vars]} me pk (i/x->chars (-> me c/parent b/pkey))] (-> (update-in me [:conf] #(sanitize pk (-> (c/merge+ % arg) b/expand-vars* b/prevar-cfg))) (init2 (if (:ssl? conf) sslvars vars))))) c/Finzable (finz [_] (c/stop _)) c/Startable (stop [me] (l/stop-threaded-loop! (:loopy me)) me) (start [_] (c/start _ nil)) (start [me _] (assoc me :loopy (l/schedule-threaded-loop me wakerFunc)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- email-xxx [server id {:keys [info conf]} sslvars vars wakerFunc] (-> (MailPlugin. server id info conf wakerFunc) (assoc :sslvars sslvars :vars vars))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} POP3Spec {:info {:name "POP3 Client" :version "1.0.0"} :conf {:$pluggable ::pop3<> :host "pop.gmail.com" :port 995 :delete-msg? false :username "joe" :passwd "PI:PASSWORD:<PASSWORD>END_PI" :interval-secs 300 :delay-secs 0 :ssl? true :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- scan* [plug ^Store store ^Folder folder] (letfn [(read* [msgs] (let [d? (get-in plug [:conf :delete-msg?])] (doseq [^MimeMessage mm msgs] (doto mm .getAllHeaders .getContent) (when d? (.setFlag mm Flags$Flag/DELETED true)) (b/dispatch (evt<> plug mm)))))] (when folder (if-not (.isOpen folder) (.open folder Folder/READ_WRITE))) (when (.isOpen folder) (try (let [cnt (.getMessageCount folder)] (c/debug "count of new mail-messages: %d." cnt) (if (c/spos? cnt) (read* (.getMessages folder)))) (finally (c/try! (.close folder true))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-pop3 [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- wake-imap [co] (let [[store folder] (c/connect co)] (try (scan* co store folder) (catch Throwable _ (c/exception _)) (finally (close-folder folder) (close-store store))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def ^{:doc ""} IMAPSpec {:info {:name "IMAP Client" :version "1.0.0"} :conf {:$pluggable ::imap<> :host "imap.gmail.com" :port 993 :delete-msg? false :ssl? true :username "joe" :passwd "PI:PASSWORD:<PASSWORD>END_PI" :interval-secs 300 :delay-secs 0 :$error nil :$action nil}}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn imap<> "Create a IMAP Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (imap _ id IMAPSpec)) ([_ id spec] (email-xxx _ id spec [cz-imaps imaps] [cz-imap imap] wake-imap))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn pop3<> "Create a POP3 Mail Plugin." {:arglists '([server id] [server id spec])} ([_ id] (pop3<> _ id POP3Spec)) ([_ id spec] (email-xxx _ id spec [cz-pop3s pop3s] [cz-pop3 pop3] wake-pop3))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";; Copyright © 2017 Douglas P. Fields, Jr. All Rights Reserved.\n;; Web: https://symboli", "end": 37, "score": 0.999855101108551, "start": 20, "tag": "NAME", "value": "Douglas P. Fields" }, { "context": "; Web: https://symbolics.lisp.engineer/\n;; E-mail: symbolics@lisp.engineer\n;; Twitter: @LispEngineer\n\n;; Sorry that this is ", "end": 139, "score": 0.9999138116836548, "start": 116, "tag": "EMAIL", "value": "symbolics@lisp.engineer" }, { "context": "er/\n;; E-mail: symbolics@lisp.engineer\n;; Twitter: @LispEngineer\n\n;; Sorry that this is really ugly. I was iterati", "end": 165, "score": 0.9991687536239624, "start": 152, "tag": "USERNAME", "value": "@LispEngineer" } ]
test/engineer/lisp/fast_atom/core_test.clj
LispEngineer/fast-atom
0
;; Copyright © 2017 Douglas P. Fields, Jr. All Rights Reserved. ;; Web: https://symbolics.lisp.engineer/ ;; E-mail: symbolics@lisp.engineer ;; Twitter: @LispEngineer ;; Sorry that this is really ugly. I was iterating super fast and wanted ;; to get some efficient performance test functions without too much ;; overhead, so lots of macros. (ns engineer.lisp.fast-atom.core-test (:import (engineer.lisp.fastatom UnsynchronizedAtom FastAtom)) (:require [clojure.test :refer :all] [engineer.lisp.fast-atom.core :refer :all])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn perf-test-1 [] (let [trials 100000000] (println "Standard atom swap!") (time (let [a (atom {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Unsynchronized atom swap!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Standard atom reset!") (time (let [a (atom {})] (dorun (for [x (range trials)] (reset! a {:x x}))))) (println "Unsynchronized atom reset!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (reset! a {:x x})))))) ;; Return test value true) (defmacro trial-body "Makes the body of a performance trial function, looping it trials times." [trials trial-num v init & body] `(let [trials# (long ~trials)] ; long: forces not using boxed math (when (pos? trials#) (let [~v ~init] (loop [~trial-num (long 1)] ; long: forces not using boxed math ~@body (when (< ~trial-num trials#) (recur (inc ~trial-num)))))))) (defmacro repeat-body "Repeats the form num times assigning the repeat to specified sym each time. Basically, unrolls something. num must be an actual number (for now)" [sym num form] (letfn [(makeform [n] ;; This isn't recursive and only handles top-level replacements (map #(if (= % sym) n %) form))] (cons 'do (map makeform (range 1 (inc num)))))) (defmacro reset!m "Since repeat-body doesn't handle nested forms, this just wraps reset! with a flattened body after the atom." [atom & body] `(reset! ~atom ~body)) (defmacro make-perf-func "Creates a performance function with a given atom creator and atom contents updator." [name desc create body a n num] ; These are necessary symbols `(defn ~name [trials#] (println ~desc " x" 10 ", trials: " trials#) (time (trial-body trials# ~num ~a ~create (repeat-body ~n 10 ~body))))) (make-perf-func std-map-swap "Std atom/map swap" (atom {}) (swap! a assoc,,, n num) a n num) (make-perf-func std-trans-swap "Std atom/transient swap" (atom (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func unsync-map-swap "Unsync atom/map swap" (UnsynchronizedAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func unsync-trans-swap "Unsync atom/transient swap" (UnsynchronizedAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func fast-map-swap "Fast atom/map swap" (FastAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func fast-trans-swap "Fast atom/transient swap" (FastAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func std-map-reset "Std atom/map reset" (atom {}) (reset!m a assoc @a n num) a n num) (make-perf-func std-trans-reset "Std atom/transient reset" (atom (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func unsync-map-reset "Unsync atom/map reset" (UnsynchronizedAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func unsync-trans-reset "Unsync atom/transient reset" (UnsynchronizedAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func fast-map-reset "Fast atom/map reset" (FastAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func fast-trans-reset "Fast atom/transient reset" (FastAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (defn blank-line [& body] (println)) (defn perf-test-2 "Run all the individual performance test functions." [] (let [trials 10000000 funcs [#'std-map-swap #'std-trans-swap #'unsync-map-swap #'unsync-trans-swap #'fast-map-swap #'fast-trans-swap #'blank-line #'std-map-reset #'std-trans-reset #'unsync-map-reset #'unsync-trans-reset #'fast-map-reset #'fast-trans-reset]] ;; Warm up the first one once (std-map-swap (long (/ trials 4))) (println "\nReal trials starting...\n") (doseq [f funcs] (System/gc) (f trials))) true) (deftest test-perf-1 (testing "Performance" (println "\n\nTest 1 (Warm up the JVM)\n\n") (is (perf-test-2)) (println "\n\nTest 2 (JVM warmed up)\n\n") (is (perf-test-2))))
92689
;; Copyright © 2017 <NAME>, Jr. All Rights Reserved. ;; Web: https://symbolics.lisp.engineer/ ;; E-mail: <EMAIL> ;; Twitter: @LispEngineer ;; Sorry that this is really ugly. I was iterating super fast and wanted ;; to get some efficient performance test functions without too much ;; overhead, so lots of macros. (ns engineer.lisp.fast-atom.core-test (:import (engineer.lisp.fastatom UnsynchronizedAtom FastAtom)) (:require [clojure.test :refer :all] [engineer.lisp.fast-atom.core :refer :all])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn perf-test-1 [] (let [trials 100000000] (println "Standard atom swap!") (time (let [a (atom {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Unsynchronized atom swap!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Standard atom reset!") (time (let [a (atom {})] (dorun (for [x (range trials)] (reset! a {:x x}))))) (println "Unsynchronized atom reset!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (reset! a {:x x})))))) ;; Return test value true) (defmacro trial-body "Makes the body of a performance trial function, looping it trials times." [trials trial-num v init & body] `(let [trials# (long ~trials)] ; long: forces not using boxed math (when (pos? trials#) (let [~v ~init] (loop [~trial-num (long 1)] ; long: forces not using boxed math ~@body (when (< ~trial-num trials#) (recur (inc ~trial-num)))))))) (defmacro repeat-body "Repeats the form num times assigning the repeat to specified sym each time. Basically, unrolls something. num must be an actual number (for now)" [sym num form] (letfn [(makeform [n] ;; This isn't recursive and only handles top-level replacements (map #(if (= % sym) n %) form))] (cons 'do (map makeform (range 1 (inc num)))))) (defmacro reset!m "Since repeat-body doesn't handle nested forms, this just wraps reset! with a flattened body after the atom." [atom & body] `(reset! ~atom ~body)) (defmacro make-perf-func "Creates a performance function with a given atom creator and atom contents updator." [name desc create body a n num] ; These are necessary symbols `(defn ~name [trials#] (println ~desc " x" 10 ", trials: " trials#) (time (trial-body trials# ~num ~a ~create (repeat-body ~n 10 ~body))))) (make-perf-func std-map-swap "Std atom/map swap" (atom {}) (swap! a assoc,,, n num) a n num) (make-perf-func std-trans-swap "Std atom/transient swap" (atom (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func unsync-map-swap "Unsync atom/map swap" (UnsynchronizedAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func unsync-trans-swap "Unsync atom/transient swap" (UnsynchronizedAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func fast-map-swap "Fast atom/map swap" (FastAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func fast-trans-swap "Fast atom/transient swap" (FastAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func std-map-reset "Std atom/map reset" (atom {}) (reset!m a assoc @a n num) a n num) (make-perf-func std-trans-reset "Std atom/transient reset" (atom (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func unsync-map-reset "Unsync atom/map reset" (UnsynchronizedAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func unsync-trans-reset "Unsync atom/transient reset" (UnsynchronizedAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func fast-map-reset "Fast atom/map reset" (FastAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func fast-trans-reset "Fast atom/transient reset" (FastAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (defn blank-line [& body] (println)) (defn perf-test-2 "Run all the individual performance test functions." [] (let [trials 10000000 funcs [#'std-map-swap #'std-trans-swap #'unsync-map-swap #'unsync-trans-swap #'fast-map-swap #'fast-trans-swap #'blank-line #'std-map-reset #'std-trans-reset #'unsync-map-reset #'unsync-trans-reset #'fast-map-reset #'fast-trans-reset]] ;; Warm up the first one once (std-map-swap (long (/ trials 4))) (println "\nReal trials starting...\n") (doseq [f funcs] (System/gc) (f trials))) true) (deftest test-perf-1 (testing "Performance" (println "\n\nTest 1 (Warm up the JVM)\n\n") (is (perf-test-2)) (println "\n\nTest 2 (JVM warmed up)\n\n") (is (perf-test-2))))
true
;; Copyright © 2017 PI:NAME:<NAME>END_PI, Jr. All Rights Reserved. ;; Web: https://symbolics.lisp.engineer/ ;; E-mail: PI:EMAIL:<EMAIL>END_PI ;; Twitter: @LispEngineer ;; Sorry that this is really ugly. I was iterating super fast and wanted ;; to get some efficient performance test functions without too much ;; overhead, so lots of macros. (ns engineer.lisp.fast-atom.core-test (:import (engineer.lisp.fastatom UnsynchronizedAtom FastAtom)) (:require [clojure.test :refer :all] [engineer.lisp.fast-atom.core :refer :all])) (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (defn perf-test-1 [] (let [trials 100000000] (println "Standard atom swap!") (time (let [a (atom {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Unsynchronized atom swap!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (swap! a assoc ,,, :x x))))) (println "Standard atom reset!") (time (let [a (atom {})] (dorun (for [x (range trials)] (reset! a {:x x}))))) (println "Unsynchronized atom reset!") (time (let [a (UnsynchronizedAtom. {})] (dorun (for [x (range trials)] (reset! a {:x x})))))) ;; Return test value true) (defmacro trial-body "Makes the body of a performance trial function, looping it trials times." [trials trial-num v init & body] `(let [trials# (long ~trials)] ; long: forces not using boxed math (when (pos? trials#) (let [~v ~init] (loop [~trial-num (long 1)] ; long: forces not using boxed math ~@body (when (< ~trial-num trials#) (recur (inc ~trial-num)))))))) (defmacro repeat-body "Repeats the form num times assigning the repeat to specified sym each time. Basically, unrolls something. num must be an actual number (for now)" [sym num form] (letfn [(makeform [n] ;; This isn't recursive and only handles top-level replacements (map #(if (= % sym) n %) form))] (cons 'do (map makeform (range 1 (inc num)))))) (defmacro reset!m "Since repeat-body doesn't handle nested forms, this just wraps reset! with a flattened body after the atom." [atom & body] `(reset! ~atom ~body)) (defmacro make-perf-func "Creates a performance function with a given atom creator and atom contents updator." [name desc create body a n num] ; These are necessary symbols `(defn ~name [trials#] (println ~desc " x" 10 ", trials: " trials#) (time (trial-body trials# ~num ~a ~create (repeat-body ~n 10 ~body))))) (make-perf-func std-map-swap "Std atom/map swap" (atom {}) (swap! a assoc,,, n num) a n num) (make-perf-func std-trans-swap "Std atom/transient swap" (atom (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func unsync-map-swap "Unsync atom/map swap" (UnsynchronizedAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func unsync-trans-swap "Unsync atom/transient swap" (UnsynchronizedAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func fast-map-swap "Fast atom/map swap" (FastAtom. {}) (swap! a assoc,,, n num) a n num) (make-perf-func fast-trans-swap "Fast atom/transient swap" (FastAtom. (transient {})) (swap! a assoc!,,, n num) a n num) (make-perf-func std-map-reset "Std atom/map reset" (atom {}) (reset!m a assoc @a n num) a n num) (make-perf-func std-trans-reset "Std atom/transient reset" (atom (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func unsync-map-reset "Unsync atom/map reset" (UnsynchronizedAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func unsync-trans-reset "Unsync atom/transient reset" (UnsynchronizedAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (make-perf-func fast-map-reset "Fast atom/map reset" (FastAtom. {}) (reset!m a assoc @a n num) a n num) (make-perf-func fast-trans-reset "Fast atom/transient reset" (FastAtom. (transient {})) (reset!m a assoc! @a n num) a n num) (defn blank-line [& body] (println)) (defn perf-test-2 "Run all the individual performance test functions." [] (let [trials 10000000 funcs [#'std-map-swap #'std-trans-swap #'unsync-map-swap #'unsync-trans-swap #'fast-map-swap #'fast-trans-swap #'blank-line #'std-map-reset #'std-trans-reset #'unsync-map-reset #'unsync-trans-reset #'fast-map-reset #'fast-trans-reset]] ;; Warm up the first one once (std-map-swap (long (/ trials 4))) (println "\nReal trials starting...\n") (doseq [f funcs] (System/gc) (f trials))) true) (deftest test-perf-1 (testing "Performance" (println "\n\nTest 1 (Warm up the JVM)\n\n") (is (perf-test-2)) (println "\n\nTest 2 (JVM warmed up)\n\n") (is (perf-test-2))))
[ { "context": "y :corp eid 1))})\n\n;; Card definitions\n\n(defcard \"Afshar\"\n (let [breakable-fn (req (if (= :hq (second (ge", "end": 14701, "score": 0.8881694078445435, "start": 14695, "tag": "NAME", "value": "Afshar" }, { "context": "d-the-run :breakable breakable-fn)]}))\n\n(defcard \"Aiki\"\n {:subroutines [(do-psi {:label \"Runner draw", "end": 15191, "score": 0.6980100274085999, "start": 15190, "tag": "NAME", "value": "A" }, { "context": "e eid card {:cause :subroutine})))}]})\n\n(defcard \"Akhet\"\n (let [breakable-fn (req (if (<= 3 (get-counter", "end": 16195, "score": 0.8635827898979187, "start": 16190, "tag": "NAME", "value": "Akhet" }, { "context": "-counters card :advancement)) 3 0))}))\n\n(defcard \"Anansi\"\n (let [corp-draw {:optional\n ", "end": 17101, "score": 0.9900654554367065, "start": 17095, "tag": "NAME", "value": "Anansi" }, { "context": "-ability 6 add-runner-card-to-grip)]})\n\n(defcard \"Archer\"\n {:additional-cost [:forfeit]\n :subroutines", "end": 20437, "score": 0.7915931344032288, "start": 20433, "tag": "NAME", "value": "Arch" }, { "context": "am-sub\n end-the-run]})\n\n(defcard \"Architect\"\n {:flags {:untrashable-while-rezzed true}\n", "end": 20627, "score": 0.7966229319572449, "start": 20623, "tag": "NAME", "value": "Arch" }, { "context": "rd))}]\n :subroutines [end-the-run]})\n\n(defcard \"Chiyashi\"\n {:implementation \"Trash effect when using an A", "end": 34690, "score": 0.8954073786735535, "start": 34682, "tag": "NAME", "value": "Chiyashi" }, { "context": "age 2)\n end-the-run]})\n\n(defcard \"Chrysalis\"\n {:flags {:rd-reveal (req true)}\n :subroutine", "end": 35274, "score": 0.9012333154678345, "start": 35265, "tag": "NAME", "value": "Chrysalis" }, { "context": "outine\"\n :prompt \"You are encountering Chrysalis. Allow its subroutine to fire?\"\n :yes", "end": 35576, "score": 0.748431921005249, "start": 35567, "tag": "NAME", "value": "Chrysalis" }, { "context": "e-unbroken-subs! :corp eid card))}}}})\n\n(defcard \"Chum\"\n {:subroutines\n [{:label \"Give +2 strength to", "end": 35752, "score": 0.8358566761016846, "start": 35748, "tag": "NAME", "value": "Chum" }, { "context": "ner-abilities [(bioroid-break 3 3)]}))\n\n(defcard \"Fenris\"\n {:on-rez take-bad-pub\n :subroutines [(do-bra", "end": 59445, "score": 0.9989138245582581, "start": 59439, "tag": "NAME", "value": "Fenris" }, { "context": "eractive (req true)\n :optional\n {:prompt \"Rez Formicary?\"\n :yes-ability\n {:msg \"rez a", "end": 61848, "score": 0.928398847579956, "start": 61845, "tag": "NAME", "value": "Rez" }, { "context": "ctive (req true)\n :optional\n {:prompt \"Rez Formicary?\"\n :yes-ability\n {:msg \"rez and move Fo", "end": 61858, "score": 0.9202103614807129, "start": 61849, "tag": "NAME", "value": "Formicary" }, { "context": " add-power-counter]})\n\n(defcard \"Galahad\"\n (grail-ice end-the-run))\n\n(defcard \"Gatekeeper", "end": 63607, "score": 0.7873269319534302, "start": 63601, "tag": "NAME", "value": "alahad" }, { "context": "(constellation-ice (do-net-damage 1)))\n\n(defcard \"Gold Farmer\"\n (letfn [(gf-lose-credits [state side eid n]\n ", "end": 65729, "score": 0.9988055229187012, "start": 65718, "tag": "NAME", "value": "Gold Farmer" }, { "context": "(end-the-run-unless-runner-pays 3)]}))\n\n(defcard \"Grim\"\n {:on-rez take-bad-pub\n :subroutines [trash-p", "end": 66656, "score": 0.971878170967102, "start": 66652, "tag": "NAME", "value": "Grim" }, { "context": "alse}]\n :subroutines [end-the-run]})\n\n(defcard \"Gutenberg\"\n {:subroutines [(tag-trace 7)]\n :strength-bon", "end": 66928, "score": 0.9719066023826599, "start": 66919, "tag": "NAME", "value": "Gutenberg" }, { "context": " (second (get-zone card)) :rd) 3 0))})\n\n(defcard \"Gyri Labyrinth\"\n {:subroutines [{:req (req run)\n ", "end": 67056, "score": 0.9997403025627136, "start": 67042, "tag": "NAME", "value": "Gyri Labyrinth" }, { "context": " :value -2}))}]})\n\n(defcard \"Hadrian's Wall\"\n (wall-ice [end-the-run end-the-run]))\n\n(defcar", "end": 67625, "score": 0.9726060032844543, "start": 67611, "tag": "NAME", "value": "Hadrian's Wall" }, { "context": " (wall-ice [end-the-run end-the-run]))\n\n(defcard \"Hagen\"\n {:subroutines [{:label \"Trash 1 program\"\n ", "end": 67683, "score": 0.9685475826263428, "start": 67678, "tag": "NAME", "value": "Hagen" }, { "context": "e-unbroken-subs! :corp eid card))}}}})\n\n(defcard \"Himitsu-Bako\"\n {:abilities [{:msg \"add it to HQ\"\n ", "end": 73336, "score": 0.9990754723548889, "start": 73324, "tag": "NAME", "value": "Himitsu-Bako" }, { "context": "nd))}]\n :subroutines [end-the-run]})\n\n(defcard \"Hive\"\n (let [corp-points (fn [corp] (min 5 (max 0 (- ", "end": 73508, "score": 0.9202280044555664, "start": 73504, "tag": "NAME", "value": "Hive" }, { "context": "run\n end-the-run]}))\n\n(defcard \"Holmegaard\"\n {:subroutines [(trace-ability 4 {:label \"Runne", "end": 74430, "score": 0.9971862435340881, "start": 74420, "tag": "NAME", "value": "Holmegaard" }, { "context": " eid target {:cause :subroutine}))}]})\n\n(defcard \"Hortum\"\n (letfn [(hort [n] {:prompt \"Choose a card to a", "end": 75153, "score": 0.9817567467689514, "start": 75147, "tag": "NAME", "value": "Hortum" }, { "context": " runner-loses-click]})\n\n(defcard \"Howler\"\n {:subroutines\n [{:label \"Install a piece of ", "end": 77661, "score": 0.6615421772003174, "start": 77655, "tag": "NAME", "value": "Howler" }, { "context": " card {:cause :subroutine}))}]))))}]})\n\n(defcard \"Hudson 1.0\"\n (let [sub {:msg \"prevent the Runner f", "end": 79041, "score": 0.5225192904472351, "start": 79040, "tag": "NAME", "value": "H" }, { "context": "ner-abilities [(bioroid-break 1 1)]}))\n\n(defcard \"Hunter\"\n {:subroutines [(tag-trace 3)]})\n\n(defcard", "end": 79293, "score": 0.7236186265945435, "start": 79292, "tag": "NAME", "value": "H" }, { "context": "e eid card {:cause :subroutine}))))]})\n\n(defcard \"Janus 1.0\"\n {:subroutines [(do-brain-damage 1)\n ", "end": 85722, "score": 0.7815217971801758, "start": 85719, "tag": "NAME", "value": "Jan" }, { "context": "nner-abilities [(bioroid-break 1 1)]})\n\n(defcard \"Jua\"\n {:on-encounter {:msg \"prevent the Runner from ", "end": 85938, "score": 0.9901267290115356, "start": 85935, "tag": "NAME", "value": "Jua" }, { "context": "eid card {:cause :subroutine})))}}}]})\n\n(defcard \"Komainu\"\n {:on-encounter {:effect (effect (gain-variable", "end": 91280, "score": 0.9971766471862793, "start": 91273, "tag": "NAME", "value": "Komainu" }, { "context": " (reset-variable-subs card 0 nil))}]})\n\n(defcard \"Konjin\"\n {:implementation \"Encounter effect is manual\"\n", "end": 91499, "score": 0.990867018699646, "start": 91493, "tag": "NAME", "value": "Konjin" }, { "context": "(effect-completed state side eid))})})\n\n(defcard \"Lab Dog\"\n {:subroutines [{:label \"Force the Runner to tr", "end": 91973, "score": 0.6759930849075317, "start": 91966, "tag": "NAME", "value": "Lab Dog" }, { "context": "e eid card {:cause :subroutine})))}]})\n\n(defcard \"Lancelot\"\n (grail-ice trash-program-sub))\n\n(defcard \"Litt", "end": 92777, "score": 0.9204235076904297, "start": 92769, "tag": "NAME", "value": "Lancelot" }, { "context": "= (:cid card) (:from-cid %))))}]))}]})\n\n(defcard \"Markus 1.0\"\n {:subroutines [runner-trash-installed-su", "end": 103738, "score": 0.5302310585975647, "start": 103734, "tag": "NAME", "value": "Mark" }, { "context": "nner-abilities [(bioroid-break 1 1)]})\n\n(defcard \"Masvingo\"\n (let [ability {:req (req (same-card? card targ", "end": 103884, "score": 0.9765117168426514, "start": 103876, "tag": "NAME", "value": "Masvingo" }, { "context": " card :advancement) end-the-run))}]}))\n\n(defcard \"Matrix Analyzer\"\n {:on-encounter {:cost [:credit 1]\n ", "end": 104465, "score": 0.8010784983634949, "start": 104450, "tag": "NAME", "value": "Matrix Analyzer" }, { "context": "1))}\n :subroutines [(tag-trace 2)]})\n\n(defcard \"Mausolus\"\n {:advanceable :always\n :subroutines [{:label", "end": 104766, "score": 0.9520705938339233, "start": 104758, "tag": "NAME", "value": "Mausolus" }, { "context": "effect-completed state side eid)))}]})\n\n(defcard \"Meridian\"\n {:subroutines [{:label \"Gain 4 [Credits] and e", "end": 105837, "score": 0.9989190101623535, "start": 105829, "tag": "NAME", "value": "Meridian" }, { "context": " :waiting-prompt \"Runner to choose an option for Meridian\"\n :prompt \"Choose one\"\n ", "end": 105970, "score": 0.7107640504837036, "start": 105965, "tag": "NAME", "value": "Merid" }, { "context": "ne\"\n :choices [\"End the run\" \"Add Meridian to score area\"]\n :player :r", "end": 106064, "score": 0.7413284778594971, "start": 106061, "tag": "NAME", "value": "Mer" }, { "context": " (do (system-msg state :corp \"uses Meridian to gain 4 [Credits] and end the run\")\n ", "end": 106280, "score": 0.6061012148857117, "start": 106277, "tag": "NAME", "value": "Mer" }, { "context": " (do (system-msg state :runner \"adds Meridian to their score area as an agenda worth -1 agen", "end": 106556, "score": 0.7529301047325134, "start": 106551, "tag": "NAME", "value": "Merid" }, { "context": "fect-completed state side eid)))))}]})\n\n(defcard \"Merlin\"\n (grail-ice (do-net-damage 2)))\n\n(defcard \"Meru", "end": 107025, "score": 0.9990813732147217, "start": 107019, "tag": "NAME", "value": "Merlin" }, { "context": "rlin\"\n (grail-ice (do-net-damage 2)))\n\n(defcard \"Meru Mati\"\n {:subroutines [end-the-run]\n :strength-bonus", "end": 107080, "score": 0.9990671873092651, "start": 107071, "tag": "NAME", "value": "Meru Mati" }, { "context": " (second (get-zone card)) :hq) 3 0))})\n\n(defcard \"Metamorph\"\n {:subroutines [{:label \"Swap two ICE or ", "end": 107195, "score": 0.5071153044700623, "start": 107192, "tag": "NAME", "value": "Met" }, { "context": "er run)) {:ignore-all-cost true}))}]})\n\n(defcard \"Mirāju\"\n {:events [{:event :end-of-encounter\n ", "end": 111464, "score": 0.6066391468048096, "start": 111461, "tag": "NAME", "value": "Mir" }, { "context": " card nil)))}]})\n\n(defcard \"Mlinzi\"\n (letfn [(net-or-trash [net-dmg mill-cnt]\n ", "end": 113198, "score": 0.5838139653205872, "start": 113192, "tag": "NAME", "value": "Mlinzi" }, { "context": " (net-or-trash 3 4)]}))\n\n(defcard \"Mother Goddess\"\n (let [mg {:req (req (ice? target))\n ", "end": 114616, "score": 0.9808610677719116, "start": 114602, "tag": "NAME", "value": "Mother Goddess" }, { "context": "oc mg :event :ice-subtype-changed)]}))\n\n(defcard \"Muckraker\"\n {:on-rez take-bad-pub\n :subroutines [(tag-tr", "end": 115476, "score": 0.9719427227973938, "start": 115467, "tag": "NAME", "value": "Muckraker" }, { "context": "ner-abilities [(bioroid-break 2 2)]}))\n\n(defcard \"Neural Katana\"\n {:subroutines [(do-net-damage 3)]})\n\n(defcard ", "end": 116794, "score": 0.9251387119293213, "start": 116781, "tag": "NAME", "value": "Neural Katana" }, { "context": "\n {:subroutines [(do-net-damage 3)]})\n\n(defcard \"News Hound\"\n (let [gain-sub {:req (req (and (= 1 (count (co", "end": 116855, "score": 0.6668150424957275, "start": 116845, "tag": "NAME", "value": "News Hound" }, { "context": "he-run\n end-the-run]})\n\n(defcard \"Orion\"\n (space-ice trash-program-sub\n (res", "end": 124734, "score": 0.8348346948623657, "start": 124729, "tag": "NAME", "value": "Orion" }, { "context": "subroutine)\n end-the-run))\n\n(defcard \"Otoroshi\"\n {:subroutines [{:async true\n ", "end": 124855, "score": 0.830791175365448, "start": 124847, "tag": "NAME", "value": "Otoroshi" }, { "context": " card nil)))}]})\n\n(defcard \"Owl\"\n {:subroutines [{:choices {:card #(and (install", "end": 127023, "score": 0.7706247568130493, "start": 127020, "tag": "NAME", "value": "Owl" }, { "context": "t}))}]\n :subroutines [end-the-run]})\n\n(defcard \"Peeping Tom\"\n (let [sub (end-the-run-unless-runner\n ", "end": 127941, "score": 0.7373367547988892, "start": 127930, "tag": "NAME", "value": "Peeping Tom" }, { "context": "r-abilities [(bioroid-break 2 2)]}))\n\n(defcard \"Shinobi\"\n {:on-rez take-bad-pub\n :subroutines [(trace-", "end": 140732, "score": 0.9493688344955444, "start": 140727, "tag": "NAME", "value": "inobi" }, { "context": " (end-run state side eid card)))})]})\n\n(defcard \"Shiro\"\n {:subroutines [{:label \"Rearrange the top 3 ca", "end": 141223, "score": 0.7371525168418884, "start": 141218, "tag": "NAME", "value": "Shiro" }, { "context": " :successful end-the-run}}]}))\n\n(defcard \"Susanoo-no-Mikoto\"\n {:subroutines [{:req (req (not= (:server run) ", "end": 148136, "score": 0.9658780694007874, "start": 148119, "tag": "NAME", "value": "Susanoo-no-Mikoto" }, { "context": "counters card :advancement) sub))}]}))\n\n(defcard \"Swordsman\"\n (let [breakable-fn (req (when-not (has-subtype", "end": 150430, "score": 0.8524464964866638, "start": 150421, "tag": "NAME", "value": "Swordsman" }, { "context": " (end-run state :corp eid card))))})})\n\n(defcard \"Tsurugi\"\n {:subroutines [(end-the-run-unless-corp-pays 1", "end": 161183, "score": 0.6745308041572571, "start": 161176, "tag": "NAME", "value": "Tsurugi" }, { "context": "\n (do-net-damage 1)]})\n\n(defcard \"Turing\"\n (let [breakable-fn (req (when-not (has-subtype", "end": 161360, "score": 0.6568439602851868, "start": 161354, "tag": "NAME", "value": "Turing" }, { "context": "te? (second (get-zone card))) 3 0))}))\n\n(defcard \"Turnpike\"\n {:on-encounter {:msg \"force the Runner to ", "end": 161810, "score": 0.537687361240387, "start": 161806, "tag": "NAME", "value": "Turn" }, { "context": "econd (get-zone card))) 3 0))}))\n\n(defcard \"Turnpike\"\n {:on-encounter {:msg \"force the Runner to lose", "end": 161814, "score": 0.5565661191940308, "start": 161812, "tag": "NAME", "value": "ke" }, { "context": "1))}\n :subroutines [(tag-trace 5)]})\n\n(defcard \"Tyrant\"\n (zero-to-hero end-the-run))\n\n(defcard \"Týr\"\n ", "end": 162024, "score": 0.6837430000305176, "start": 162018, "tag": "NAME", "value": "Tyrant" }, { "context": "\"Tyrant\"\n (zero-to-hero end-the-run))\n\n(defcard \"Týr\"\n {:subroutines [(do-brain-damage 2)\n ", "end": 162070, "score": 0.6692742705345154, "start": 162067, "tag": "NAME", "value": "Týr" }, { "context": " (trace-ability 3 end-the-run)]})\n\n(defcard \"Virgo\"\n (constellation-ice (give-tags 1)))\n\n(defca", "end": 165171, "score": 0.7594479322433472, "start": 165170, "tag": "NAME", "value": "V" } ]
src/clj/game/cards/ice.clj
cmsd2/netrunner
0
(ns game.cards.ice (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;;; Helper functions specific for ICE (defn reset-variable-subs ([state side card total sub] (reset-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) old-subs (remove #(and (= (:cid card) (:from-cid %)) (:variable %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines (into [])) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn gain-variable-subs ([state side card total sub] (gain-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) card) :subroutines (into [])) new-card (assoc card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn reset-printed-subs ([state side card total sub] (reset-printed-subs state side card total sub {:printed true})) ([state side card total sub args] (let [old-subs (remove #(and (= (:cid card) (:from-cid %)) (:printed %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) ;;; Runner abilites for breaking subs (defn bioroid-break ([cost qty] (bioroid-break cost qty nil)) ([cost qty args] (break-sub [:lose-click cost] qty nil args))) ;;; General subroutines (def end-the-run "Basic ETR subroutine" {:label "End the run" :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (def end-the-run-if-tagged "ETR subroutine if tagged" {:label "End the run if the Runner is tagged" :req (req tagged) :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (defn runner-pays "Ability to pay to avoid a subroutine by paying a resource" [cost] {:async true :effect (req (wait-for (pay state :runner card cost) (when-let [payment-str (:msg async-result)] (system-msg state :runner (str payment-str " due to " (:title card) " subroutine"))) (effect-completed state side eid)))}) (defn end-the-run-unless-runner-pays [amount] {:player :runner :async true :label (str "End the run unless the Runner pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side (runner-pays [:credit amount]) card nil)))}) (defn end-the-run-unless-corp-pays [amount] {:async true :label (str "End the run unless the Corp pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (end-run state :corp eid card) (wait-for (pay state :corp card [:credit amount]) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (effect-completed state side eid))))}) (defn end-the-run-unless-runner [label prompt ability] {:player :runner :async true :label (str "End the run unless the Runner " label) :prompt (str "End the run or " prompt "?") :choices ["End the run" (capitalize prompt)] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side ability card nil)))}) (defn give-tags "Basic give runner n tags subroutine." [n] {:label (str "Give the Runner " (quantify n "tag")) :msg (str "give the Runner " (quantify n "tag")) :async true :effect (effect (gain-tags :corp eid n))}) (def add-power-counter "Adds 1 power counter to the card." {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1))}) (defn trace-ability "Run a trace with specified base strength. If successful trigger specified ability" ([base {:keys [label] :as ability}] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability}}) ([base ability un-ability] (let [label (str (:label ability) " / " (:label un-ability))] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability :unsuccessful un-ability}}))) (defn tag-trace "Trace ability for giving a tag, at specified base strength" ([base] (tag-trace base 1)) ([base n] (trace-ability base (give-tags n)))) (defn gain-credits-sub "Gain specified amount of credits" [credits] {:label (str "Gain " credits " [Credits]") :msg (str "gain " credits " [Credits]") :async true :effect (effect (gain-credits eid credits))}) (defn power-counter-ability "Does specified ability using a power counter." [{:keys [label message] :as ability}] (assoc ability :label label :msg message :cost [:power 1])) (defn do-psi "Start a psi game, if not equal do ability" ([{:keys [label] :as ability}] {:label (str "Psi Game - " label) :msg (str "start a psi game (" label ")") :psi {:not-equal ability}}) ([{:keys [label-neq] :as neq-ability} {:keys [label-eq] :as eq-ability}] {:label (str "Psi Game - " label-neq " / " label-eq) :msg (str "start a psi game (" label-neq " / " label-eq ")") :psi {:not-equal neq-ability :equal eq-ability}})) (def runner-loses-click ; Runner loses a click effect {:label "Force the Runner to lose 1 [Click]" :msg "force the Runner to lose 1 [Click] if able" :effect (effect (lose :runner :click 1))}) (def add-runner-card-to-grip "Add 1 installed Runner card to the grip" {:label "Add an installed Runner card to the grip" :req (req (not-empty (all-installed state :runner))) :waiting-prompt "Corp to select a target" :prompt "Choose a card" :choices {:card #(and (installed? %) (runner? %))} :msg "add 1 installed card to the Runner's Grip" :effect (effect (move :runner target :hand true) (system-msg (str "adds " (:title target) " to the Runner's Grip")))}) (def trash-program-sub {:prompt "Select a program to trash" :label "Trash a program" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-hardware-sub {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (hardware? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-resource-sub {:prompt "Select a resource to trash" :label "Trash a resource" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-installed-sub {:async true :prompt "Select an installed card to trash" :label "Trash an installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :effect (effect (trash eid target {:cause :subroutine}))}) (def runner-trash-installed-sub (assoc trash-installed-sub :player :runner :label "Force the Runner to trash an installed card" :msg (msg "force the Runner to trash " (:title target)))) ;;; For Advanceable ICE (defn wall-ice [subroutines] {:advanceable :always :subroutines subroutines :strength-bonus (req (get-counters card :advancement))}) (defn space-ice "Creates data for Space ICE with specified abilities." [& abilities] {:advanceable :always :subroutines (vec abilities) :rez-cost-bonus (req (* -3 (get-counters card :advancement)))}) ;;; For Grail ICE (defn grail-in-hand "Req that specified card is a Grail card in the Corp's hand." [card] (and (corp? card) (in-hand? card) (has-subtype? card "Grail"))) (def reveal-grail "Ability for revealing Grail ICE from HQ." {:label "Reveal up to 2 Grail ICE from HQ" :choices {:max 2 :card grail-in-hand} :async true :effect (effect (reveal eid targets)) :msg (let [sub-label #(:label (first (:subroutines (card-def %))))] (msg "reveal " (string/join ", " (map #(str (:title %) " (" (sub-label %) ")") targets))))}) (def resolve-grail "Ability for resolving a subroutine on a Grail ICE in HQ." {:label "Resolve a Grail ICE subroutine from HQ" :choices {:card grail-in-hand} :effect (req (doseq [ice targets] (let [subroutine (first (:subroutines (card-def ice)))] (resolve-ability state side subroutine card nil))))}) (defn grail-ice "Creates data for grail ICE" [ability] {:abilities [reveal-grail] :subroutines [ability resolve-grail]}) ;;; For NEXT ICE (defn next-ice-count "Counts number of rezzed NEXT ICE - for use with NEXT Bronze and NEXT Gold" [corp] (let [servers (flatten (seq (:servers corp))) rezzed-next? #(and (rezzed? %) (has-subtype? % "NEXT"))] (reduce (fn [c server] (+ c (count (filter rezzed-next? (:ices server))))) 0 servers))) ;;; For Morph ICE (defn morph-ice "Creates the data for morph ICE with specified types and ability." [base other ability] {:advanceable :always :constant-effects [{:type :lose-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value base} {:type :gain-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value other}] :subroutines [ability]}) ;;; For Constellation ICE (defn constellation-ice "Generates map for Constellation ICE with specified effect." [ability] {:subroutines [(-> (trace-ability 2 ability) (assoc-in [:trace :kicker] ability) (assoc-in [:trace :kicker-min] 5))]}) ;; For advance-only-while-rezzed, sub-growing ICE (defn zero-to-hero "Salvage, Tyrant, Woodcutter" [sub] (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :while-rezzed :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) ;; For 7 Wonders ICE (defn wonder-sub "Checks total number of advancement counters on a piece of ice against number" [card number] (<= number (get-counters card :advancement))) (defn resolve-another-subroutine "For cards like Orion or Upayoga." ([] (resolve-another-subroutine (constantly true) "Resolve a subroutine on another ice")) ([pred] (resolve-another-subroutine pred "Resolve a subroutine on another ice")) ([pred label] (let [pred #(and (ice? %) (rezzed? %) (pred %))] {:async true :label label :effect (effect (continue-ability (when (< 1 (count (filter pred (all-active-installed state :corp)))) {:async true :prompt "Select the ice" :choices {:card pred :all true} :effect (effect (continue-ability (let [ice target] {:async true :prompt "Select the subroutine" :choices (req (unbroken-subroutines-choice ice)) :msg (msg "resolve the subroutine (\"[subroutine] " target "\") from " (:title ice)) :effect (req (let [sub (first (filter #(= target (make-label (:sub-effect %))) (:subroutines ice)))] (continue-ability state side (:sub-effect sub) ice nil)))}) card nil))}) card nil))}))) ;;; Helper function for adding implementation notes to ICE defined with functions (defn- implementation-note "Adds an implementation note to the ice-definition" [note ice-def] (assoc ice-def :implementation note)) (def take-bad-pub ; Bad pub on rez effect {:async true :effect (effect (system-msg (str "takes 1 bad publicity from " (:title card))) (gain-bad-publicity :corp eid 1))}) ;; Card definitions (defcard "Afshar" (let [breakable-fn (req (if (= :hq (second (get-zone card))) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:subroutines [{:msg "make the Runner lose 2 [Credits]" :breakable breakable-fn :async true :effect (effect (lose-credits :runner eid 2))} (assoc end-the-run :breakable breakable-fn)]})) (defcard "Aiki" {:subroutines [(do-psi {:label "Runner draws 2 cards" :msg "make the Runner draw 2 cards" :async true :effect (effect (draw :runner eid 2 nil))}) (do-net-damage 1) (do-net-damage 1)]}) (defcard "Aimor" {:subroutines [{:async true :label "Trash the top 3 cards of the Stack. Trash Aimor." :effect (req (system-msg state :corp (str "uses Aimor to trash " (string/join ", " (map :title (take 3 (:deck runner)))) " from the Runner's Stack")) (wait-for (mill state :corp :runner 3) (system-msg state side (str "trashes Aimor")) (trash state side eid card {:cause :subroutine})))}]}) (defcard "Akhet" (let [breakable-fn (req (if (<= 3 (get-counters card :advancement)) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1[Credit]. Place 1 advancement token." :breakable breakable-fn :msg (msg "gain 1 [Credit] and place 1 advancement token on " (card-str state target)) :prompt "Choose an installed card" :choices {:card installed?} :async true :effect (effect (add-prop target :advance-counter 1 {:placed true}) (gain-credits eid 1))} (assoc end-the-run :breakable breakable-fn)] :strength-bonus (req (if (<= 3 (get-counters card :advancement)) 3 0))})) (defcard "Anansi" (let [corp-draw {:optional {:waiting-prompt "Corp to draw a card" :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} runner-draw {:player :runner :optional {:waiting-prompt "Runner to decide on card draw" :prompt "Pay 2 [Credits] to draw 1 card?" :yes-ability {:async true :effect (req (wait-for (pay state :runner card [:credit 2]) (if (:cost-paid async-result) (do (system-msg state :runner "pays 2 [Credits] to draw 1 card") (draw state :runner eid 1 nil)) (do (system-msg state :runner "does not draw 1 card") (effect-completed state side eid)))))} :no-ability {:effect (effect (system-msg :runner "does not draw 1 card"))}}}] {:subroutines [{:msg "rearrange the top 5 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (req (let [from (take 5 (:deck corp))] (continue-ability state side (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from)) card nil)))} {:label "Draw 1 card, runner draws 1 card" :async true :effect (req (wait-for (resolve-ability state side corp-draw card nil) (continue-ability state :runner runner-draw card nil)))} (do-net-damage 1)] :events [(assoc (do-net-damage 3) :event :end-of-encounter :req (req (and (= (:ice context) card) (seq (remove :broken (:subroutines (:ice context)))))))]})) (defcard "Archangel" {:flags {:rd-reveal (req true)} :access {:optional {:req (req (not (in-discard? card))) :waiting-prompt "Corp to decide to trigger Archangel" :prompt "Pay 3 [Credits] to force Runner to encounter Archangel?" :player :corp :yes-ability {:cost [:credit 3] :async true :msg "force the Runner to encounter Archangel" :effect (effect (continue-ability :runner {:optional {:player :runner :prompt "You are encountering Archangel. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! eid card))}}} card nil))} :no-ability {:effect (effect (system-msg :corp "declines to force the Runner to encounter Archangel"))}}} :subroutines [(trace-ability 6 add-runner-card-to-grip)]}) (defcard "Archer" {:additional-cost [:forfeit] :subroutines [(gain-credits-sub 2) trash-program-sub trash-program-sub end-the-run]}) (defcard "Architect" {:flags {:untrashable-while-rezzed true} :subroutines [{:label "Look at the top 5 cards of R&D" :prompt "Choose a card to install" :async true :activatemsg "uses Architect to look at the top 5 cards of R&D" :req (req (and (not (string? target)) (not (operation? target)))) :not-distinct true :choices (req (conj (take 5 (:deck corp)) "No install")) :effect (effect (system-msg (str "chooses the card in position " (+ 1 (.indexOf (take 5 (:deck corp)) target)) " from R&D (top is 1)")) (corp-install eid target nil {:ignore-all-cost true}))} {:label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}]}) (defcard "Ashigaru" {:on-rez {:effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (corp? target) (or (in-hand? target) (= :hand (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))}]}) (defcard "Assassin" {:subroutines [(trace-ability 5 (do-net-damage 3)) (trace-ability 4 trash-program-sub)]}) (defcard "Asteroid Belt" (space-ice end-the-run)) (defcard "Authenticator" {:on-encounter {:optional {:req (req (not (:bypass run))) :player :runner :prompt "Take 1 tag to bypass?" :yes-ability {:async true :effect (req (system-msg state :runner "takes 1 tag on encountering Authenticator to bypass it") (bypass-ice state) (gain-tags state :runner eid 1 {:unpreventable true}))}}} :subroutines [(gain-credits-sub 2) end-the-run]}) (defcard "Bailiff" {:implementation "Gain credit is manual" :abilities [(gain-credits-sub 1)] :subroutines [end-the-run]}) (defcard "Bandwidth" {:subroutines [{:msg "give the Runner 1 tag" :async true :effect (req (wait-for (gain-tags state :corp 1) (register-events state side card [{:event :successful-run :duration :end-of-run :unregister-once-resolved true :async true :msg "make the Runner lose 1 tag" :effect (effect (lose-tags :corp eid 1))}]) (effect-completed state side eid)))}]}) (defcard "Bastion" {:subroutines [end-the-run]}) (defcard "Battlement" {:subroutines [end-the-run end-the-run]}) (defcard "Blockchain" (let [sub-count (fn [corp] (quot (count (filter #(and (operation? %) (has-subtype? % "Transaction") (faceup? %)) (:discard corp))) 2)) sub {:label "Gain 1 [Credits], Runner loses 1 [Credits]" :msg "gain 1 [Credits] and force the Runner to lose 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 1) (lose-credits state :runner eid 1)))}] {:on-rez {:effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (operation? target) (has-subtype? target "Transaction") (or (in-discard? target) (= :discard (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))}] :subroutines [sub end-the-run]})) (defcard "Bloodletter" {:subroutines [{:async true :label "Runner trashes 1 program or top 2 cards of their Stack" :effect (req (if (empty? (filter program? (all-active-installed state :runner))) (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner {:waiting-prompt "Runner to choose an option for Bloodletter" :prompt "Trash 1 program or trash top 2 cards of the Stack?" :choices (req [(when (seq (filter program? (all-active-installed state :runner))) "Trash 1 program") (when (<= 1 (count (:deck runner))) "Trash top 2 of Stack")]) :async true :effect (req (if (= target "Trash top 2 of Stack") (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner trash-program-sub card nil)))} card nil)))}]}) (defcard "Bloom" {:subroutines [{:label "Install a piece of ice from HQ protecting another server, ignoring all costs" :prompt "Choose ICE to install from HQ in another server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (let [this (zone->name (second (get-zone card))) nice target] (continue-ability state side {:prompt (str "Choose a location to install " (:title target)) :choices (req (remove #(= this %) (corp-install-list state nice))) :async true :effect (effect (corp-install eid nice target {:ignore-all-cost true}))} card nil)))} {:label "Install a piece of ice from HQ in the next innermost position, protecting this server, ignoring all costs" :prompt "Choose ICE to install from HQ in this server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (corp-install state side eid target (zone->name (target-server run)) {:ignore-all-cost true :index (max (dec run-position) 0)}) (swap! state update-in [:run :position] inc))}]}) (defcard "Border Control" {:abilities [{:label "End the run" :msg (msg "end the run") :async true :cost [:trash] :effect (effect (end-run eid card))}] :subroutines [{:label "Gain 1 [Credits] for each ice protecting this server" :msg (msg "gain " (count (:ices (card->server state card))) " [Credits]") :async true :effect (req (let [num-ice (count (:ices (card->server state card)))] (gain-credits state :corp eid num-ice)))} end-the-run]}) (defcard "Brainstorm" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-brain-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "Builder" (let [sub {:label "Place 1 advancement token on an ICE that can be advanced protecting this server" :msg (msg "place 1 advancement token on " (card-str state target)) :choices {:card #(and (ice? %) (can-be-advanced? %))} :effect (effect (add-prop target :advance-counter 1 {:placed true}))}] {:abilities [{:label "Move Builder to the outermost position of any server" :cost [:click 1] :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)))}] :subroutines [sub sub]})) (defcard "Bullfrog" {:subroutines [(do-psi {:label "Move Bullfrog to another server" :player :corp :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)) (redirect-run target) (effect-completed eid))})]}) (defcard "Bulwark" (let [sub {:msg "gain 2 [Credits] and end the run" :async true :effect (req (wait-for (gain-credits state side 2) (end-run state side eid card)))}] {:on-rez take-bad-pub :on-encounter {:req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg "gain 2 [Credits] if there is an installed AI" :async true :effect (effect (gain-credits eid 2))} :subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") sub sub]})) (defcard "Burke Bugs" {:subroutines [(trace-ability 0 (assoc trash-program-sub :not-distinct true :player :runner :msg "force the Runner to trash a program" :label "Force the Runner to trash a program"))]}) (defcard "Caduceus" {:subroutines [(trace-ability 3 (gain-credits-sub 3)) (trace-ability 2 end-the-run)]}) (defcard "Cell Portal" {:subroutines [{:msg "make the Runner approach the outermost ICE" :effect (req (let [server (zone->name (target-server run))] (redirect-run state side server :approach-ice) (derez state side card)))}]}) (defcard "Changeling" (morph-ice "Barrier" "Sentry" end-the-run)) (defcard "Checkpoint" {:on-rez take-bad-pub :subroutines [(trace-ability 5 {:label "Do 3 meat damage when this run is successful" :msg "do 3 meat damage when this run is successful" :effect (effect (register-events card [{:event :run-ends :duration :end-of-run :async true :req (req (:successful target)) :msg "do 3 meat damage" :effect (effect (damage eid :meat 3 {:card card}))}]))})]}) (defcard "Chetana" {:subroutines [{:msg "make each player gain 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (gain-credits state :corp eid 2)))} (do-psi {:label "Do 1 net damage for each card in the Runner's grip" :msg (msg "do " (count (get-in @state [:runner :hand])) " net damage") :effect (effect (damage eid :net (count (get-in @state [:runner :hand])) {:card card}))})]}) (defcard "Chimera" {:on-rez {:prompt "Choose one subtype" :choices ["Barrier" "Code Gate" "Sentry"] :msg (msg "make it gain " target) :effect (effect (update! (assoc card :subtype-target target)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? card target) (:subtype-target card))) :value (req (:subtype-target card))}] :events [{:event :runner-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))} {:event :corp-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))}] :subroutines [end-the-run]}) (defcard "Chiyashi" {:implementation "Trash effect when using an AI to break is activated manually" :abilities [{:async true :label "Trash the top 2 cards of the Runner's Stack" :req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg (msg (str "trash " (string/join ", " (map :title (take 2 (:deck runner)))) " from the Runner's Stack")) :effect (effect (mill :corp eid :runner 2))}] :subroutines [(do-net-damage 2) (do-net-damage 2) end-the-run]}) (defcard "Chrysalis" {:flags {:rd-reveal (req true)} :subroutines [(do-net-damage 2)] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Chrysalis subroutine" :prompt "You are encountering Chrysalis. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "Chum" {:subroutines [{:label "Give +2 strength to next ICE Runner encounters" :req (req this-server) :msg (msg "give +2 strength to the next ICE the Runner encounters") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [target-ice (:ice context)] (register-floating-effect state side card {:type :ice-strength :duration :end-of-encounter :value 2 :req (req (same-card? target target-ice))}) (register-events state side card [(assoc (do-net-damage 3) :event :end-of-encounter :duration :end-of-run :unregister-once-resolved true :req (req (and (same-card? (:ice context) target-ice) (seq (remove :broken (:subroutines (:ice context)))))))])))}]))}]}) (defcard "Clairvoyant Monitor" {:subroutines [(do-psi {:label "Place 1 advancement token and end the run" :player :corp :prompt "Select a target for Clairvoyant Monitor" :msg (msg "place 1 advancement token on " (card-str state target) " and end the run") :choices {:card installed?} :effect (effect (add-prop target :advance-counter 1 {:placed true}) (end-run eid card))})]}) (defcard "Cobra" {:subroutines [trash-program-sub (do-net-damage 2)]}) (defcard "Colossus" (wall-ice [{:label "Give the Runner 1 tag (Give the Runner 2 tags)" :async true :msg (msg "give the Runner " (if (wonder-sub card 3) "2 tags" "1 tag")) :effect (effect (gain-tags :corp eid (if (wonder-sub card 3) 2 1)))} {:label "Trash 1 program (Trash 1 program and 1 resource)" :async true :msg (msg "trash 1 program" (when (wonder-sub card 3) " and 1 resource")) :effect (req (wait-for (resolve-ability state side trash-program-sub card nil) (if (wonder-sub card 3) (continue-ability state side {:prompt "Choose a resource to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (trash eid target {:cause :subroutine}))} card nil) (effect-completed state side eid))))}])) (defcard "Congratulations!" {:events [{:event :pass-ice :req (req (same-card? (:ice context) card)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}] :subroutines [{:label "Gain 2 [Credits]. The Runner gains 1 [Credits]" :msg "gain 2 [Credits]. The Runner gains 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 2) (gain-credits state :runner eid 1)))}]}) (defcard "Conundrum" {:subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") runner-loses-click end-the-run] :strength-bonus (req (if (some #(has-subtype? % "AI") (all-active-installed state :runner)) 3 0))}) (defcard "Cortex Lock" {:subroutines [{:label "Do 1 net damage for each unused memory unit the Runner has" :msg (msg "do " (available-mu state) " net damage") :effect (effect (damage eid :net (available-mu state) {:card card}))}]}) (defcard "Crick" {:subroutines [{:label "install a card from Archives" :prompt "Select a card to install from Archives" :show-discard true :async true :choices {:card #(and (not (operation? %)) (in-discard? %) (corp? %))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}] :strength-bonus (req (if (= (second (get-zone card)) :archives) 3 0))}) (defcard "Curtain Wall" {:subroutines [end-the-run end-the-run end-the-run] :strength-bonus (req (let [ices (:ices (card->server state card))] (if (same-card? card (last ices)) 4 0))) :events [{:event :trash :req (req (and (not (same-card? card target)) (= (card->server state card) (card->server state target)))) :effect (effect (update-ice-strength card))} {:event :corp-install :req (req (and (not (same-card? card (:card context))) (= (card->server state card) (card->server state (:card context))))) :effect (effect (update-ice-strength card))}]}) (defcard "Data Hound" (letfn [(dh-trash [cards] {:prompt "Choose a card to trash" :choices cards :async true :msg (msg "trash " (:title target)) :effect (req (wait-for (trash state side target {:unpreventable true :cause :subroutine}) (continue-ability state side (reorder-choice :runner :runner (remove-once #(= % target) cards) '() (count (remove-once #(= % target) cards)) (remove-once #(= % target) cards)) card nil)))})] {:subroutines [(trace-ability 2 {:async true :label "Look at the top of the stack" :msg "look at top X cards of the stack" :waiting-prompt "Corp to rearrange the top cards of the stack" :effect (req (let [c (- target (second targets)) from (take c (:deck runner))] (system-msg state :corp (str "looks at the top " (quantify c "card") " of the stack")) (if (< 1 c) (continue-ability state side (dh-trash from) card nil) (wait-for (trash state side (first from) {:unpreventable true :cause :subroutine}) (system-msg state :corp (str "trashes " (:title (first from)))) (effect-completed state side eid)))))})]})) (defcard "Data Loop" {:on-encounter {:req (req (pos? (count (:hand runner)))) :async true :effect (effect (continue-ability :runner (let [n (min 2 (count (:hand runner)))] {:prompt (str "Choose " (quantify n "card") " in your Grip to add to the top of the Stack (second card targeted will be topmost)") :choices {:max n :all true :card #(and (in-hand? %) (runner? %))} :msg (msg "add " n " cards from their Grip to the top of the Stack") :effect (req (doseq [c targets] (move state :runner c :deck {:front true})))}) card nil))} :subroutines [end-the-run-if-tagged end-the-run]}) (defcard "Data Mine" {:subroutines [{:msg "do 1 net damage" :async true :effect (req (wait-for (damage state :runner :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))}]}) (defcard "Data Raven" {:abilities [(power-counter-ability (give-tags 1))] :on-encounter {:msg "force the Runner to take 1 tag or end the run" :player :runner :prompt "Choose one" :choices ["Take 1 tag" "End the run"] :async true :effect (req (if (= target "Take 1 tag") (do (system-msg state :runner "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state :runner "ends the run") (end-run state :runner eid card))))} :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Data Ward" {:on-encounter {:player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Take 1 tag"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state :runner card :credit 3) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)) (do (system-msg state :runner "takes 1 tag on encountering Data Ward") (gain-tags state :runner eid 1))))} :subroutines [end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Datapike" {:subroutines [{:msg "force the Runner to pay 2 [Credits] if able" :async true :effect (req (wait-for (pay state :runner card :credit 2) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)))} end-the-run]}) (defcard "DNA Tracker" (let [sub {:msg "do 1 net damage and make the Runner lose 2 [Credits]" :async true :effect (req (wait-for (damage state side :net 1 {:card card}) (lose-credits state :runner eid 2)))}] {:subroutines [sub sub sub]})) (defcard "Dracō" {:on-rez {:prompt "How many power counters?" :choices :credit :msg (msg "add " target " power counters") :effect (effect (add-counter card :power target) (update-ice-strength card))} :strength-bonus (req (get-counters card :power)) :subroutines [(trace-ability 2 {:label "Give the Runner 1 tag and end the run" :msg "give the Runner 1 tag and end the run" :async true :effect (req (wait-for (gain-tags state :corp 1) (end-run state :corp eid card)))})]}) (defcard "Drafter" {:subroutines [{:label "Add 1 card from Archives to HQ" :prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))} {:async true :label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil {:ignore-all-cost true}))}]}) (defcard "Eli 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Eli 2.0" {:subroutines [{:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} end-the-run end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Endless EULA" (let [sub (end-the-run-unless-runner-pays 1)] (letfn [(break-fn [unbroken-subs total] {:async true :effect (req (if (seq unbroken-subs) (wait-for (pay state :runner (make-eid state {:source-type :subroutine}) card [:credit 1]) (system-msg state :runner (:msg async-result)) (continue-ability state side (break-fn (rest unbroken-subs) (inc total)) card nil)) (let [msgs (when (pos? total) (str "resolves " (quantify total "unbroken subroutine") " on Endless EULA" " (\"[subroutine] " (:label sub) "\")"))] (when (pos? total) (system-msg state side msgs)) (effect-completed state side eid))))})] {:subroutines [sub sub sub sub sub sub] :runner-abilities [{:req (req (<= (count (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card))) (total-available-credits state :runner eid card))) :async true :label "Pay for all unbroken subs" :effect (req (let [unbroken-subs (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card)) eid (assoc eid :source-type :subroutine)] (->> unbroken-subs (reduce resolve-subroutine card) (update! state side)) (continue-ability state side (break-fn unbroken-subs 0) card nil)))}]}))) (defcard "Enforcer 1.0" {:additional-cost [:forfeit] :subroutines [trash-program-sub (do-brain-damage 1) {:label "Trash a console" :prompt "Select a console to trash" :choices {:card #(has-subtype? % "Console")} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target {:cause :subroutine}))} {:msg "trash all virtual resources" :async true :effect (req (let [cards (filter #(has-subtype? % "Virtual") (all-active-installed state :runner))] (trash-cards state side eid cards {:cause :subroutine})))}] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Engram Flush" (let [sub {:async true :label "Reveal the grip" :msg (msg "reveal " (quantify (count (:hand runner)) "card") " from grip: " (string/join ", " (map :title (:hand runner)))) :effect (effect (reveal eid (:hand runner)))}] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :effect (req (let [cardtype target] (system-msg state side (str "uses " (:title card) " to name " target)) (register-events state side card [{:event :corp-reveal :duration :end-of-encounter :async true :req (req (and ; all revealed cards are in grip (every? in-hand? targets) ; entire grip was revealed (= (count targets) (count (:hand runner))) ; there are cards with the named card type (some #(is-type? % cardtype) targets))) :prompt "Select revealed card to trash" :choices (req (concat (filter #(is-type? % cardtype) targets) ["None"])) :msg (msg "trash " (:title target) " from grip") :effect (req (if (= "None" target) (effect-completed state side eid) (trash state side eid target {:cause :subroutine})))}])))} :subroutines [sub sub]})) (defcard "Enigma" {:subroutines [runner-loses-click end-the-run]}) (defcard "Envelope" {:subroutines [(do-net-damage 1) end-the-run]}) (defcard "Errand Boy" (let [sub {:async true :label "Draw a card or gain 1 [Credits]" :prompt "Choose one:" :choices ["Gain 1 [Credits]" "Draw 1 card"] :msg (req (if (= target "Gain 1 [Credits]") "gain 1 [Credits]" "draw 1 card")) :effect (req (if (= target "Gain 1 [Credits]") (gain-credits state :corp eid 1) (draw state :corp eid 1 nil)))}] {:subroutines [sub sub sub]})) (defcard "Excalibur" {:subroutines [{:label "The Runner cannot make another run this turn" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}]}) (defcard "Executive Functioning" {:subroutines [(trace-ability 4 (do-brain-damage 1))]}) (defcard "F2P" {:subroutines [add-runner-card-to-grip (give-tags 1)] :runner-abilities [(break-sub [:credit 2] 1 nil {:req (req (not tagged))})]}) (defcard "Fairchild" {:subroutines [(end-the-run-unless-runner-pays 4) (end-the-run-unless-runner-pays 4) (end-the-run-unless-runner "trashes an installed card" "trash an installed card" runner-trash-installed-sub) (end-the-run-unless-runner "suffers 1 brain damage" "suffer 1 brain damage" (do-brain-damage 1))]}) (defcard "Fairchild 1.0" (let [sub {:label "Force the Runner to pay 1 [Credits] or trash an installed card" :msg "force the Runner to pay 1 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 1 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 1 [Credits]") (wait-for (pay state side card :credit 1) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Fairchild 2.0" (let [sub {:label "Force the Runner to pay 2 [Credits] or trash an installed card" :msg "force the Runner to pay 2 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 2 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 2 [Credits]") (wait-for (pay state side card :credit 2) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub (do-brain-damage 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Fairchild 3.0" (let [sub {:label "Force the Runner to pay 3 [Credits] or trash an installed card" :msg "force the Runner to pay 3 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state side card :credit 3) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub {:label "Do 1 brain damage or end the run" :prompt "Choose one" :choices ["Do 1 brain damage" "End the run"] :msg (msg (string/lower-case target)) :async true :effect (req (if (= target "Do 1 brain damage") (damage state side eid :brain 1 {:card card}) (end-run state side eid card)))}] :runner-abilities [(bioroid-break 3 3)]})) (defcard "Fenris" {:on-rez take-bad-pub :subroutines [(do-brain-damage 1) end-the-run]}) (defcard "Fire Wall" (wall-ice [end-the-run])) (defcard "Flare" {:subroutines [(trace-ability 6 {:label "Trash 1 hardware, do 2 meat damage, and end the run" :async true :effect (effect (continue-ability {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :choices {:card hardware?} :msg (msg "trash " (:title target)) :async true :effect (req (wait-for (trash state side target {:cause :subroutine}) (system-msg state :corp (str "uses Flare to trash " (:title target))) (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))) :cancel-effect (req (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))} card nil))})]}) (defcard "Formicary" {:derezzed-events [{:event :approach-server :interactive (req true) :optional {:prompt "Rez Formicary?" :yes-ability {:msg "rez and move Formicary. The Runner is now approaching Formicary" :async true :effect (req (wait-for (rez state side card) (move state side (get-card state card) [:servers (target-server run) :ices] {:front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :encounter-ice) (set-current-ice state) (update-all-ice state side) (update-all-icebreakers state side) (effect-completed state side eid) (start-next-phase state side nil)))}}}] :subroutines [{:label "End the run unless the Runner suffers 2 net damage" :player :runner :async true :prompt "Suffer 2 net damage or end the run?" :choices ["2 net damage" "End the run"] :effect (req (if (= target "End the run") (do (system-msg state :runner "chooses to end the run") (end-run state :corp eid card)) (damage state :runner eid :net 2 {:card card :unpreventable true})))}]}) (defcard "Free Lunch" {:abilities [{:cost [:power 1] :label "Runner loses 1 [Credits]" :msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))}] :subroutines [add-power-counter add-power-counter]}) (defcard "Galahad" (grail-ice end-the-run)) (defcard "Gatekeeper" (let [draw-ab {:async true :prompt "Draw how many cards?" :choices {:number (req 3) :max (req 3) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} reveal-and-shuffle {:prompt "Reveal and shuffle up to 3 agendas" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (agenda? %)) :max (req 3)} :async true :effect (req (wait-for (reveal state side targets) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (effect-completed state :corp eid))) :cancel-effect (effect (shuffle! :deck) (effect-completed eid)) :msg (msg "add " (str (string/join ", " (map :title targets))) " to R&D")} draw-reveal-shuffle {:async true :label "Draw cards, reveal and shuffle agendas" :effect (req (wait-for (resolve-ability state side draw-ab card nil) (continue-ability state side reveal-and-shuffle card nil)))}] {:strength-bonus (req (if (= :this-turn (:rezzed card)) 6 0)) :subroutines [draw-reveal-shuffle end-the-run]})) (defcard "Gemini" (constellation-ice (do-net-damage 1))) (defcard "Gold Farmer" (letfn [(gf-lose-credits [state side eid n] (if (pos? n) (wait-for (lose-credits state :runner 1) (gf-lose-credits state side eid (dec n))) (effect-completed state side eid)))] {:implementation "Auto breaking will break even with too few credits" :on-break-subs {:req (req (some :printed (second targets))) :msg (msg (let [n-subs (count (filter :printed (second targets)))] (str "force the runner to lose " n-subs " [Credits] for breaking printed subs"))) :async true :effect (effect (gf-lose-credits eid (count (filter :printed (second targets)))))} :subroutines [(end-the-run-unless-runner-pays 3) (end-the-run-unless-runner-pays 3)]})) (defcard "Grim" {:on-rez take-bad-pub :subroutines [trash-program-sub]}) (defcard "Guard" {:constant-effects [{:type :bypass-ice :req (req (same-card? card target)) :value false}] :subroutines [end-the-run]}) (defcard "Gutenberg" {:subroutines [(tag-trace 7)] :strength-bonus (req (if (= (second (get-zone card)) :rd) 3 0))}) (defcard "Gyri Labyrinth" {:subroutines [{:req (req run) :label "Reduce Runner's hand size by 2" :msg "reduce the Runner's maximum hand size by 2 until the start of the next Corp turn" :effect (effect (register-floating-effect card {:type :hand-size :duration :until-corp-turn-begins :req (req (= :runner side)) :value -2}))}]}) (defcard "Hadrian's Wall" (wall-ice [end-the-run end-the-run])) (defcard "Hagen" {:subroutines [{:label "Trash 1 program" :prompt "Choose a program that is not a decoder, fracter or killer" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %) (not (has-subtype? % "Decoder")) (not (has-subtype? % "Fracter")) (not (has-subtype? % "Killer")))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))} end-the-run] :strength-bonus (req (- (count (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner)))))}) (defcard "Hailstorm" {:subroutines [{:label "Remove a card in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a card in the Runner's Heap" :choices (req (:discard runner)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg)) } card nil))} end-the-run]}) (defcard "Harvester" (let [sub {:label "Runner draws 3 cards and discards down to maximum hand size" :msg "make the Runner draw 3 cards and discard down to their maximum hand size" :async true :effect (req (wait-for (draw state :runner 3 nil) (continue-ability state :runner (let [delta (- (count (get-in @state [:runner :hand])) (hand-size state :runner))] (when (pos? delta) {:prompt (msg "Select " delta " cards to discard") :player :runner :choices {:max delta :card #(in-hand? %)} :async true :effect (req (wait-for (trash-cards state :runner targets) (system-msg state :runner (str "trashes " (string/join ", " (map :title targets)))) (effect-completed state side eid)))})) card nil)))}] {:subroutines [sub sub]})) (defcard "Heimdall 1.0" {:subroutines [(do-brain-damage 1) end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Heimdall 2.0" {:subroutines [(do-brain-damage 1) {:msg "do 1 brain damage and end the run" :effect (req (wait-for (damage state side :brain 1 {:card card}) (end-run state side eid card)))} end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Herald" {:flags {:rd-reveal (req true)} :subroutines [(gain-credits-sub 2) {:async true :label "Pay up to 2 [Credits] to place up to 2 advancement tokens" :prompt "How many advancement tokens?" :choices (req (map str (range (inc (min 2 (:credit corp)))))) :effect (req (let [c (str->int target)] (if (can-pay? state side (assoc eid :source card :source-type :subroutine) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :subroutine})] (wait-for (pay state :corp new-eid card :credit c) (system-msg state :corp (:msg async-result)) (continue-ability state side {:msg (msg "pay " c "[Credits] and place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Herald subroutines" :prompt "You are encountering Herald. Allow its subroutines to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "Himitsu-Bako" {:abilities [{:msg "add it to HQ" :cost [:credit 1] :effect (effect (move card :hand))}] :subroutines [end-the-run]}) (defcard "Hive" (let [corp-points (fn [corp] (min 5 (max 0 (- 5 (:agenda-point corp 0))))) ability {:silent (req true) :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :agenda-scored) (assoc ability :event :as-agenda :req (req (= "Corp" (:as-agenda-side target))))] :abilities [{:label "Lose subroutines" :msg (msg "lose " (- 5 (corp-points corp)) " subroutines") :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] :subroutines [end-the-run end-the-run end-the-run end-the-run end-the-run]})) (defcard "Holmegaard" {:subroutines [(trace-ability 4 {:label "Runner cannot access any cards this run" :msg "stop the Runner from accessing any cards this run" :effect (effect (prevent-access))}) {:label "Trash an icebreaker" :prompt "Choose an icebreaker to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (has-subtype? % "Icebreaker"))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}]}) (defcard "Hortum" (letfn [(hort [n] {:prompt "Choose a card to add to HQ with Hortum" :async true :choices (req (cancellable (:deck corp) :sorted)) :msg "add 1 card to HQ from R&D" :cancel-effect (req (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid)) :effect (req (move state side target :hand) (if (< n 2) (continue-ability state side (hort (inc n)) card nil) (do (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid))))})] (let [breakable-fn (req (when (or (> 3 (get-counters card :advancement)) (not (has-subtype? target "AI"))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 4 [Credits])" :breakable breakable-fn :msg (msg "gain " (if (wonder-sub card 3) "4" "1") " [Credits]") :async true :effect (effect (gain-credits :corp eid (if (wonder-sub card 3) 4 1)))} {:label "End the run (Search R&D for up to 2 cards and add them to HQ, shuffle R&D, end the run)" :async true :breakable breakable-fn :effect (req (if (wonder-sub card 3) (wait-for (resolve-ability state side (hort 1) card nil) (do (system-msg state side (str "uses Hortum to add 2 cards to HQ from R&D, " "shuffle R&D, and end the run")) (end-run state side eid card))) (do (system-msg state side (str "uses Hortum to end the run")) (end-run state side eid card))))}]}))) (defcard "Hourglass" {:subroutines [runner-loses-click runner-loses-click runner-loses-click]}) (defcard "Howler" {:subroutines [{:label "Install a piece of Bioroid ICE from HQ or Archives" :req (req (some #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid")) (concat (:hand corp) (:discard corp)))) :async true :prompt "Install ICE from HQ or Archives?" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid"))} :effect (req (wait-for (corp-install state side (make-eid state eid) target (zone->name (target-server run)) {:ignore-all-cost true :index (card-index state card)}) (let [new-ice async-result] (register-events state side card [{:event :run-ends :duration :end-of-run :async true :effect (effect (derez new-ice) (trash eid card {:cause :subroutine}))}]))))}]}) (defcard "Hudson 1.0" (let [sub {:msg "prevent the Runner from accessing more than 1 card during this run" :effect (effect (max-access 1))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Hunter" {:subroutines [(tag-trace 3)]}) (defcard "Hydra" (letfn [(otherwise-tag [message ability] {:msg (msg (if tagged message "give the Runner 1 tag")) :label (str (capitalize message) " if the Runner is tagged; otherwise, give the Runner 1 tag") :async true :effect (req (if tagged (ability state :runner eid card nil) (gain-tags state :runner eid 1)))})] {:subroutines [(otherwise-tag "do 3 net damage" (effect (damage :runner eid :net 3 {:card card}))) (otherwise-tag "gain 5 [Credits]" (effect (gain-credits :corp eid 5))) (otherwise-tag "end the run" (effect (end-run eid card)))]})) (defcard "Ice Wall" (wall-ice [end-the-run])) (defcard "Ichi 1.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 1 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Ichi 2.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 3 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Inazuma" {:subroutines [{:msg "prevent the Runner from breaking subroutines on the next piece of ICE they encounter this run" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "prevent the runner from breaking subroutines on " (:title (:ice context))) :effect (effect (register-floating-effect card (let [encountered-ice (:ice context)] {:type :cannot-break-subs-on-ice :duration :end-of-encounter :req (req (same-card? encountered-ice target)) :value true})))}]))} {:msg "prevent the Runner from jacking out until after the next piece of ICE" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [encountered-ice (:ice context)] (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :msg (msg "can jack out again after encountering " (:title encountered-ice)) :effect (req (swap! state update :run dissoc :cannot-jack-out)) :req (req (same-card? encountered-ice (:ice context)))}])))}]))}]}) (defcard "Information Overload" {:on-encounter (tag-trace 1) :on-rez {:effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))} :events [{:event :tags-changed :effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))}]}) (defcard "Interrupt 0" (let [sub {:label "Make the Runner pay 1 [Credits] to use icebreaker" :msg "make the Runner pay 1 [Credits] to use icebreakers to break subroutines during this run" :effect (effect (register-floating-effect card {:type :break-sub-additional-cost :duration :end-of-run :req (req (and ; The card is an icebreaker (has-subtype? target "Icebreaker") ; and is using a break ability (contains? (second targets) :break) (pos? (:break (second targets) 0)))) :value [:credit 1]}))}] {:subroutines [sub sub]})) (defcard "IP Block" {:on-encounter (assoc (give-tags 1) :req (req (seq (filter #(has-subtype? % "AI") (all-active-installed state :runner)))) :msg "give the runner 1 tag because there is an installed AI") :subroutines [(tag-trace 3) end-the-run-if-tagged]}) (defcard "IQ" {:subroutines [end-the-run] :strength-bonus (req (count (:hand corp))) :rez-cost-bonus (req (count (:hand corp))) :leave-play (req (remove-watch state (keyword (str "iq" (:cid card)))))}) (defcard "Ireress" (let [sub {:msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} ability {:effect (effect (reset-variable-subs card (count-bad-pub state) sub))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :corp-gain-bad-publicity) (assoc ability :event :corp-lose-bad-publicity)]})) (defcard "It's a Trap!" {:expose {:msg "do 2 net damage" :async true :effect (effect (damage eid :net 2 {:card card}))} :subroutines [(assoc runner-trash-installed-sub :effect (req (wait-for (trash state side target {:cause :subroutine}) (trash state side eid card {:cause :subroutine}))))]}) (defcard "Janus 1.0" {:subroutines [(do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Jua" {:on-encounter {:msg "prevent the Runner from installing cards for the rest of the turn" :effect (effect (register-turn-flag! card :runner-lock-install (constantly true)))} :subroutines [{:label "Choose 2 installed Runner cards, if able. The Runner must add 1 of those to the top of the Stack." :req (req (>= (count (all-installed state :runner)) 2)) :async true :prompt "Select 2 installed Runner cards" :choices {:card #(and (runner? %) (installed? %)) :max 2 :all true} :msg (msg "add either " (card-str state (first targets)) " or " (card-str state (second targets)) " to the Stack") :effect (effect (continue-ability (when (= 2 (count targets)) {:player :runner :waiting-prompt "Runner to decide which card to move" :prompt "Select a card to move to the Stack" :choices {:card #(some (partial same-card? %) targets)} :effect (req (move state :runner target :deck {:front true}) (system-msg state :runner (str "selected " (card-str state target) " to move to the Stack")))}) card nil))}]}) (defcard "Kakugo" {:events [{:event :pass-ice :async true :req (req (same-card? (:ice context) card)) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] :subroutines [end-the-run]}) (defcard "Kamali 1.0" (letfn [(better-name [kind] (if (= "hardware" kind) "piece of hardware" kind)) (runner-trash [kind] {:prompt (str "Select an installed " (better-name kind) " to trash") :label (str "Trash an installed " (better-name kind)) :msg (msg "trash " (:title target)) :async true :choices {:card #(and (installed? %) (is-type? % (capitalize kind)))} :cancel-effect (effect (system-msg (str "fails to trash an installed " (better-name kind))) (effect-completed eid)) :effect (effect (trash eid target {:cause :subroutine}))}) (sub-map [kind] {:player :runner :async true :waiting-prompt "Runner to decide on Kamali 1.0 action" :prompt "Choose one" :choices ["Take 1 brain damage" (str "Trash an installed " (better-name kind))] :effect (req (if (= target "Take 1 brain damage") (do (system-msg state :corp "uses Kamali 1.0 to give the Runner 1 brain damage") (damage state :runner eid :brain 1 {:card card})) (continue-ability state :runner (runner-trash kind) card nil)))}) (brain-trash [kind] {:label (str "Force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :msg (str "force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :async true :effect (req (wait-for (resolve-ability state side (sub-map kind) card nil) (clear-wait-prompt state :corp)))})] {:subroutines [(brain-trash "resource") (brain-trash "hardware") (brain-trash "program")] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Karunā" (let [offer-jack-out {:optional {:waiting-prompt "Runner to decide on jack out" :player :runner :prompt "Jack out?" :yes-ability {:async true :effect (effect (jack-out eid))} :no-ability {:effect (effect (system-msg :runner "chooses to continue"))}}}] {:subroutines [{:label "Do 2 net damage" :async true :effect (req (wait-for (resolve-ability state side (do-net-damage 2) card nil) (continue-ability state side offer-jack-out card nil)))} (do-net-damage 2)]})) (defcard "Kitsune" {:subroutines [{:optional {:req (req (pos? (count (:hand corp)))) :prompt "Force the Runner to access a card in HQ?" :yes-ability {:async true :prompt "Select a card in HQ to force access" :choices {:card (every-pred in-hand? corp?) :all true} :label "Force the Runner to access a card in HQ" :msg (msg "force the Runner to access " (:title target)) :effect (req (wait-for (do-access state :runner [:hq] {:no-root true :access-first target}) (trash state side eid card {:cause :subroutine})))}}}]}) (defcard "Komainu" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-net-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "Konjin" {:implementation "Encounter effect is manual" :on-encounter (do-psi {:label "Force the runner to encounter another ice" :prompt "Choose a piece of ice" :choices {:card ice? :not-self true} :msg (msg "force the Runner to encounter " (card-str state target)) :effect (req (effect-completed state side eid))})}) (defcard "Lab Dog" {:subroutines [{:label "Force the Runner to trash an installed piece of hardware" :player :runner :async true :msg (msg "force the Runner to trash " (:title target)) :prompt "Select a piece of hardware to trash" :choices {:card #(and (installed? %) (hardware? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "Lancelot" (grail-ice trash-program-sub)) (defcard "Little Engine" {:subroutines [end-the-run end-the-run {:msg "make the Runner gain 5 [Credits]" :async true :effect (effect (gain-credits :runner eid 5))}]}) (defcard "Lockdown" {:subroutines [{:label "The Runner cannot draw cards for the remainder of this turn" :msg "prevent the Runner from drawing cards" :effect (effect (prevent-draw))}]}) (defcard "Loki" {:on-encounter {:req (req (<= 2 (count (filter ice? (all-active-installed state :corp))))) :choices {:card #(and (ice? %) (active? %)) :not-self true} :effect (req (let [target-subtypes (:subtype target)] (register-floating-effect state :corp card {:type :gain-subtype :duration :end-of-run :req (req (same-card? card target)) :value (:subtypes target)}) (doseq [sub (:subroutines target)] (add-sub! state side (get-card state card) sub (:cid target) {:front true})) (register-events state side card (let [cid (:cid target)] [{:event :run-ends :unregister-once-resolved true :req (req (get-card state card)) :effect (effect (remove-subs! (get-card state card) #(= cid (:from-cid %))))}]))))} :subroutines [{:label "End the run unless the Runner shuffles their Grip into the Stack" :async true :effect (req (if (zero? (count (:hand runner))) (do (system-msg state :corp (str "uses Loki to end the run")) (end-run state side eid card)) (continue-ability state :runner {:optional {:waiting-prompt "Runner to decide to shuffle their Grip into the Stack" :prompt "Reshuffle your Grip into the Stack?" :player :runner :yes-ability {:effect (req (doseq [c (:hand runner)] (move state :runner c :deck)) (shuffle! state :runner :deck) (system-msg state :runner "shuffles their Grip into their Stack"))} :no-ability {:async true :effect (effect (system-msg :runner "doesn't shuffle their Grip into their Stack. Loki ends the run") (end-run eid card))}}} card nil)))}]}) (defcard "Loot Box" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (top-3-names [state] (map :title (top-3 state)))] {:subroutines [(end-the-run-unless-runner-pays 2) {:label "Reveal the top 3 cards of the Stack" :async true :effect (req (system-msg state side (str "uses Loot Box to reveal the top 3 cards of the stack: " (string/join ", " (top-3-names state)))) (wait-for (reveal state side (top-3 state)) (continue-ability state side {:waiting-prompt "Corp to choose a card to add to the Grip" :prompt "Choose a card to add to the Grip" :choices (req (top-3 state)) :msg (msg "add " (:title target) " to the Grip, gain " (:cost target) " [Credits] and shuffle the Stack. Loot Box is trashed") :async true :effect (req (move state :runner target :hand) (wait-for (gain-credits state :corp (:cost target)) (shuffle! state :runner :deck) (trash state side eid card {:cause :subroutine})))} card nil)))}]})) (defcard "Lotus Field" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Lycan" (morph-ice "Sentry" "Code Gate" trash-program-sub)) (defcard "Machicolation A" {:subroutines [trash-program-sub trash-program-sub trash-hardware-sub {:label "Runner loses 3[credit], if able. End the run." :msg "make the Runner lose 3[credit] and end the run" :async true :effect (req (if (>= (:credit runner) 3) (wait-for (lose-credits state :runner 3) (end-run state :corp eid card)) (end-run state :corp eid card)))}]}) (defcard "Machicolation B" {:subroutines [trash-resource-sub trash-resource-sub (do-net-damage 1) {:label "Runner loses 1[click], if able. End the run." :msg "make the Runner lose 1[click] and end the run" :async true :effect (req (lose state :runner :click 1) (end-run state :corp eid card))}]}) (defcard "Macrophage" {:subroutines [(trace-ability 4 {:label "Purge virus counters" :msg "purge virus counters" :effect (effect (purge))}) (trace-ability 3 {:label "Trash a virus" :prompt "Choose a virus to trash" :choices {:card #(and (installed? %) (has-subtype? % "Virus"))} :msg (msg "trash " (:title target)) :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}) (trace-ability 2 {:label "Remove a virus in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a virus in the Heap to remove from the game" :choices (req (cancellable (filter #(has-subtype? % "Virus") (:discard runner)) :sorted)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg))} card nil))}) (trace-ability 1 end-the-run)]}) (defcard "Magnet" (letfn [(disable-hosted [state side c] (doseq [hc (:hosted (get-card state c))] (unregister-events state side hc) (update! state side (dissoc hc :abilities))))] {:on-rez {:async true :effect (req (let [magnet card] (wait-for (resolve-ability state side {:req (req (some #(some program? (:hosted %)) (remove-once #(same-card? % magnet) (filter ice? (all-installed state corp))))) :prompt "Select a Program to host on Magnet" :choices {:card #(and (program? %) (ice? (:host %)) (not (same-card? (:host %) magnet)))} :effect (effect (host card target))} card nil) (disable-hosted state side card) (effect-completed state side eid))))} :derez-effect {:req (req (not-empty (:hosted card))) :effect (req (doseq [c (get-in card [:hosted])] (card-init state side c {:resolve-effect false})))} :events [{:event :runner-install :req (req (same-card? card (:host (:card context)))) :effect (req (disable-hosted state side card) (update-ice-strength state side card))}] :subroutines [end-the-run]})) (defcard "Mamba" {:abilities [(power-counter-ability (do-net-damage 1))] :subroutines [(do-net-damage 1) (do-psi {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1) (effect-completed eid))})]}) (defcard "Marker" {:subroutines [{:label "Give next encountered ice \"End the run\"" :msg (msg "give next encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :req (req (rezzed? (:ice context))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "Markus 1.0" {:subroutines [runner-trash-installed-sub end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Masvingo" (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}] {:advanceable :always :on-rez {:effect (effect (add-prop card :advance-counter 1))} :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}]})) (defcard "Matrix Analyzer" {:on-encounter {:cost [:credit 1] :choices {:card can-be-advanced?} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (effect (add-prop target :advance-counter 1))} :subroutines [(tag-trace 2)]}) (defcard "Mausolus" {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 3 [Credits])" :msg (msg "gain " (if (wonder-sub card 3) 3 1) "[Credits]") :async true :effect (effect (gain-credits eid (if (wonder-sub card 3) 3 1)))} {:label "Do 1 net damage (Do 3 net damage)" :async true :msg (msg "do " (if (wonder-sub card 3) 3 1) " net damage") :effect (effect (damage eid :net (if (wonder-sub card 3) 3 1) {:card card}))} {:label "Give the Runner 1 tag (and end the run)" :async true :msg (msg "give the Runner 1 tag" (when (wonder-sub card 3) " and end the run")) :effect (req (gain-tags state :corp eid 1) (if (wonder-sub card 3) (end-run state side eid card) (effect-completed state side eid)))}]}) (defcard "Meridian" {:subroutines [{:label "Gain 4 [Credits] and end the run" :waiting-prompt "Runner to choose an option for Meridian" :prompt "Choose one" :choices ["End the run" "Add Meridian to score area"] :player :runner :async true :effect (req (if (= target "End the run") (do (system-msg state :corp "uses Meridian to gain 4 [Credits] and end the run") (wait-for (gain-credits state :corp 4) (end-run state :runner eid card))) (do (system-msg state :runner "adds Meridian to their score area as an agenda worth -1 agenda points") (wait-for (as-agenda state :runner card -1) (when current-ice (continue state :corp nil) (continue state :runner nil)) (effect-completed state side eid)))))}]}) (defcard "Merlin" (grail-ice (do-net-damage 2))) (defcard "Meru Mati" {:subroutines [end-the-run] :strength-bonus (req (if (= (second (get-zone card)) :hq) 3 0))}) (defcard "Metamorph" {:subroutines [{:label "Swap two ICE or swap two installed non-ICE" :msg "swap two ICE or swap two installed non-ICE" :async true :prompt "Choose one" :req (req (or (<= 2 (count (filter ice? (all-installed state :corp)))) (<= 2 (count (remove ice? (all-installed state :corp)))))) :choices (req [(when (<= 2 (count (filter ice? (all-installed state :corp)))) "Swap two ICE") (when (<= 2 (count (remove ice? (all-installed state :corp)))) "Swap two non-ICE")]) :effect (effect (continue-ability (if (= target "Swap two ICE") {:prompt "Select the two ICE to swap" :choices {:card #(and (installed? %) (ice? %)) :not-self true :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-ice state side targets))} {:prompt "Select the two cards to swap" :choices {:card #(and (installed? %) (not (ice? %))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-installed state side targets))}) card nil))}]}) (defcard "Mganga" {:subroutines [(do-psi {:async true :label "do 2 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 2 {:card card}) (trash state :corp eid card {:cause :subroutine})))} {:async true :label "do 1 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))})]}) (defcard "Mind Game" {:subroutines [(do-psi {:label "Redirect the run to another server" :player :corp :prompt "Choose a server" :choices (req (remove #{(-> @state :run :server central->name)} servers)) :msg (msg "redirect the run to " target " and for the remainder of the run, the runner must add 1 installed card to the bottom of their stack as an additional cost to jack out") :effect (effect (redirect-run target :approach-ice) (register-floating-effect card {:type :jack-out-additional-cost :duration :end-of-run :value [:add-installed-to-bottom-of-deck 1]}) (effect-completed eid) (start-next-phase nil))})]}) (defcard "Minelayer" {:subroutines [{:msg "install an ICE from HQ" :async true :choices {:card #(and (ice? %) (in-hand? %))} :prompt "Choose an ICE to install from HQ" :effect (effect (corp-install eid target (zone->name (target-server run)) {:ignore-all-cost true}))}]}) (defcard "Mirāju" {:events [{:event :end-of-encounter :req (req (and (same-card? card (:ice context)) (:broken (first (filter :printed (:subroutines (:ice context))))))) :msg "make the Runner continue the run on Archives. Mirāju is derezzed" :effect (req (redirect-run state side "Archives" :approach-ice) (derez state side card))}] :subroutines [{:async true :label "Draw 1 card, then shuffle 1 card from HQ into R&D" :effect (req (wait-for (resolve-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil) (continue-ability state side {:prompt "Choose 1 card in HQ to shuffle into R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "shuffle 1 card in HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))} card nil)))}]}) (defcard "Mlinzi" (letfn [(net-or-trash [net-dmg mill-cnt] {:label (str "Do " net-dmg " net damage") :player :runner :waiting-prompt "Runner to choose an option for Mlinzi" :prompt "Take net damage or trash cards from the stack?" :choices (req [(str "Take " net-dmg " net damage") (when (<= mill-cnt (count (:deck runner))) (str "Trash the top " mill-cnt " cards of the stack"))]) :async true :effect (req (if (= target (str "Take " net-dmg " net damage")) (do (system-msg state :corp (str "uses Mlinzi to do " net-dmg " net damage")) (damage state :runner eid :net net-dmg {:card card})) (do (system-msg state :corp (str "uses Mlinzi to trash " (string/join ", " (map :title (take mill-cnt (:deck runner)))) " from the runner's stack")) (mill state :runner eid :runner mill-cnt))))})] {:subroutines [(net-or-trash 1 2) (net-or-trash 2 3) (net-or-trash 3 4)]})) (defcard "Mother Goddess" (let [mg {:req (req (ice? target)) :effect (effect (update-all-subtypes))}] {:constant-effects [{:type :gain-subtype :req (req (same-card? card target)) :value (req (->> (vals (:servers corp)) (mapcat :ices) (filter #(and (rezzed? %) (not (same-card? card %)))) (mapcat :subtypes)))}] :subroutines [end-the-run] :events [{:event :rez :req (req (ice? (:card context))) :effect (effect (update-all-subtypes))} (assoc mg :event :card-moved) (assoc mg :event :derez) (assoc mg :event :ice-subtype-changed)]})) (defcard "Muckraker" {:on-rez take-bad-pub :subroutines [(tag-trace 1) (tag-trace 2) (tag-trace 3) end-the-run-if-tagged]}) (defcard "Najja 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Nebula" (space-ice trash-program-sub)) (defcard "Negotiator" {:subroutines [(gain-credits-sub 2) trash-program-sub] :runner-abilities [(break-sub [:credit 2] 1)]}) (defcard "Nerine 2.0" (let [sub {:label "Do 1 brain damage and Corp may draw 1 card" :async true :msg "do 1 brain damage" :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (continue-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Neural Katana" {:subroutines [(do-net-damage 3)]}) (defcard "News Hound" (let [gain-sub {:req (req (and (= 1 (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current"))) :msg "make News Hound gain \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 1 end-the-run {:back true}))} lose-sub {:req (req (and (zero? (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current") (active? (:card context)))) :msg "make News Hound lose \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 0 nil))}] {:on-rez {:effect (req (when (pos? (count (concat (get-in @state [:corp :current]) (get-in @state [:runner :current])))) (reset-variable-subs state side card 1 end-the-run {:back true})))} :events [(assoc gain-sub :event :play-event) (assoc gain-sub :event :play-operation) (assoc lose-sub :event :corp-trash) (assoc lose-sub :event :runner-trash) (assoc lose-sub :event :game-trash)] :subroutines [(tag-trace 3)]})) (defcard "NEXT Bronze" {:subroutines [end-the-run] :strength-bonus (req (next-ice-count corp))}) (defcard "NEXT Diamond" {:rez-cost-bonus (req (- (next-ice-count corp))) :subroutines [(do-brain-damage 1) (do-brain-damage 1) {:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}]}) (defcard "NEXT Gold" (letfn [(trash-programs [cnt state side card eid] (if (> cnt 0) (wait-for (resolve-ability state side trash-program-sub card nil) (trash-programs (dec cnt) state side card eid)) (effect-completed state side eid)))] {:subroutines [{:label "Do 1 net damage for each rezzed NEXT ice" :msg (msg "do " (next-ice-count corp) " net damage") :effect (effect (damage eid :net (next-ice-count corp) {:card card}))} {:label "Trash 1 program for each rezzed NEXT ice" :async true :effect (req (trash-programs (min (count (filter program? (all-active-installed state :runner))) (next-ice-count corp)) state side card eid))}]})) (defcard "NEXT Opal" (let [sub {:label "Install a card from HQ, paying all costs" :prompt "Choose a card in HQ to install" :req (req (some #(not (operation? %)) (:hand corp))) :choices {:card #(and (not (operation? %)) (in-hand? %) (corp? %))} :async true :effect (effect (corp-install eid target nil nil)) :msg (msg (corp-install-msg target))} ability {:req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}] {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}]})) (defcard "NEXT Sapphire" {:subroutines [{:label "Draw up to X cards" :prompt "Draw how many cards?" :msg (msg "draw " target " cards") :choices {:number (req (next-ice-count corp)) :default (req 1)} :async true :effect (effect (draw eid target nil))} {:label "Add up to X cards from Archives to HQ" :prompt "Select cards to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state side c :hand))) :msg (msg "add " (let [seen (filter :seen targets) m (count (filter #(not (:seen %)) targets))] (str (string/join ", " (map :title seen)) (when (pos? m) (str (when-not (empty? seen) " and ") (quantify m "unseen card"))))) " to HQ")} {:label "Shuffle up to X cards from HQ into R&D" :prompt "Select cards to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck)) :cancel-effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle " (count targets) " cards from HQ into R&D")}]}) (defcard "NEXT Silver" {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))}]}) (defcard "Nightdancer" (let [sub {:label (str "The Runner loses [Click], if able. " "You have an additional [Click] to spend during your next turn.") :msg (str "force the runner to lose a [Click], if able. " "Corp gains an additional [Click] to spend during their next turn") :effect (req (lose state :runner :click 1) (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}] {:subroutines [sub sub]})) (defcard "Oduduwa" {:on-encounter {:msg "place 1 advancement counter on Oduduwa" :async true :effect (effect (add-prop card :advance-counter 1 {:placed true}) (continue-ability (let [card (get-card state card) counters (get-counters card :advancement)] {:optional {:prompt (str "Place " (quantify counters "advancement counter") " on another ice?") :yes-ability {:msg (msg "place " (quantify counters "advancement counter") " on " (card-str state target)) :choices {:card ice? :not-self true} :effect (effect (add-prop target :advance-counter counters {:placed true}))}}}) (get-card state card) nil))} :subroutines [end-the-run end-the-run]}) (defcard "Orion" (space-ice trash-program-sub (resolve-another-subroutine) end-the-run)) (defcard "Otoroshi" {:subroutines [{:async true :label "Place 3 advancement tokens on installed card" :msg "place 3 advancement tokens on installed card" :prompt "Choose an installed Corp card" :req (req (some (complement ice?) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (ice? %)))} :effect (req (let [c target title (if (:rezzed c) (:title c) "selected unrezzed card")] (add-counter state side c :advancement 3) (continue-ability state side {:player :runner :async true :waiting-prompt "Runner to resolve Otoroshi" :prompt (str "Access " title " or pay 3 [Credits]?") :choices ["Access card" (when (>= (:credit runner) 3) "Pay 3 [Credits]")] :msg (msg "force the Runner to " (if (= target "Access card") (str "access " title) "pay 3 [Credits]")) :effect (req (if (= target "Access card") (access-card state :runner eid c) (wait-for (pay state :runner card :credit 3) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} card nil)))}]}) (defcard "Owl" {:subroutines [{:choices {:card #(and (installed? %) (program? %))} :label "Add installed program to the top of the Runner's Stack" :msg "add an installed program to the top of the Runner's Stack" :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Runner's Stack")))}]}) (defcard "Pachinko" {:subroutines [end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Paper Wall" {:events [{:event :subroutines-broken :req (req (and (same-card? card target) (empty? (remove :broken (:subroutines target))))) :async true :effect (effect (trash :corp eid card {:cause :effect}))}] :subroutines [end-the-run]}) (defcard "Peeping Tom" (let [sub (end-the-run-unless-runner "takes 1 tag" "take 1 tag" (give-tags 1))] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [n (count (filter #(is-type? % target) (:hand runner)))] (system-msg state side (str "uses Peeping Tom to name " target ", then reveals " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip. Peeping Tom gains " n " subroutines")) (wait-for (reveal state side (:hand runner)) (gain-variable-subs state side card n sub) (effect-completed state side eid))))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]})) (defcard "Pop-up Window" {:on-encounter (gain-credits-sub 1) :subroutines [(end-the-run-unless-runner-pays 1)]}) (defcard "Pup" (let [sub {:player :runner :async true :label (str "Do 1 net damage unless the Runner pays 1 [Credits]") :prompt (str "Suffer 1 net damage or pay 1 [Credits]?") :choices ["Suffer 1 net damage" "Pay 1 [Credits]"] :effect (req (if (= "Suffer 1 net damage" target) (continue-ability state :corp (do-net-damage 1) card nil) (wait-for (pay state :runner card [:credit 1]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))}] {:subroutines [sub sub]})) (defcard "Quandary" {:subroutines [end-the-run]}) (defcard "Quicksand" {:on-encounter {:msg "add 1 power counter to Quicksand" :effect (effect (add-counter card :power 1) (update-all-ice))} :subroutines [end-the-run] :strength-bonus (req (get-counters card :power))}) (defcard "Rainbow" {:subroutines [end-the-run]}) (defcard "Ravana 1.0" (let [sub (resolve-another-subroutine #(has-subtype? % "Bioroid") "Resolve a subroutine on a rezzed bioroid ice")] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Red Tape" {:subroutines [{:label "Give +3 strength to all ICE for the remainder of the run" :msg "give +3 strength to all ICE for the remainder of the run" :effect (effect (pump-all-ice 3 :end-of-run))}]}) (defcard "Resistor" {:strength-bonus (req (count-tags state)) :subroutines [(trace-ability 4 end-the-run)]}) (defcard "Rime" {:implementation "Can be rezzed anytime already" :on-rez {:effect (effect (update-all-ice))} :subroutines [{:label "Runner loses 1 [Credit]" :msg "force the Runner to lose 1 [Credit]" :async true :effect (effect (lose-credits :runner eid 1))}] :constant-effects [{:type :ice-strength :req (req (protecting-same-server? card target)) :value 1}]}) (defcard "Rototurret" {:subroutines [trash-program-sub end-the-run]}) (defcard "Sadaka" (let [maybe-draw-effect {:optional {:player :corp :waiting-prompt "Corp to decide on Sadaka card draw action" :prompt "Draw 1 card?" :yes-ability {:async true :effect (effect (draw eid 1 nil)) :msg "draw 1 card"}}}] {:subroutines [{:label "Look at the top 3 cards of R&D" :req (req (not-empty (:deck corp))) :async true :effect (effect (continue-ability (let [top-cards (take 3 (:deck corp)) top-names (map :title top-cards)] {:waiting-prompt "Corp to decide on Sadaka R&D card actions" :prompt (str "Top 3 cards of R&D: " (string/join ", " top-names)) :choices ["Arrange cards" "Shuffle R&D"] :async true :effect (req (if (= target "Arrange cards") (wait-for (resolve-ability state side (reorder-choice :corp top-cards) card nil) (system-msg state :corp (str "rearranges the top " (quantify (count top-cards) "card") " of R&D")) (continue-ability state side maybe-draw-effect card nil)) (do (shuffle! state :corp :deck) (system-msg state :corp (str "shuffles R&D")) (continue-ability state side maybe-draw-effect card nil))))}) card nil))} {:label "Trash 1 card in HQ" :async true :effect (req (wait-for (resolve-ability state side {:waiting-prompt "Corp to select cards to trash with Sadaka" :prompt "Choose a card in HQ to trash" :choices (req (cancellable (:hand corp) :sorted)) :async true :cancel-effect (effect (system-msg "chooses not to trash a card from HQ") (effect-completed eid)) :effect (req (wait-for (trash state :corp target {:cause :subroutine}) (system-msg state :corp "trashes a card from HQ") (continue-ability state side trash-resource-sub card nil)))} card nil) (when current-ice (continue state :corp nil) (continue state :runner nil)) (system-msg state :corp "trashes Sadaka") (trash state :corp eid card nil)))}]})) (defcard "Sagittarius" (constellation-ice trash-program-sub)) (defcard "Saisentan" (let [sub {:label "Do 1 net damage" :async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [choice (get-in card [:special :saisentan]) cards async-result dmg (some #(when (= (:type %) choice) %) cards)] (if dmg (do (system-msg state :corp "uses Saisentan to deal a second net damage") (damage state side eid :net 1 {:card card})) (effect-completed state side eid)))))}] {:on-encounter {:waiting-prompt "Corp to choose Saisentan card type" :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "choose the card type " target) :effect (effect (update! (assoc-in card [:special :saisentan] target)))} :events [{:event :end-of-encounter :req (req (get-in card [:special :saisentan])) :effect (effect (update! (dissoc-in card [:special :saisentan])))}] :subroutines [sub sub sub]})) (defcard "Salvage" (zero-to-hero (tag-trace 2))) (defcard "Sand Storm" {:subroutines [{:async true :label "Move Sand Storm and the run to another server" :prompt "Choose another server and redirect the run to its outermost position" :choices (req (remove #{(zone->name (:server (:run @state)))} (cancellable servers))) :msg (msg "move Sand Storm and the run. The Runner is now running on " target ". Sand Storm is trashed") :effect (effect (redirect-run target :approach-ice) (trash eid card {:unpreventable true :cause :subroutine}))}]}) (defcard "Sandstone" {:subroutines [end-the-run] :strength-bonus (req (- (get-counters card :virus))) :on-encounter {:msg "place 1 virus counter on Sandstone" :effect (effect (add-counter card :virus 1) (update-ice-strength (get-card state card)))}}) (defcard "Sandman" {:subroutines [add-runner-card-to-grip add-runner-card-to-grip]}) (defcard "Sapper" {:flags {:rd-reveal (req true)} :subroutines [trash-program-sub] :access {:async true :optional {:req (req (and (not (in-discard? card)) (some program? (all-active-installed state :runner)))) :player :runner :waiting-prompt "Runner to decide to break Sapper subroutine" :prompt "Allow Sapper subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "Searchlight" (let [sub {:label "Trace X - Give the Runner 1 tag" :trace {:base (req (get-counters card :advancement)) :label "Give the Runner 1 tag" :successful (give-tags 1)}}] {:advanceable :always :subroutines [sub sub]})) (defcard "Seidr Adaptive Barrier" {:strength-bonus (req (count (:ices (card->server state card)))) :subroutines [end-the-run]}) (defcard "Self-Adapting Code Wall" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Sensei" {:subroutines [{:label "Give encountered ice \"End the run\"" :msg (msg "give encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :req (req (not (same-card? card (:ice context)))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "Shadow" (wall-ice [(gain-credits-sub 2) (tag-trace 3)])) (defcard "Sherlock 1.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the top of the Runner's Stack" :msg (msg "add " (:title target) " to the top of the Runner's Stack") :effect (effect (move :runner target :deck {:front true}))})] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Sherlock 2.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the bottom of the Runner's Stack" :msg (msg "add " (:title target) " to the bottom of the Runner's Stack") :effect (effect (move :runner target :deck))})] {:subroutines [sub sub (give-tags 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Shinobi" {:on-rez take-bad-pub :subroutines [(trace-ability 1 (do-net-damage 1)) (trace-ability 2 (do-net-damage 2)) (trace-ability 3 {:label "Do 3 net damage and end the run" :msg "do 3 net damage and end the run" :effect (req (wait-for (damage state side :net 3 {:card card}) (end-run state side eid card)))})]}) (defcard "Shiro" {:subroutines [{:label "Rearrange the top 3 cards of R&D" :msg "rearrange the top 3 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (effect (continue-ability (let [from (take 3 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))} {:optional {:prompt "Pay 1 [Credits] to keep the Runner from accessing the top card of R&D?" :yes-ability {:cost [:credit 1] :msg "keep the Runner from accessing the top card of R&D"} :no-ability {:async true :msg "make the Runner access the top card of R&D" :effect (effect (do-access :runner eid [:rd] {:no-root true}))}}}]}) (defcard "Slot Machine" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (effect-type [card] (keyword (str "slot-machine-top-3-" (:cid card)))) (name-builder [card] (str (:title card) " (" (:type card) ")")) (top-3-names [cards] (map name-builder cards)) (top-3-types [state card et] (->> (get-effects state :corp card et) first (keep :type) (into #{}) count)) (ability [] {:label "Encounter ability (manual)" :async true :effect (req (move state :runner (first (:deck runner)) :deck) (let [t3 (top-3 state) effect-type (effect-type card)] (register-floating-effect state side card {:type effect-type :duration :end-of-encounter :value t3}) (system-msg state side (str "uses Slot Machine to put the top card of the stack to the bottom," " then reveal the top 3 cards in the stack: " (string/join ", " (top-3-names t3)))) (reveal state side eid t3)))})] {:on-encounter (ability) :abilities [(ability)] :subroutines [{:label "Runner loses 3 [Credits]" :msg "force the Runner to lose 3 [Credits]" :async true :effect (effect (lose-credits :runner eid 3))} {:label "Gain 3 [Credits]" :async true :effect (req (let [et (effect-type card) unique-types (top-3-types state card et)] ;; When there are 3 cards in the deck, sub needs 2 or fewer unique types ;; When there are 2 cards in the deck, sub needs 1 unique type (if (or (and (<= unique-types 2) (= 3 (count (first (get-effects state :corp card et))))) (and (= unique-types 1) (= 2 (count (first (get-effects state :corp card et)))))) (do (system-msg state :corp (str "uses Slot Machine to gain 3 [Credits]")) (gain-credits state :corp eid 3)) (effect-completed state side eid))))} {:label "Place 3 advancement tokens" :async true :effect (effect (continue-ability (let [et (effect-type card) unique-types (top-3-types state card et)] (when (and (= 3 (count (first (get-effects state :corp card et)))) (= 1 unique-types)) {:choices {:card installed?} :prompt "Choose an installed card" :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 3 {:placed true}))})) card nil))}]})) (defcard "Snoop" {:on-encounter {:msg (msg "reveal the Runner's Grip (" (string/join ", " (map :title (:hand runner))) ")") :async true :effect (effect (reveal eid (:hand runner)))} :abilities [{:async true :req (req (pos? (get-counters card :power))) :cost [:power 1] :label "Reveal all cards in Grip and trash 1 card" :msg (msg "look at all cards in Grip and trash " (:title target) " using 1 power counter") :choices (req (cancellable (:hand runner) :sorted)) :prompt "Choose a card to trash" :effect (effect (reveal (:hand runner)) (trash eid target {:cause :subroutine}))}] :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Snowflake" {:subroutines [(do-psi end-the-run)]}) (defcard "Special Offer" {:subroutines [{:label "Gain 5 [Credits] and trash Special Offer" :msg "gains 5 [Credits] and trashes Special Offer" :async true :effect (req (wait-for (gain-credits state :corp 5) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "Spiderweb" {:subroutines [end-the-run end-the-run end-the-run]}) (defcard "Surveyor" (let [x (req (* 2 (count (:ices (card->server state card)))))] {:strength-bonus x :subroutines [{:label "Trace X - Give the Runner 2 tags" :trace {:base x :label "Give the Runner 2 tags" :successful (give-tags 2)}} {:label "Trace X - End the run" :trace {:base x :label "End the run" :successful end-the-run}}]})) (defcard "Susanoo-no-Mikoto" {:subroutines [{:req (req (not= (:server run) [:discard])) :msg "make the Runner continue the run on Archives" :effect (req (redirect-run state side "Archives" :approach-ice) (register-events state side card [{:event :approach-ice :duration :end-of-run :unregister-once-resolved true :msg "prevent the runner from jacking out" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :effect (req (swap! state update :run dissoc :cannot-jack-out))}]))}]))}]}) (defcard "Swarm" (let [sub {:player :runner :async true :label "Trash a program" :prompt "Let Corp trash 1 program or pay 3 [Credits]?" :choices ["Corp trash" "Pay 3 [Credits]"] :effect (req (if (= "Corp trash" target) (continue-ability state :corp trash-program-sub card nil) (wait-for (pay state :runner card [:credit 3]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :always :on-rez take-bad-pub :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) (defcard "Swordsman" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [{:async true :breakable breakable-fn :prompt "Select an AI program to trash" :msg (msg "trash " (:title target)) :label "Trash an AI program" :choices {:card #(and (installed? %) (program? %) (has-subtype? % "AI"))} :effect (effect (trash eid target {:cause :subroutine}))} (assoc (do-net-damage 1) :breakable breakable-fn)]})) (defcard "SYNC BRE" {:subroutines [(tag-trace 4) (trace-ability 2 {:label "Runner reduces cards accessed by 1 for this run" :async true :msg "reduce cards accessed for this run by 1" :effect (effect (access-bonus :total -1))})]}) (defcard "Tapestry" {:subroutines [runner-loses-click {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} {:req (req (pos? (count (:hand corp)))) :prompt "Choose a card in HQ to move to the top of R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "add 1 card in HQ to the top of R&D" :effect (effect (move target :deck {:front true}))}]}) (defcard "Taurus" (constellation-ice trash-hardware-sub)) (defcard "Thimblerig" (let [ability {:optional {:req (req (and (<= 2 (count (filter ice? (all-installed state :corp)))) (if run (same-card? (:ice context) card) true))) :prompt "Swap Thimblerig with another ice?" :yes-ability {:prompt "Choose a piece of ice to swap Thimblerig with" :choices {:card ice? :not-self true} :effect (effect (swap-ice card target)) :msg (msg "swap " (card-str state card) " with " (card-str state target))}}}] {:events [(assoc ability :event :pass-ice) (assoc ability :event :corp-turn-begins)] :subroutines [end-the-run]})) (defcard "Thoth" {:on-encounter (give-tags 1) :subroutines [(trace-ability 4 {:label "Do 1 net damage for each Runner tag" :async true :msg (msg "do " (count-tags state) " net damage") :effect (effect (damage eid :net (count-tags state) {:card card}))}) (trace-ability 4 {:label "Runner loses 1 [Credits] for each tag" :async true :msg (msg "force the Runner to lose " (count-tags state) " [Credits]") :effect (effect (lose-credits :runner eid (count-tags state)))})]}) (defcard "Tithonium" {:alternative-cost [:forfeit] :cannot-host true :subroutines [trash-program-sub trash-program-sub {:label "Trash a resource and end the run" :async true :effect (req (wait-for (resolve-ability state side {:req (req (pos? (count (filter resource? (all-installed state :runner))))) :async true :choices {:all true :card #(and (installed? %) (resource? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (complete-with-result state side eid target)))} card nil) (system-msg state side (str "uses Tithonium to " (if async-result (str "trash " (:title async-result) " and ends the run") "end the run"))) (end-run state side eid card)))}]}) (defcard "TL;DR" {:subroutines [{:label "Double subroutines on an ICE" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "duplicate each subroutine on " (:title (:ice context))) :effect (req (let [curr-subs (map #(assoc % :from-cid (:cid (:ice context))) (:subroutines (:ice context))) tldr-subs (map #(assoc % :from-cid (:cid card)) curr-subs) new-subs (->> (interleave curr-subs tldr-subs) (reduce (fn [ice sub] (add-sub ice sub (:from-cid sub) nil)) (assoc (:ice context) :subroutines [])) :subroutines (into [])) new-card (assoc (:ice context) :subroutines new-subs)] (update! state :corp new-card) (register-events state side card (let [cid (:cid card)] [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :req (req (get-card state new-card)) :effect (effect (remove-subs! (get-card state new-card) #(= cid (:from-cid %))))}]))))}]))}]}) (defcard "TMI" {:on-rez {:trace {:base 2 :msg "keep TMI rezzed" :label "Keep TMI rezzed" :unsuccessful {:effect (effect (derez card))}}} :subroutines [end-the-run]}) (defcard "Tollbooth" {:on-encounter {:async true :effect (req (wait-for (pay state :runner card [:credit 3]) (if (:cost-paid async-result) (do (system-msg state :runner (str (:msg async-result) " when encountering Tollbooth")) (effect-completed state side eid)) (do (system-msg state :runner "ends the run, as the Runner can't pay 3 [Credits] when encountering Tollbooth") (end-run state :corp eid card)))))} :subroutines [end-the-run]}) (defcard "Tour Guide" (let [ef (effect (reset-variable-subs card (count (filter asset? (all-active-installed state :corp))) end-the-run)) ability {:label "Reset number of subs" :silent (req true) :req (req (asset? target)) :effect ef} trash-req (req (and (asset? (:card target)) (installed? (:card target)) (rezzed? (:card target))))] {:on-rez {:effect ef} :events [{:event :rez :label "Reset number of subs" :silent (req true) :req (req (asset? (:card context))) :effect ef} (assoc ability :event :derez) (assoc ability :event :game-trash :req trash-req) (assoc ability :event :corp-trash :req trash-req) (assoc ability :event :runner-trash :req trash-req)]})) (defcard "Trebuchet" {:on-rez take-bad-pub :subroutines [{:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (req (trash state side eid target {:cause :subroutine}))} (trace-ability 6 {:label "The Runner cannot steal or trash Corp cards for the remainder of this run" :msg "prevent the Runner from stealing or trashing Corp cards for the remainder of the run" :effect (req (register-run-flag! state side card :can-steal (fn [state side card] ((constantly false) (toast state :runner "Cannot steal due to Trebuchet." "warning")))) (register-run-flag! state side card :can-trash (fn [state side card] ((constantly (not= (:side card) "Corp")) (toast state :runner "Cannot trash due to Trebuchet." "warning")))))})]}) (defcard "Tribunal" {:subroutines [runner-trash-installed-sub runner-trash-installed-sub runner-trash-installed-sub]}) (defcard "Troll" {:on-encounter (trace-ability 2 {:msg "force the Runner to lose [Click] or end the run" :player :runner :prompt "Choose one" :choices ["Lose [Click]" "End the run"] :async true :effect (req (if (and (= target "Lose [Click]") (can-pay? state :runner (assoc eid :source card :source-type :subroutine) card nil [:click 1])) (do (system-msg state :runner "loses [Click]") (lose state :runner :click 1) (effect-completed state :runner eid)) (do (system-msg state :corp "ends the run") (end-run state :corp eid card))))})}) (defcard "Tsurugi" {:subroutines [(end-the-run-unless-corp-pays 1) (do-net-damage 1) (do-net-damage 1) (do-net-damage 1)]}) (defcard "Turing" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [(assoc (end-the-run-unless-runner "spends [Click][Click][Click]" "spend [Click][Click][Click]" (runner-pays [:click 3])) :breakable breakable-fn)] :strength-bonus (req (if (is-remote? (second (get-zone card))) 3 0))})) (defcard "Turnpike" {:on-encounter {:msg "force the Runner to lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} :subroutines [(tag-trace 5)]}) (defcard "Tyrant" (zero-to-hero end-the-run)) (defcard "Týr" {:subroutines [(do-brain-damage 2) (combine-abilities trash-installed-sub (gain-credits-sub 3)) end-the-run] :runner-abilities [(bioroid-break 1 1 {:additional-ability {:effect (req (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}})]}) (defcard "Universal Connectivity Fee" {:subroutines [{:label "Force the Runner to lose credits" :msg (msg "force the Runner to lose " (if tagged "all credits" "1 [Credits]")) :async true :effect (req (if tagged (wait-for (lose-credits state :runner :all) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})) (lose-credits state :runner eid 1)))}]}) (defcard "Upayoga" {:subroutines [(do-psi {:label "Make the Runner lose 2 [Credits]" :msg "make the Runner lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))}) (resolve-another-subroutine #(has-subtype? % "Psi") "Resolve a subroutine on a rezzed psi ice")]}) (defcard "Uroboros" {:subroutines [(trace-ability 4 {:label "Prevent the Runner from making another run" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}) (trace-ability 4 end-the-run)]}) (defcard "Vanilla" {:subroutines [end-the-run]}) (defcard "Veritas" {:subroutines [{:label "Corp gains 2 [Credits]" :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :corp eid 2))} {:label "Runner loses 2 [Credits]" :msg "force the Runner to lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))} (trace-ability 2 (give-tags 1))]}) (defcard "Vikram 1.0" {:implementation "Program prevention is not implemented" :subroutines [{:msg "prevent the Runner from using programs for the remainder of this run"} (trace-ability 4 (do-brain-damage 1)) (trace-ability 4 (do-brain-damage 1))] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 1.0" {:subroutines [(do-brain-damage 1) end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 2.0" {:abilities [(power-counter-ability (do-brain-damage 1))] :subroutines [(trace-ability 2 add-power-counter) end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Viper" {:subroutines [(trace-ability 3 runner-loses-click) (trace-ability 3 end-the-run)]}) (defcard "Virgo" (constellation-ice (give-tags 1))) (defcard "Waiver" {:subroutines [(trace-ability 5 {:label "Reveal the grip and trash cards" :msg (msg "reveal all cards in the grip: " (string/join ", " (map :title (:hand runner)))) :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [delta (- target (second targets)) cards (filter #(<= (:cost %) delta) (:hand runner))] (system-msg state side (str "uses Waiver to trash " (string/join ", " (map :title cards)))) (trash-cards state side eid cards {:cause :subroutine}))))})]}) (defcard "Wall of Static" {:subroutines [end-the-run]}) (defcard "Wall of Thorns" {:subroutines [(do-net-damage 2) end-the-run]}) (defcard "Watchtower" {:subroutines [{:label "Search R&D and add 1 card to HQ" :prompt "Choose a card to add to HQ" :msg "add a card from R&D to HQ" :choices (req (cancellable (:deck corp) :sorted)) :cancel-effect (effect (system-msg "cancels the effect of Watchtower")) :effect (effect (shuffle! :deck) (move target :hand))}]}) (defcard "Weir" {:subroutines [runner-loses-click {:label "Runner trashes 1 card from their Grip" :req (req (pos? (count (:hand runner)))) :prompt "Choose a card to trash from your Grip" :player :runner :choices (req (:hand runner)) :not-distinct true :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " from their Grip")) (trash :runner eid target {:cause :subroutine}))}]}) (defcard "Wendigo" (implementation-note "Program prevention is not implemented" (morph-ice "Code Gate" "Barrier" {:msg "prevent the Runner from using a chosen program for the remainder of this run"}))) (defcard "Whirlpool" {:subroutines [{:label "The Runner cannot jack out for the remainder of this run" :msg "prevent the Runner from jacking out" :async true :effect (req (prevent-jack-out state side) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine}))}]}) (defcard "Winchester" (let [ab {:req (req (protecting-hq? card)) :effect (req (reset-variable-subs state :corp card 1 (trace-ability 3 end-the-run) {:back true}))}] {:subroutines [(trace-ability 4 trash-program-sub) (trace-ability 3 trash-hardware-sub)] :on-rez {:effect (effect (continue-ability ab card nil))} :events [(assoc ab :event :rez) (assoc ab :event :card-moved) (assoc ab :event :approach-ice) (assoc ab :event :swap :req (req (or (protecting-hq? target) (protecting-hq? (second targets)))))]})) (defcard "Woodcutter" (zero-to-hero (do-net-damage 1))) (defcard "Wormhole" (space-ice (resolve-another-subroutine))) (defcard "Wotan" {:subroutines [(end-the-run-unless-runner "spends [Click][Click]" "spend [Click][Click]" (runner-pays [:click 2])) (end-the-run-unless-runner-pays 3) (end-the-run-unless-runner "trashes an installed program" "trash an installed program" trash-program-sub) (end-the-run-unless-runner "takes 1 brain damage" "take 1 brain damage" (do-brain-damage 1))]}) (defcard "Wraparound" {:subroutines [end-the-run] :strength-bonus (req (if (some #(has-subtype? % "Fracter") (all-active-installed state :runner)) 0 7))}) (defcard "Yagura" {:subroutines [{:msg "look at the top card of R&D" :optional {:prompt (msg "Move " (:title (first (:deck corp))) " to the bottom of R&D?") :yes-ability {:msg "move the top card of R&D to the bottom" :effect (effect (move (first (:deck corp)) :deck))} :no-ability {:effect (effect (system-msg :corp (str "does not use Yagura to move the top card of R&D to the bottom")))}}} (do-net-damage 1)]}) (defcard "Zed 1.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [(do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Zed 2.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [trash-hardware-sub trash-hardware-sub (do-brain-damage 2)] :runner-abilities [(bioroid-break 2 2)]})
76722
(ns game.cards.ice (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;;; Helper functions specific for ICE (defn reset-variable-subs ([state side card total sub] (reset-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) old-subs (remove #(and (= (:cid card) (:from-cid %)) (:variable %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines (into [])) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn gain-variable-subs ([state side card total sub] (gain-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) card) :subroutines (into [])) new-card (assoc card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn reset-printed-subs ([state side card total sub] (reset-printed-subs state side card total sub {:printed true})) ([state side card total sub args] (let [old-subs (remove #(and (= (:cid card) (:from-cid %)) (:printed %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) ;;; Runner abilites for breaking subs (defn bioroid-break ([cost qty] (bioroid-break cost qty nil)) ([cost qty args] (break-sub [:lose-click cost] qty nil args))) ;;; General subroutines (def end-the-run "Basic ETR subroutine" {:label "End the run" :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (def end-the-run-if-tagged "ETR subroutine if tagged" {:label "End the run if the Runner is tagged" :req (req tagged) :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (defn runner-pays "Ability to pay to avoid a subroutine by paying a resource" [cost] {:async true :effect (req (wait-for (pay state :runner card cost) (when-let [payment-str (:msg async-result)] (system-msg state :runner (str payment-str " due to " (:title card) " subroutine"))) (effect-completed state side eid)))}) (defn end-the-run-unless-runner-pays [amount] {:player :runner :async true :label (str "End the run unless the Runner pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side (runner-pays [:credit amount]) card nil)))}) (defn end-the-run-unless-corp-pays [amount] {:async true :label (str "End the run unless the Corp pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (end-run state :corp eid card) (wait-for (pay state :corp card [:credit amount]) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (effect-completed state side eid))))}) (defn end-the-run-unless-runner [label prompt ability] {:player :runner :async true :label (str "End the run unless the Runner " label) :prompt (str "End the run or " prompt "?") :choices ["End the run" (capitalize prompt)] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side ability card nil)))}) (defn give-tags "Basic give runner n tags subroutine." [n] {:label (str "Give the Runner " (quantify n "tag")) :msg (str "give the Runner " (quantify n "tag")) :async true :effect (effect (gain-tags :corp eid n))}) (def add-power-counter "Adds 1 power counter to the card." {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1))}) (defn trace-ability "Run a trace with specified base strength. If successful trigger specified ability" ([base {:keys [label] :as ability}] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability}}) ([base ability un-ability] (let [label (str (:label ability) " / " (:label un-ability))] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability :unsuccessful un-ability}}))) (defn tag-trace "Trace ability for giving a tag, at specified base strength" ([base] (tag-trace base 1)) ([base n] (trace-ability base (give-tags n)))) (defn gain-credits-sub "Gain specified amount of credits" [credits] {:label (str "Gain " credits " [Credits]") :msg (str "gain " credits " [Credits]") :async true :effect (effect (gain-credits eid credits))}) (defn power-counter-ability "Does specified ability using a power counter." [{:keys [label message] :as ability}] (assoc ability :label label :msg message :cost [:power 1])) (defn do-psi "Start a psi game, if not equal do ability" ([{:keys [label] :as ability}] {:label (str "Psi Game - " label) :msg (str "start a psi game (" label ")") :psi {:not-equal ability}}) ([{:keys [label-neq] :as neq-ability} {:keys [label-eq] :as eq-ability}] {:label (str "Psi Game - " label-neq " / " label-eq) :msg (str "start a psi game (" label-neq " / " label-eq ")") :psi {:not-equal neq-ability :equal eq-ability}})) (def runner-loses-click ; Runner loses a click effect {:label "Force the Runner to lose 1 [Click]" :msg "force the Runner to lose 1 [Click] if able" :effect (effect (lose :runner :click 1))}) (def add-runner-card-to-grip "Add 1 installed Runner card to the grip" {:label "Add an installed Runner card to the grip" :req (req (not-empty (all-installed state :runner))) :waiting-prompt "Corp to select a target" :prompt "Choose a card" :choices {:card #(and (installed? %) (runner? %))} :msg "add 1 installed card to the Runner's Grip" :effect (effect (move :runner target :hand true) (system-msg (str "adds " (:title target) " to the Runner's Grip")))}) (def trash-program-sub {:prompt "Select a program to trash" :label "Trash a program" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-hardware-sub {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (hardware? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-resource-sub {:prompt "Select a resource to trash" :label "Trash a resource" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-installed-sub {:async true :prompt "Select an installed card to trash" :label "Trash an installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :effect (effect (trash eid target {:cause :subroutine}))}) (def runner-trash-installed-sub (assoc trash-installed-sub :player :runner :label "Force the Runner to trash an installed card" :msg (msg "force the Runner to trash " (:title target)))) ;;; For Advanceable ICE (defn wall-ice [subroutines] {:advanceable :always :subroutines subroutines :strength-bonus (req (get-counters card :advancement))}) (defn space-ice "Creates data for Space ICE with specified abilities." [& abilities] {:advanceable :always :subroutines (vec abilities) :rez-cost-bonus (req (* -3 (get-counters card :advancement)))}) ;;; For Grail ICE (defn grail-in-hand "Req that specified card is a Grail card in the Corp's hand." [card] (and (corp? card) (in-hand? card) (has-subtype? card "Grail"))) (def reveal-grail "Ability for revealing Grail ICE from HQ." {:label "Reveal up to 2 Grail ICE from HQ" :choices {:max 2 :card grail-in-hand} :async true :effect (effect (reveal eid targets)) :msg (let [sub-label #(:label (first (:subroutines (card-def %))))] (msg "reveal " (string/join ", " (map #(str (:title %) " (" (sub-label %) ")") targets))))}) (def resolve-grail "Ability for resolving a subroutine on a Grail ICE in HQ." {:label "Resolve a Grail ICE subroutine from HQ" :choices {:card grail-in-hand} :effect (req (doseq [ice targets] (let [subroutine (first (:subroutines (card-def ice)))] (resolve-ability state side subroutine card nil))))}) (defn grail-ice "Creates data for grail ICE" [ability] {:abilities [reveal-grail] :subroutines [ability resolve-grail]}) ;;; For NEXT ICE (defn next-ice-count "Counts number of rezzed NEXT ICE - for use with NEXT Bronze and NEXT Gold" [corp] (let [servers (flatten (seq (:servers corp))) rezzed-next? #(and (rezzed? %) (has-subtype? % "NEXT"))] (reduce (fn [c server] (+ c (count (filter rezzed-next? (:ices server))))) 0 servers))) ;;; For Morph ICE (defn morph-ice "Creates the data for morph ICE with specified types and ability." [base other ability] {:advanceable :always :constant-effects [{:type :lose-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value base} {:type :gain-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value other}] :subroutines [ability]}) ;;; For Constellation ICE (defn constellation-ice "Generates map for Constellation ICE with specified effect." [ability] {:subroutines [(-> (trace-ability 2 ability) (assoc-in [:trace :kicker] ability) (assoc-in [:trace :kicker-min] 5))]}) ;; For advance-only-while-rezzed, sub-growing ICE (defn zero-to-hero "Salvage, Tyrant, Woodcutter" [sub] (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :while-rezzed :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) ;; For 7 Wonders ICE (defn wonder-sub "Checks total number of advancement counters on a piece of ice against number" [card number] (<= number (get-counters card :advancement))) (defn resolve-another-subroutine "For cards like Orion or Upayoga." ([] (resolve-another-subroutine (constantly true) "Resolve a subroutine on another ice")) ([pred] (resolve-another-subroutine pred "Resolve a subroutine on another ice")) ([pred label] (let [pred #(and (ice? %) (rezzed? %) (pred %))] {:async true :label label :effect (effect (continue-ability (when (< 1 (count (filter pred (all-active-installed state :corp)))) {:async true :prompt "Select the ice" :choices {:card pred :all true} :effect (effect (continue-ability (let [ice target] {:async true :prompt "Select the subroutine" :choices (req (unbroken-subroutines-choice ice)) :msg (msg "resolve the subroutine (\"[subroutine] " target "\") from " (:title ice)) :effect (req (let [sub (first (filter #(= target (make-label (:sub-effect %))) (:subroutines ice)))] (continue-ability state side (:sub-effect sub) ice nil)))}) card nil))}) card nil))}))) ;;; Helper function for adding implementation notes to ICE defined with functions (defn- implementation-note "Adds an implementation note to the ice-definition" [note ice-def] (assoc ice-def :implementation note)) (def take-bad-pub ; Bad pub on rez effect {:async true :effect (effect (system-msg (str "takes 1 bad publicity from " (:title card))) (gain-bad-publicity :corp eid 1))}) ;; Card definitions (defcard "<NAME>" (let [breakable-fn (req (if (= :hq (second (get-zone card))) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:subroutines [{:msg "make the Runner lose 2 [Credits]" :breakable breakable-fn :async true :effect (effect (lose-credits :runner eid 2))} (assoc end-the-run :breakable breakable-fn)]})) (defcard "<NAME>iki" {:subroutines [(do-psi {:label "Runner draws 2 cards" :msg "make the Runner draw 2 cards" :async true :effect (effect (draw :runner eid 2 nil))}) (do-net-damage 1) (do-net-damage 1)]}) (defcard "Aimor" {:subroutines [{:async true :label "Trash the top 3 cards of the Stack. Trash Aimor." :effect (req (system-msg state :corp (str "uses Aimor to trash " (string/join ", " (map :title (take 3 (:deck runner)))) " from the Runner's Stack")) (wait-for (mill state :corp :runner 3) (system-msg state side (str "trashes Aimor")) (trash state side eid card {:cause :subroutine})))}]}) (defcard "<NAME>" (let [breakable-fn (req (if (<= 3 (get-counters card :advancement)) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1[Credit]. Place 1 advancement token." :breakable breakable-fn :msg (msg "gain 1 [Credit] and place 1 advancement token on " (card-str state target)) :prompt "Choose an installed card" :choices {:card installed?} :async true :effect (effect (add-prop target :advance-counter 1 {:placed true}) (gain-credits eid 1))} (assoc end-the-run :breakable breakable-fn)] :strength-bonus (req (if (<= 3 (get-counters card :advancement)) 3 0))})) (defcard "<NAME>" (let [corp-draw {:optional {:waiting-prompt "Corp to draw a card" :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} runner-draw {:player :runner :optional {:waiting-prompt "Runner to decide on card draw" :prompt "Pay 2 [Credits] to draw 1 card?" :yes-ability {:async true :effect (req (wait-for (pay state :runner card [:credit 2]) (if (:cost-paid async-result) (do (system-msg state :runner "pays 2 [Credits] to draw 1 card") (draw state :runner eid 1 nil)) (do (system-msg state :runner "does not draw 1 card") (effect-completed state side eid)))))} :no-ability {:effect (effect (system-msg :runner "does not draw 1 card"))}}}] {:subroutines [{:msg "rearrange the top 5 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (req (let [from (take 5 (:deck corp))] (continue-ability state side (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from)) card nil)))} {:label "Draw 1 card, runner draws 1 card" :async true :effect (req (wait-for (resolve-ability state side corp-draw card nil) (continue-ability state :runner runner-draw card nil)))} (do-net-damage 1)] :events [(assoc (do-net-damage 3) :event :end-of-encounter :req (req (and (= (:ice context) card) (seq (remove :broken (:subroutines (:ice context)))))))]})) (defcard "Archangel" {:flags {:rd-reveal (req true)} :access {:optional {:req (req (not (in-discard? card))) :waiting-prompt "Corp to decide to trigger Archangel" :prompt "Pay 3 [Credits] to force Runner to encounter Archangel?" :player :corp :yes-ability {:cost [:credit 3] :async true :msg "force the Runner to encounter Archangel" :effect (effect (continue-ability :runner {:optional {:player :runner :prompt "You are encountering Archangel. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! eid card))}}} card nil))} :no-ability {:effect (effect (system-msg :corp "declines to force the Runner to encounter Archangel"))}}} :subroutines [(trace-ability 6 add-runner-card-to-grip)]}) (defcard "<NAME>er" {:additional-cost [:forfeit] :subroutines [(gain-credits-sub 2) trash-program-sub trash-program-sub end-the-run]}) (defcard "<NAME>itect" {:flags {:untrashable-while-rezzed true} :subroutines [{:label "Look at the top 5 cards of R&D" :prompt "Choose a card to install" :async true :activatemsg "uses Architect to look at the top 5 cards of R&D" :req (req (and (not (string? target)) (not (operation? target)))) :not-distinct true :choices (req (conj (take 5 (:deck corp)) "No install")) :effect (effect (system-msg (str "chooses the card in position " (+ 1 (.indexOf (take 5 (:deck corp)) target)) " from R&D (top is 1)")) (corp-install eid target nil {:ignore-all-cost true}))} {:label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}]}) (defcard "Ashigaru" {:on-rez {:effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (corp? target) (or (in-hand? target) (= :hand (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))}]}) (defcard "Assassin" {:subroutines [(trace-ability 5 (do-net-damage 3)) (trace-ability 4 trash-program-sub)]}) (defcard "Asteroid Belt" (space-ice end-the-run)) (defcard "Authenticator" {:on-encounter {:optional {:req (req (not (:bypass run))) :player :runner :prompt "Take 1 tag to bypass?" :yes-ability {:async true :effect (req (system-msg state :runner "takes 1 tag on encountering Authenticator to bypass it") (bypass-ice state) (gain-tags state :runner eid 1 {:unpreventable true}))}}} :subroutines [(gain-credits-sub 2) end-the-run]}) (defcard "Bailiff" {:implementation "Gain credit is manual" :abilities [(gain-credits-sub 1)] :subroutines [end-the-run]}) (defcard "Bandwidth" {:subroutines [{:msg "give the Runner 1 tag" :async true :effect (req (wait-for (gain-tags state :corp 1) (register-events state side card [{:event :successful-run :duration :end-of-run :unregister-once-resolved true :async true :msg "make the Runner lose 1 tag" :effect (effect (lose-tags :corp eid 1))}]) (effect-completed state side eid)))}]}) (defcard "Bastion" {:subroutines [end-the-run]}) (defcard "Battlement" {:subroutines [end-the-run end-the-run]}) (defcard "Blockchain" (let [sub-count (fn [corp] (quot (count (filter #(and (operation? %) (has-subtype? % "Transaction") (faceup? %)) (:discard corp))) 2)) sub {:label "Gain 1 [Credits], Runner loses 1 [Credits]" :msg "gain 1 [Credits] and force the Runner to lose 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 1) (lose-credits state :runner eid 1)))}] {:on-rez {:effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (operation? target) (has-subtype? target "Transaction") (or (in-discard? target) (= :discard (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))}] :subroutines [sub end-the-run]})) (defcard "Bloodletter" {:subroutines [{:async true :label "Runner trashes 1 program or top 2 cards of their Stack" :effect (req (if (empty? (filter program? (all-active-installed state :runner))) (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner {:waiting-prompt "Runner to choose an option for Bloodletter" :prompt "Trash 1 program or trash top 2 cards of the Stack?" :choices (req [(when (seq (filter program? (all-active-installed state :runner))) "Trash 1 program") (when (<= 1 (count (:deck runner))) "Trash top 2 of Stack")]) :async true :effect (req (if (= target "Trash top 2 of Stack") (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner trash-program-sub card nil)))} card nil)))}]}) (defcard "Bloom" {:subroutines [{:label "Install a piece of ice from HQ protecting another server, ignoring all costs" :prompt "Choose ICE to install from HQ in another server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (let [this (zone->name (second (get-zone card))) nice target] (continue-ability state side {:prompt (str "Choose a location to install " (:title target)) :choices (req (remove #(= this %) (corp-install-list state nice))) :async true :effect (effect (corp-install eid nice target {:ignore-all-cost true}))} card nil)))} {:label "Install a piece of ice from HQ in the next innermost position, protecting this server, ignoring all costs" :prompt "Choose ICE to install from HQ in this server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (corp-install state side eid target (zone->name (target-server run)) {:ignore-all-cost true :index (max (dec run-position) 0)}) (swap! state update-in [:run :position] inc))}]}) (defcard "Border Control" {:abilities [{:label "End the run" :msg (msg "end the run") :async true :cost [:trash] :effect (effect (end-run eid card))}] :subroutines [{:label "Gain 1 [Credits] for each ice protecting this server" :msg (msg "gain " (count (:ices (card->server state card))) " [Credits]") :async true :effect (req (let [num-ice (count (:ices (card->server state card)))] (gain-credits state :corp eid num-ice)))} end-the-run]}) (defcard "Brainstorm" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-brain-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "Builder" (let [sub {:label "Place 1 advancement token on an ICE that can be advanced protecting this server" :msg (msg "place 1 advancement token on " (card-str state target)) :choices {:card #(and (ice? %) (can-be-advanced? %))} :effect (effect (add-prop target :advance-counter 1 {:placed true}))}] {:abilities [{:label "Move Builder to the outermost position of any server" :cost [:click 1] :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)))}] :subroutines [sub sub]})) (defcard "Bullfrog" {:subroutines [(do-psi {:label "Move Bullfrog to another server" :player :corp :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)) (redirect-run target) (effect-completed eid))})]}) (defcard "Bulwark" (let [sub {:msg "gain 2 [Credits] and end the run" :async true :effect (req (wait-for (gain-credits state side 2) (end-run state side eid card)))}] {:on-rez take-bad-pub :on-encounter {:req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg "gain 2 [Credits] if there is an installed AI" :async true :effect (effect (gain-credits eid 2))} :subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") sub sub]})) (defcard "Burke Bugs" {:subroutines [(trace-ability 0 (assoc trash-program-sub :not-distinct true :player :runner :msg "force the Runner to trash a program" :label "Force the Runner to trash a program"))]}) (defcard "Caduceus" {:subroutines [(trace-ability 3 (gain-credits-sub 3)) (trace-ability 2 end-the-run)]}) (defcard "Cell Portal" {:subroutines [{:msg "make the Runner approach the outermost ICE" :effect (req (let [server (zone->name (target-server run))] (redirect-run state side server :approach-ice) (derez state side card)))}]}) (defcard "Changeling" (morph-ice "Barrier" "Sentry" end-the-run)) (defcard "Checkpoint" {:on-rez take-bad-pub :subroutines [(trace-ability 5 {:label "Do 3 meat damage when this run is successful" :msg "do 3 meat damage when this run is successful" :effect (effect (register-events card [{:event :run-ends :duration :end-of-run :async true :req (req (:successful target)) :msg "do 3 meat damage" :effect (effect (damage eid :meat 3 {:card card}))}]))})]}) (defcard "Chetana" {:subroutines [{:msg "make each player gain 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (gain-credits state :corp eid 2)))} (do-psi {:label "Do 1 net damage for each card in the Runner's grip" :msg (msg "do " (count (get-in @state [:runner :hand])) " net damage") :effect (effect (damage eid :net (count (get-in @state [:runner :hand])) {:card card}))})]}) (defcard "Chimera" {:on-rez {:prompt "Choose one subtype" :choices ["Barrier" "Code Gate" "Sentry"] :msg (msg "make it gain " target) :effect (effect (update! (assoc card :subtype-target target)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? card target) (:subtype-target card))) :value (req (:subtype-target card))}] :events [{:event :runner-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))} {:event :corp-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))}] :subroutines [end-the-run]}) (defcard "<NAME>" {:implementation "Trash effect when using an AI to break is activated manually" :abilities [{:async true :label "Trash the top 2 cards of the Runner's Stack" :req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg (msg (str "trash " (string/join ", " (map :title (take 2 (:deck runner)))) " from the Runner's Stack")) :effect (effect (mill :corp eid :runner 2))}] :subroutines [(do-net-damage 2) (do-net-damage 2) end-the-run]}) (defcard "<NAME>" {:flags {:rd-reveal (req true)} :subroutines [(do-net-damage 2)] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Chrysalis subroutine" :prompt "You are encountering <NAME>. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "<NAME>" {:subroutines [{:label "Give +2 strength to next ICE Runner encounters" :req (req this-server) :msg (msg "give +2 strength to the next ICE the Runner encounters") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [target-ice (:ice context)] (register-floating-effect state side card {:type :ice-strength :duration :end-of-encounter :value 2 :req (req (same-card? target target-ice))}) (register-events state side card [(assoc (do-net-damage 3) :event :end-of-encounter :duration :end-of-run :unregister-once-resolved true :req (req (and (same-card? (:ice context) target-ice) (seq (remove :broken (:subroutines (:ice context)))))))])))}]))}]}) (defcard "Clairvoyant Monitor" {:subroutines [(do-psi {:label "Place 1 advancement token and end the run" :player :corp :prompt "Select a target for Clairvoyant Monitor" :msg (msg "place 1 advancement token on " (card-str state target) " and end the run") :choices {:card installed?} :effect (effect (add-prop target :advance-counter 1 {:placed true}) (end-run eid card))})]}) (defcard "Cobra" {:subroutines [trash-program-sub (do-net-damage 2)]}) (defcard "Colossus" (wall-ice [{:label "Give the Runner 1 tag (Give the Runner 2 tags)" :async true :msg (msg "give the Runner " (if (wonder-sub card 3) "2 tags" "1 tag")) :effect (effect (gain-tags :corp eid (if (wonder-sub card 3) 2 1)))} {:label "Trash 1 program (Trash 1 program and 1 resource)" :async true :msg (msg "trash 1 program" (when (wonder-sub card 3) " and 1 resource")) :effect (req (wait-for (resolve-ability state side trash-program-sub card nil) (if (wonder-sub card 3) (continue-ability state side {:prompt "Choose a resource to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (trash eid target {:cause :subroutine}))} card nil) (effect-completed state side eid))))}])) (defcard "Congratulations!" {:events [{:event :pass-ice :req (req (same-card? (:ice context) card)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}] :subroutines [{:label "Gain 2 [Credits]. The Runner gains 1 [Credits]" :msg "gain 2 [Credits]. The Runner gains 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 2) (gain-credits state :runner eid 1)))}]}) (defcard "Conundrum" {:subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") runner-loses-click end-the-run] :strength-bonus (req (if (some #(has-subtype? % "AI") (all-active-installed state :runner)) 3 0))}) (defcard "Cortex Lock" {:subroutines [{:label "Do 1 net damage for each unused memory unit the Runner has" :msg (msg "do " (available-mu state) " net damage") :effect (effect (damage eid :net (available-mu state) {:card card}))}]}) (defcard "Crick" {:subroutines [{:label "install a card from Archives" :prompt "Select a card to install from Archives" :show-discard true :async true :choices {:card #(and (not (operation? %)) (in-discard? %) (corp? %))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}] :strength-bonus (req (if (= (second (get-zone card)) :archives) 3 0))}) (defcard "Curtain Wall" {:subroutines [end-the-run end-the-run end-the-run] :strength-bonus (req (let [ices (:ices (card->server state card))] (if (same-card? card (last ices)) 4 0))) :events [{:event :trash :req (req (and (not (same-card? card target)) (= (card->server state card) (card->server state target)))) :effect (effect (update-ice-strength card))} {:event :corp-install :req (req (and (not (same-card? card (:card context))) (= (card->server state card) (card->server state (:card context))))) :effect (effect (update-ice-strength card))}]}) (defcard "Data Hound" (letfn [(dh-trash [cards] {:prompt "Choose a card to trash" :choices cards :async true :msg (msg "trash " (:title target)) :effect (req (wait-for (trash state side target {:unpreventable true :cause :subroutine}) (continue-ability state side (reorder-choice :runner :runner (remove-once #(= % target) cards) '() (count (remove-once #(= % target) cards)) (remove-once #(= % target) cards)) card nil)))})] {:subroutines [(trace-ability 2 {:async true :label "Look at the top of the stack" :msg "look at top X cards of the stack" :waiting-prompt "Corp to rearrange the top cards of the stack" :effect (req (let [c (- target (second targets)) from (take c (:deck runner))] (system-msg state :corp (str "looks at the top " (quantify c "card") " of the stack")) (if (< 1 c) (continue-ability state side (dh-trash from) card nil) (wait-for (trash state side (first from) {:unpreventable true :cause :subroutine}) (system-msg state :corp (str "trashes " (:title (first from)))) (effect-completed state side eid)))))})]})) (defcard "Data Loop" {:on-encounter {:req (req (pos? (count (:hand runner)))) :async true :effect (effect (continue-ability :runner (let [n (min 2 (count (:hand runner)))] {:prompt (str "Choose " (quantify n "card") " in your Grip to add to the top of the Stack (second card targeted will be topmost)") :choices {:max n :all true :card #(and (in-hand? %) (runner? %))} :msg (msg "add " n " cards from their Grip to the top of the Stack") :effect (req (doseq [c targets] (move state :runner c :deck {:front true})))}) card nil))} :subroutines [end-the-run-if-tagged end-the-run]}) (defcard "Data Mine" {:subroutines [{:msg "do 1 net damage" :async true :effect (req (wait-for (damage state :runner :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))}]}) (defcard "Data Raven" {:abilities [(power-counter-ability (give-tags 1))] :on-encounter {:msg "force the Runner to take 1 tag or end the run" :player :runner :prompt "Choose one" :choices ["Take 1 tag" "End the run"] :async true :effect (req (if (= target "Take 1 tag") (do (system-msg state :runner "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state :runner "ends the run") (end-run state :runner eid card))))} :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Data Ward" {:on-encounter {:player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Take 1 tag"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state :runner card :credit 3) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)) (do (system-msg state :runner "takes 1 tag on encountering Data Ward") (gain-tags state :runner eid 1))))} :subroutines [end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Datapike" {:subroutines [{:msg "force the Runner to pay 2 [Credits] if able" :async true :effect (req (wait-for (pay state :runner card :credit 2) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)))} end-the-run]}) (defcard "DNA Tracker" (let [sub {:msg "do 1 net damage and make the Runner lose 2 [Credits]" :async true :effect (req (wait-for (damage state side :net 1 {:card card}) (lose-credits state :runner eid 2)))}] {:subroutines [sub sub sub]})) (defcard "Dracō" {:on-rez {:prompt "How many power counters?" :choices :credit :msg (msg "add " target " power counters") :effect (effect (add-counter card :power target) (update-ice-strength card))} :strength-bonus (req (get-counters card :power)) :subroutines [(trace-ability 2 {:label "Give the Runner 1 tag and end the run" :msg "give the Runner 1 tag and end the run" :async true :effect (req (wait-for (gain-tags state :corp 1) (end-run state :corp eid card)))})]}) (defcard "Drafter" {:subroutines [{:label "Add 1 card from Archives to HQ" :prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))} {:async true :label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil {:ignore-all-cost true}))}]}) (defcard "Eli 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Eli 2.0" {:subroutines [{:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} end-the-run end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Endless EULA" (let [sub (end-the-run-unless-runner-pays 1)] (letfn [(break-fn [unbroken-subs total] {:async true :effect (req (if (seq unbroken-subs) (wait-for (pay state :runner (make-eid state {:source-type :subroutine}) card [:credit 1]) (system-msg state :runner (:msg async-result)) (continue-ability state side (break-fn (rest unbroken-subs) (inc total)) card nil)) (let [msgs (when (pos? total) (str "resolves " (quantify total "unbroken subroutine") " on Endless EULA" " (\"[subroutine] " (:label sub) "\")"))] (when (pos? total) (system-msg state side msgs)) (effect-completed state side eid))))})] {:subroutines [sub sub sub sub sub sub] :runner-abilities [{:req (req (<= (count (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card))) (total-available-credits state :runner eid card))) :async true :label "Pay for all unbroken subs" :effect (req (let [unbroken-subs (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card)) eid (assoc eid :source-type :subroutine)] (->> unbroken-subs (reduce resolve-subroutine card) (update! state side)) (continue-ability state side (break-fn unbroken-subs 0) card nil)))}]}))) (defcard "Enforcer 1.0" {:additional-cost [:forfeit] :subroutines [trash-program-sub (do-brain-damage 1) {:label "Trash a console" :prompt "Select a console to trash" :choices {:card #(has-subtype? % "Console")} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target {:cause :subroutine}))} {:msg "trash all virtual resources" :async true :effect (req (let [cards (filter #(has-subtype? % "Virtual") (all-active-installed state :runner))] (trash-cards state side eid cards {:cause :subroutine})))}] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Engram Flush" (let [sub {:async true :label "Reveal the grip" :msg (msg "reveal " (quantify (count (:hand runner)) "card") " from grip: " (string/join ", " (map :title (:hand runner)))) :effect (effect (reveal eid (:hand runner)))}] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :effect (req (let [cardtype target] (system-msg state side (str "uses " (:title card) " to name " target)) (register-events state side card [{:event :corp-reveal :duration :end-of-encounter :async true :req (req (and ; all revealed cards are in grip (every? in-hand? targets) ; entire grip was revealed (= (count targets) (count (:hand runner))) ; there are cards with the named card type (some #(is-type? % cardtype) targets))) :prompt "Select revealed card to trash" :choices (req (concat (filter #(is-type? % cardtype) targets) ["None"])) :msg (msg "trash " (:title target) " from grip") :effect (req (if (= "None" target) (effect-completed state side eid) (trash state side eid target {:cause :subroutine})))}])))} :subroutines [sub sub]})) (defcard "Enigma" {:subroutines [runner-loses-click end-the-run]}) (defcard "Envelope" {:subroutines [(do-net-damage 1) end-the-run]}) (defcard "Errand Boy" (let [sub {:async true :label "Draw a card or gain 1 [Credits]" :prompt "Choose one:" :choices ["Gain 1 [Credits]" "Draw 1 card"] :msg (req (if (= target "Gain 1 [Credits]") "gain 1 [Credits]" "draw 1 card")) :effect (req (if (= target "Gain 1 [Credits]") (gain-credits state :corp eid 1) (draw state :corp eid 1 nil)))}] {:subroutines [sub sub sub]})) (defcard "Excalibur" {:subroutines [{:label "The Runner cannot make another run this turn" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}]}) (defcard "Executive Functioning" {:subroutines [(trace-ability 4 (do-brain-damage 1))]}) (defcard "F2P" {:subroutines [add-runner-card-to-grip (give-tags 1)] :runner-abilities [(break-sub [:credit 2] 1 nil {:req (req (not tagged))})]}) (defcard "Fairchild" {:subroutines [(end-the-run-unless-runner-pays 4) (end-the-run-unless-runner-pays 4) (end-the-run-unless-runner "trashes an installed card" "trash an installed card" runner-trash-installed-sub) (end-the-run-unless-runner "suffers 1 brain damage" "suffer 1 brain damage" (do-brain-damage 1))]}) (defcard "Fairchild 1.0" (let [sub {:label "Force the Runner to pay 1 [Credits] or trash an installed card" :msg "force the Runner to pay 1 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 1 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 1 [Credits]") (wait-for (pay state side card :credit 1) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Fairchild 2.0" (let [sub {:label "Force the Runner to pay 2 [Credits] or trash an installed card" :msg "force the Runner to pay 2 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 2 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 2 [Credits]") (wait-for (pay state side card :credit 2) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub (do-brain-damage 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Fairchild 3.0" (let [sub {:label "Force the Runner to pay 3 [Credits] or trash an installed card" :msg "force the Runner to pay 3 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state side card :credit 3) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub {:label "Do 1 brain damage or end the run" :prompt "Choose one" :choices ["Do 1 brain damage" "End the run"] :msg (msg (string/lower-case target)) :async true :effect (req (if (= target "Do 1 brain damage") (damage state side eid :brain 1 {:card card}) (end-run state side eid card)))}] :runner-abilities [(bioroid-break 3 3)]})) (defcard "<NAME>" {:on-rez take-bad-pub :subroutines [(do-brain-damage 1) end-the-run]}) (defcard "Fire Wall" (wall-ice [end-the-run])) (defcard "Flare" {:subroutines [(trace-ability 6 {:label "Trash 1 hardware, do 2 meat damage, and end the run" :async true :effect (effect (continue-ability {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :choices {:card hardware?} :msg (msg "trash " (:title target)) :async true :effect (req (wait-for (trash state side target {:cause :subroutine}) (system-msg state :corp (str "uses Flare to trash " (:title target))) (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))) :cancel-effect (req (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))} card nil))})]}) (defcard "Formicary" {:derezzed-events [{:event :approach-server :interactive (req true) :optional {:prompt "<NAME> <NAME>?" :yes-ability {:msg "rez and move Formicary. The Runner is now approaching Formicary" :async true :effect (req (wait-for (rez state side card) (move state side (get-card state card) [:servers (target-server run) :ices] {:front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :encounter-ice) (set-current-ice state) (update-all-ice state side) (update-all-icebreakers state side) (effect-completed state side eid) (start-next-phase state side nil)))}}}] :subroutines [{:label "End the run unless the Runner suffers 2 net damage" :player :runner :async true :prompt "Suffer 2 net damage or end the run?" :choices ["2 net damage" "End the run"] :effect (req (if (= target "End the run") (do (system-msg state :runner "chooses to end the run") (end-run state :corp eid card)) (damage state :runner eid :net 2 {:card card :unpreventable true})))}]}) (defcard "Free Lunch" {:abilities [{:cost [:power 1] :label "Runner loses 1 [Credits]" :msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))}] :subroutines [add-power-counter add-power-counter]}) (defcard "G<NAME>" (grail-ice end-the-run)) (defcard "Gatekeeper" (let [draw-ab {:async true :prompt "Draw how many cards?" :choices {:number (req 3) :max (req 3) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} reveal-and-shuffle {:prompt "Reveal and shuffle up to 3 agendas" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (agenda? %)) :max (req 3)} :async true :effect (req (wait-for (reveal state side targets) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (effect-completed state :corp eid))) :cancel-effect (effect (shuffle! :deck) (effect-completed eid)) :msg (msg "add " (str (string/join ", " (map :title targets))) " to R&D")} draw-reveal-shuffle {:async true :label "Draw cards, reveal and shuffle agendas" :effect (req (wait-for (resolve-ability state side draw-ab card nil) (continue-ability state side reveal-and-shuffle card nil)))}] {:strength-bonus (req (if (= :this-turn (:rezzed card)) 6 0)) :subroutines [draw-reveal-shuffle end-the-run]})) (defcard "Gemini" (constellation-ice (do-net-damage 1))) (defcard "<NAME>" (letfn [(gf-lose-credits [state side eid n] (if (pos? n) (wait-for (lose-credits state :runner 1) (gf-lose-credits state side eid (dec n))) (effect-completed state side eid)))] {:implementation "Auto breaking will break even with too few credits" :on-break-subs {:req (req (some :printed (second targets))) :msg (msg (let [n-subs (count (filter :printed (second targets)))] (str "force the runner to lose " n-subs " [Credits] for breaking printed subs"))) :async true :effect (effect (gf-lose-credits eid (count (filter :printed (second targets)))))} :subroutines [(end-the-run-unless-runner-pays 3) (end-the-run-unless-runner-pays 3)]})) (defcard "<NAME>" {:on-rez take-bad-pub :subroutines [trash-program-sub]}) (defcard "Guard" {:constant-effects [{:type :bypass-ice :req (req (same-card? card target)) :value false}] :subroutines [end-the-run]}) (defcard "<NAME>" {:subroutines [(tag-trace 7)] :strength-bonus (req (if (= (second (get-zone card)) :rd) 3 0))}) (defcard "<NAME>" {:subroutines [{:req (req run) :label "Reduce Runner's hand size by 2" :msg "reduce the Runner's maximum hand size by 2 until the start of the next Corp turn" :effect (effect (register-floating-effect card {:type :hand-size :duration :until-corp-turn-begins :req (req (= :runner side)) :value -2}))}]}) (defcard "<NAME>" (wall-ice [end-the-run end-the-run])) (defcard "<NAME>" {:subroutines [{:label "Trash 1 program" :prompt "Choose a program that is not a decoder, fracter or killer" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %) (not (has-subtype? % "Decoder")) (not (has-subtype? % "Fracter")) (not (has-subtype? % "Killer")))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))} end-the-run] :strength-bonus (req (- (count (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner)))))}) (defcard "Hailstorm" {:subroutines [{:label "Remove a card in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a card in the Runner's Heap" :choices (req (:discard runner)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg)) } card nil))} end-the-run]}) (defcard "Harvester" (let [sub {:label "Runner draws 3 cards and discards down to maximum hand size" :msg "make the Runner draw 3 cards and discard down to their maximum hand size" :async true :effect (req (wait-for (draw state :runner 3 nil) (continue-ability state :runner (let [delta (- (count (get-in @state [:runner :hand])) (hand-size state :runner))] (when (pos? delta) {:prompt (msg "Select " delta " cards to discard") :player :runner :choices {:max delta :card #(in-hand? %)} :async true :effect (req (wait-for (trash-cards state :runner targets) (system-msg state :runner (str "trashes " (string/join ", " (map :title targets)))) (effect-completed state side eid)))})) card nil)))}] {:subroutines [sub sub]})) (defcard "Heimdall 1.0" {:subroutines [(do-brain-damage 1) end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Heimdall 2.0" {:subroutines [(do-brain-damage 1) {:msg "do 1 brain damage and end the run" :effect (req (wait-for (damage state side :brain 1 {:card card}) (end-run state side eid card)))} end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Herald" {:flags {:rd-reveal (req true)} :subroutines [(gain-credits-sub 2) {:async true :label "Pay up to 2 [Credits] to place up to 2 advancement tokens" :prompt "How many advancement tokens?" :choices (req (map str (range (inc (min 2 (:credit corp)))))) :effect (req (let [c (str->int target)] (if (can-pay? state side (assoc eid :source card :source-type :subroutine) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :subroutine})] (wait-for (pay state :corp new-eid card :credit c) (system-msg state :corp (:msg async-result)) (continue-ability state side {:msg (msg "pay " c "[Credits] and place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Herald subroutines" :prompt "You are encountering Herald. Allow its subroutines to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "<NAME>" {:abilities [{:msg "add it to HQ" :cost [:credit 1] :effect (effect (move card :hand))}] :subroutines [end-the-run]}) (defcard "<NAME>" (let [corp-points (fn [corp] (min 5 (max 0 (- 5 (:agenda-point corp 0))))) ability {:silent (req true) :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :agenda-scored) (assoc ability :event :as-agenda :req (req (= "Corp" (:as-agenda-side target))))] :abilities [{:label "Lose subroutines" :msg (msg "lose " (- 5 (corp-points corp)) " subroutines") :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] :subroutines [end-the-run end-the-run end-the-run end-the-run end-the-run]})) (defcard "<NAME>" {:subroutines [(trace-ability 4 {:label "Runner cannot access any cards this run" :msg "stop the Runner from accessing any cards this run" :effect (effect (prevent-access))}) {:label "Trash an icebreaker" :prompt "Choose an icebreaker to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (has-subtype? % "Icebreaker"))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}]}) (defcard "<NAME>" (letfn [(hort [n] {:prompt "Choose a card to add to HQ with Hortum" :async true :choices (req (cancellable (:deck corp) :sorted)) :msg "add 1 card to HQ from R&D" :cancel-effect (req (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid)) :effect (req (move state side target :hand) (if (< n 2) (continue-ability state side (hort (inc n)) card nil) (do (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid))))})] (let [breakable-fn (req (when (or (> 3 (get-counters card :advancement)) (not (has-subtype? target "AI"))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 4 [Credits])" :breakable breakable-fn :msg (msg "gain " (if (wonder-sub card 3) "4" "1") " [Credits]") :async true :effect (effect (gain-credits :corp eid (if (wonder-sub card 3) 4 1)))} {:label "End the run (Search R&D for up to 2 cards and add them to HQ, shuffle R&D, end the run)" :async true :breakable breakable-fn :effect (req (if (wonder-sub card 3) (wait-for (resolve-ability state side (hort 1) card nil) (do (system-msg state side (str "uses Hortum to add 2 cards to HQ from R&D, " "shuffle R&D, and end the run")) (end-run state side eid card))) (do (system-msg state side (str "uses Hortum to end the run")) (end-run state side eid card))))}]}))) (defcard "Hourglass" {:subroutines [runner-loses-click runner-loses-click runner-loses-click]}) (defcard "<NAME>" {:subroutines [{:label "Install a piece of Bioroid ICE from HQ or Archives" :req (req (some #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid")) (concat (:hand corp) (:discard corp)))) :async true :prompt "Install ICE from HQ or Archives?" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid"))} :effect (req (wait-for (corp-install state side (make-eid state eid) target (zone->name (target-server run)) {:ignore-all-cost true :index (card-index state card)}) (let [new-ice async-result] (register-events state side card [{:event :run-ends :duration :end-of-run :async true :effect (effect (derez new-ice) (trash eid card {:cause :subroutine}))}]))))}]}) (defcard "<NAME>udson 1.0" (let [sub {:msg "prevent the Runner from accessing more than 1 card during this run" :effect (effect (max-access 1))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "<NAME>unter" {:subroutines [(tag-trace 3)]}) (defcard "Hydra" (letfn [(otherwise-tag [message ability] {:msg (msg (if tagged message "give the Runner 1 tag")) :label (str (capitalize message) " if the Runner is tagged; otherwise, give the Runner 1 tag") :async true :effect (req (if tagged (ability state :runner eid card nil) (gain-tags state :runner eid 1)))})] {:subroutines [(otherwise-tag "do 3 net damage" (effect (damage :runner eid :net 3 {:card card}))) (otherwise-tag "gain 5 [Credits]" (effect (gain-credits :corp eid 5))) (otherwise-tag "end the run" (effect (end-run eid card)))]})) (defcard "Ice Wall" (wall-ice [end-the-run])) (defcard "Ichi 1.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 1 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Ichi 2.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 3 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Inazuma" {:subroutines [{:msg "prevent the Runner from breaking subroutines on the next piece of ICE they encounter this run" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "prevent the runner from breaking subroutines on " (:title (:ice context))) :effect (effect (register-floating-effect card (let [encountered-ice (:ice context)] {:type :cannot-break-subs-on-ice :duration :end-of-encounter :req (req (same-card? encountered-ice target)) :value true})))}]))} {:msg "prevent the Runner from jacking out until after the next piece of ICE" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [encountered-ice (:ice context)] (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :msg (msg "can jack out again after encountering " (:title encountered-ice)) :effect (req (swap! state update :run dissoc :cannot-jack-out)) :req (req (same-card? encountered-ice (:ice context)))}])))}]))}]}) (defcard "Information Overload" {:on-encounter (tag-trace 1) :on-rez {:effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))} :events [{:event :tags-changed :effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))}]}) (defcard "Interrupt 0" (let [sub {:label "Make the Runner pay 1 [Credits] to use icebreaker" :msg "make the Runner pay 1 [Credits] to use icebreakers to break subroutines during this run" :effect (effect (register-floating-effect card {:type :break-sub-additional-cost :duration :end-of-run :req (req (and ; The card is an icebreaker (has-subtype? target "Icebreaker") ; and is using a break ability (contains? (second targets) :break) (pos? (:break (second targets) 0)))) :value [:credit 1]}))}] {:subroutines [sub sub]})) (defcard "IP Block" {:on-encounter (assoc (give-tags 1) :req (req (seq (filter #(has-subtype? % "AI") (all-active-installed state :runner)))) :msg "give the runner 1 tag because there is an installed AI") :subroutines [(tag-trace 3) end-the-run-if-tagged]}) (defcard "IQ" {:subroutines [end-the-run] :strength-bonus (req (count (:hand corp))) :rez-cost-bonus (req (count (:hand corp))) :leave-play (req (remove-watch state (keyword (str "iq" (:cid card)))))}) (defcard "Ireress" (let [sub {:msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} ability {:effect (effect (reset-variable-subs card (count-bad-pub state) sub))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :corp-gain-bad-publicity) (assoc ability :event :corp-lose-bad-publicity)]})) (defcard "It's a Trap!" {:expose {:msg "do 2 net damage" :async true :effect (effect (damage eid :net 2 {:card card}))} :subroutines [(assoc runner-trash-installed-sub :effect (req (wait-for (trash state side target {:cause :subroutine}) (trash state side eid card {:cause :subroutine}))))]}) (defcard "<NAME>us 1.0" {:subroutines [(do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "<NAME>" {:on-encounter {:msg "prevent the Runner from installing cards for the rest of the turn" :effect (effect (register-turn-flag! card :runner-lock-install (constantly true)))} :subroutines [{:label "Choose 2 installed Runner cards, if able. The Runner must add 1 of those to the top of the Stack." :req (req (>= (count (all-installed state :runner)) 2)) :async true :prompt "Select 2 installed Runner cards" :choices {:card #(and (runner? %) (installed? %)) :max 2 :all true} :msg (msg "add either " (card-str state (first targets)) " or " (card-str state (second targets)) " to the Stack") :effect (effect (continue-ability (when (= 2 (count targets)) {:player :runner :waiting-prompt "Runner to decide which card to move" :prompt "Select a card to move to the Stack" :choices {:card #(some (partial same-card? %) targets)} :effect (req (move state :runner target :deck {:front true}) (system-msg state :runner (str "selected " (card-str state target) " to move to the Stack")))}) card nil))}]}) (defcard "Kakugo" {:events [{:event :pass-ice :async true :req (req (same-card? (:ice context) card)) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] :subroutines [end-the-run]}) (defcard "Kamali 1.0" (letfn [(better-name [kind] (if (= "hardware" kind) "piece of hardware" kind)) (runner-trash [kind] {:prompt (str "Select an installed " (better-name kind) " to trash") :label (str "Trash an installed " (better-name kind)) :msg (msg "trash " (:title target)) :async true :choices {:card #(and (installed? %) (is-type? % (capitalize kind)))} :cancel-effect (effect (system-msg (str "fails to trash an installed " (better-name kind))) (effect-completed eid)) :effect (effect (trash eid target {:cause :subroutine}))}) (sub-map [kind] {:player :runner :async true :waiting-prompt "Runner to decide on Kamali 1.0 action" :prompt "Choose one" :choices ["Take 1 brain damage" (str "Trash an installed " (better-name kind))] :effect (req (if (= target "Take 1 brain damage") (do (system-msg state :corp "uses Kamali 1.0 to give the Runner 1 brain damage") (damage state :runner eid :brain 1 {:card card})) (continue-ability state :runner (runner-trash kind) card nil)))}) (brain-trash [kind] {:label (str "Force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :msg (str "force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :async true :effect (req (wait-for (resolve-ability state side (sub-map kind) card nil) (clear-wait-prompt state :corp)))})] {:subroutines [(brain-trash "resource") (brain-trash "hardware") (brain-trash "program")] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Karunā" (let [offer-jack-out {:optional {:waiting-prompt "Runner to decide on jack out" :player :runner :prompt "Jack out?" :yes-ability {:async true :effect (effect (jack-out eid))} :no-ability {:effect (effect (system-msg :runner "chooses to continue"))}}}] {:subroutines [{:label "Do 2 net damage" :async true :effect (req (wait-for (resolve-ability state side (do-net-damage 2) card nil) (continue-ability state side offer-jack-out card nil)))} (do-net-damage 2)]})) (defcard "Kitsune" {:subroutines [{:optional {:req (req (pos? (count (:hand corp)))) :prompt "Force the Runner to access a card in HQ?" :yes-ability {:async true :prompt "Select a card in HQ to force access" :choices {:card (every-pred in-hand? corp?) :all true} :label "Force the Runner to access a card in HQ" :msg (msg "force the Runner to access " (:title target)) :effect (req (wait-for (do-access state :runner [:hq] {:no-root true :access-first target}) (trash state side eid card {:cause :subroutine})))}}}]}) (defcard "<NAME>" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-net-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "<NAME>" {:implementation "Encounter effect is manual" :on-encounter (do-psi {:label "Force the runner to encounter another ice" :prompt "Choose a piece of ice" :choices {:card ice? :not-self true} :msg (msg "force the Runner to encounter " (card-str state target)) :effect (req (effect-completed state side eid))})}) (defcard "<NAME>" {:subroutines [{:label "Force the Runner to trash an installed piece of hardware" :player :runner :async true :msg (msg "force the Runner to trash " (:title target)) :prompt "Select a piece of hardware to trash" :choices {:card #(and (installed? %) (hardware? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "<NAME>" (grail-ice trash-program-sub)) (defcard "Little Engine" {:subroutines [end-the-run end-the-run {:msg "make the Runner gain 5 [Credits]" :async true :effect (effect (gain-credits :runner eid 5))}]}) (defcard "Lockdown" {:subroutines [{:label "The Runner cannot draw cards for the remainder of this turn" :msg "prevent the Runner from drawing cards" :effect (effect (prevent-draw))}]}) (defcard "Loki" {:on-encounter {:req (req (<= 2 (count (filter ice? (all-active-installed state :corp))))) :choices {:card #(and (ice? %) (active? %)) :not-self true} :effect (req (let [target-subtypes (:subtype target)] (register-floating-effect state :corp card {:type :gain-subtype :duration :end-of-run :req (req (same-card? card target)) :value (:subtypes target)}) (doseq [sub (:subroutines target)] (add-sub! state side (get-card state card) sub (:cid target) {:front true})) (register-events state side card (let [cid (:cid target)] [{:event :run-ends :unregister-once-resolved true :req (req (get-card state card)) :effect (effect (remove-subs! (get-card state card) #(= cid (:from-cid %))))}]))))} :subroutines [{:label "End the run unless the Runner shuffles their Grip into the Stack" :async true :effect (req (if (zero? (count (:hand runner))) (do (system-msg state :corp (str "uses Loki to end the run")) (end-run state side eid card)) (continue-ability state :runner {:optional {:waiting-prompt "Runner to decide to shuffle their Grip into the Stack" :prompt "Reshuffle your Grip into the Stack?" :player :runner :yes-ability {:effect (req (doseq [c (:hand runner)] (move state :runner c :deck)) (shuffle! state :runner :deck) (system-msg state :runner "shuffles their Grip into their Stack"))} :no-ability {:async true :effect (effect (system-msg :runner "doesn't shuffle their Grip into their Stack. Loki ends the run") (end-run eid card))}}} card nil)))}]}) (defcard "Loot Box" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (top-3-names [state] (map :title (top-3 state)))] {:subroutines [(end-the-run-unless-runner-pays 2) {:label "Reveal the top 3 cards of the Stack" :async true :effect (req (system-msg state side (str "uses Loot Box to reveal the top 3 cards of the stack: " (string/join ", " (top-3-names state)))) (wait-for (reveal state side (top-3 state)) (continue-ability state side {:waiting-prompt "Corp to choose a card to add to the Grip" :prompt "Choose a card to add to the Grip" :choices (req (top-3 state)) :msg (msg "add " (:title target) " to the Grip, gain " (:cost target) " [Credits] and shuffle the Stack. Loot Box is trashed") :async true :effect (req (move state :runner target :hand) (wait-for (gain-credits state :corp (:cost target)) (shuffle! state :runner :deck) (trash state side eid card {:cause :subroutine})))} card nil)))}]})) (defcard "Lotus Field" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Lycan" (morph-ice "Sentry" "Code Gate" trash-program-sub)) (defcard "Machicolation A" {:subroutines [trash-program-sub trash-program-sub trash-hardware-sub {:label "Runner loses 3[credit], if able. End the run." :msg "make the Runner lose 3[credit] and end the run" :async true :effect (req (if (>= (:credit runner) 3) (wait-for (lose-credits state :runner 3) (end-run state :corp eid card)) (end-run state :corp eid card)))}]}) (defcard "Machicolation B" {:subroutines [trash-resource-sub trash-resource-sub (do-net-damage 1) {:label "Runner loses 1[click], if able. End the run." :msg "make the Runner lose 1[click] and end the run" :async true :effect (req (lose state :runner :click 1) (end-run state :corp eid card))}]}) (defcard "Macrophage" {:subroutines [(trace-ability 4 {:label "Purge virus counters" :msg "purge virus counters" :effect (effect (purge))}) (trace-ability 3 {:label "Trash a virus" :prompt "Choose a virus to trash" :choices {:card #(and (installed? %) (has-subtype? % "Virus"))} :msg (msg "trash " (:title target)) :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}) (trace-ability 2 {:label "Remove a virus in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a virus in the Heap to remove from the game" :choices (req (cancellable (filter #(has-subtype? % "Virus") (:discard runner)) :sorted)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg))} card nil))}) (trace-ability 1 end-the-run)]}) (defcard "Magnet" (letfn [(disable-hosted [state side c] (doseq [hc (:hosted (get-card state c))] (unregister-events state side hc) (update! state side (dissoc hc :abilities))))] {:on-rez {:async true :effect (req (let [magnet card] (wait-for (resolve-ability state side {:req (req (some #(some program? (:hosted %)) (remove-once #(same-card? % magnet) (filter ice? (all-installed state corp))))) :prompt "Select a Program to host on Magnet" :choices {:card #(and (program? %) (ice? (:host %)) (not (same-card? (:host %) magnet)))} :effect (effect (host card target))} card nil) (disable-hosted state side card) (effect-completed state side eid))))} :derez-effect {:req (req (not-empty (:hosted card))) :effect (req (doseq [c (get-in card [:hosted])] (card-init state side c {:resolve-effect false})))} :events [{:event :runner-install :req (req (same-card? card (:host (:card context)))) :effect (req (disable-hosted state side card) (update-ice-strength state side card))}] :subroutines [end-the-run]})) (defcard "Mamba" {:abilities [(power-counter-ability (do-net-damage 1))] :subroutines [(do-net-damage 1) (do-psi {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1) (effect-completed eid))})]}) (defcard "Marker" {:subroutines [{:label "Give next encountered ice \"End the run\"" :msg (msg "give next encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :req (req (rezzed? (:ice context))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "<NAME>us 1.0" {:subroutines [runner-trash-installed-sub end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "<NAME>" (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}] {:advanceable :always :on-rez {:effect (effect (add-prop card :advance-counter 1))} :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}]})) (defcard "<NAME>" {:on-encounter {:cost [:credit 1] :choices {:card can-be-advanced?} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (effect (add-prop target :advance-counter 1))} :subroutines [(tag-trace 2)]}) (defcard "<NAME>" {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 3 [Credits])" :msg (msg "gain " (if (wonder-sub card 3) 3 1) "[Credits]") :async true :effect (effect (gain-credits eid (if (wonder-sub card 3) 3 1)))} {:label "Do 1 net damage (Do 3 net damage)" :async true :msg (msg "do " (if (wonder-sub card 3) 3 1) " net damage") :effect (effect (damage eid :net (if (wonder-sub card 3) 3 1) {:card card}))} {:label "Give the Runner 1 tag (and end the run)" :async true :msg (msg "give the Runner 1 tag" (when (wonder-sub card 3) " and end the run")) :effect (req (gain-tags state :corp eid 1) (if (wonder-sub card 3) (end-run state side eid card) (effect-completed state side eid)))}]}) (defcard "<NAME>" {:subroutines [{:label "Gain 4 [Credits] and end the run" :waiting-prompt "Runner to choose an option for <NAME>ian" :prompt "Choose one" :choices ["End the run" "Add <NAME>idian to score area"] :player :runner :async true :effect (req (if (= target "End the run") (do (system-msg state :corp "uses <NAME>idian to gain 4 [Credits] and end the run") (wait-for (gain-credits state :corp 4) (end-run state :runner eid card))) (do (system-msg state :runner "adds <NAME>ian to their score area as an agenda worth -1 agenda points") (wait-for (as-agenda state :runner card -1) (when current-ice (continue state :corp nil) (continue state :runner nil)) (effect-completed state side eid)))))}]}) (defcard "<NAME>" (grail-ice (do-net-damage 2))) (defcard "<NAME>" {:subroutines [end-the-run] :strength-bonus (req (if (= (second (get-zone card)) :hq) 3 0))}) (defcard "<NAME>amorph" {:subroutines [{:label "Swap two ICE or swap two installed non-ICE" :msg "swap two ICE or swap two installed non-ICE" :async true :prompt "Choose one" :req (req (or (<= 2 (count (filter ice? (all-installed state :corp)))) (<= 2 (count (remove ice? (all-installed state :corp)))))) :choices (req [(when (<= 2 (count (filter ice? (all-installed state :corp)))) "Swap two ICE") (when (<= 2 (count (remove ice? (all-installed state :corp)))) "Swap two non-ICE")]) :effect (effect (continue-ability (if (= target "Swap two ICE") {:prompt "Select the two ICE to swap" :choices {:card #(and (installed? %) (ice? %)) :not-self true :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-ice state side targets))} {:prompt "Select the two cards to swap" :choices {:card #(and (installed? %) (not (ice? %))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-installed state side targets))}) card nil))}]}) (defcard "Mganga" {:subroutines [(do-psi {:async true :label "do 2 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 2 {:card card}) (trash state :corp eid card {:cause :subroutine})))} {:async true :label "do 1 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))})]}) (defcard "Mind Game" {:subroutines [(do-psi {:label "Redirect the run to another server" :player :corp :prompt "Choose a server" :choices (req (remove #{(-> @state :run :server central->name)} servers)) :msg (msg "redirect the run to " target " and for the remainder of the run, the runner must add 1 installed card to the bottom of their stack as an additional cost to jack out") :effect (effect (redirect-run target :approach-ice) (register-floating-effect card {:type :jack-out-additional-cost :duration :end-of-run :value [:add-installed-to-bottom-of-deck 1]}) (effect-completed eid) (start-next-phase nil))})]}) (defcard "Minelayer" {:subroutines [{:msg "install an ICE from HQ" :async true :choices {:card #(and (ice? %) (in-hand? %))} :prompt "Choose an ICE to install from HQ" :effect (effect (corp-install eid target (zone->name (target-server run)) {:ignore-all-cost true}))}]}) (defcard "<NAME>āju" {:events [{:event :end-of-encounter :req (req (and (same-card? card (:ice context)) (:broken (first (filter :printed (:subroutines (:ice context))))))) :msg "make the Runner continue the run on Archives. Mirāju is derezzed" :effect (req (redirect-run state side "Archives" :approach-ice) (derez state side card))}] :subroutines [{:async true :label "Draw 1 card, then shuffle 1 card from HQ into R&D" :effect (req (wait-for (resolve-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil) (continue-ability state side {:prompt "Choose 1 card in HQ to shuffle into R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "shuffle 1 card in HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))} card nil)))}]}) (defcard "<NAME>" (letfn [(net-or-trash [net-dmg mill-cnt] {:label (str "Do " net-dmg " net damage") :player :runner :waiting-prompt "Runner to choose an option for Mlinzi" :prompt "Take net damage or trash cards from the stack?" :choices (req [(str "Take " net-dmg " net damage") (when (<= mill-cnt (count (:deck runner))) (str "Trash the top " mill-cnt " cards of the stack"))]) :async true :effect (req (if (= target (str "Take " net-dmg " net damage")) (do (system-msg state :corp (str "uses Mlinzi to do " net-dmg " net damage")) (damage state :runner eid :net net-dmg {:card card})) (do (system-msg state :corp (str "uses Mlinzi to trash " (string/join ", " (map :title (take mill-cnt (:deck runner)))) " from the runner's stack")) (mill state :runner eid :runner mill-cnt))))})] {:subroutines [(net-or-trash 1 2) (net-or-trash 2 3) (net-or-trash 3 4)]})) (defcard "<NAME>" (let [mg {:req (req (ice? target)) :effect (effect (update-all-subtypes))}] {:constant-effects [{:type :gain-subtype :req (req (same-card? card target)) :value (req (->> (vals (:servers corp)) (mapcat :ices) (filter #(and (rezzed? %) (not (same-card? card %)))) (mapcat :subtypes)))}] :subroutines [end-the-run] :events [{:event :rez :req (req (ice? (:card context))) :effect (effect (update-all-subtypes))} (assoc mg :event :card-moved) (assoc mg :event :derez) (assoc mg :event :ice-subtype-changed)]})) (defcard "<NAME>" {:on-rez take-bad-pub :subroutines [(tag-trace 1) (tag-trace 2) (tag-trace 3) end-the-run-if-tagged]}) (defcard "Najja 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Nebula" (space-ice trash-program-sub)) (defcard "Negotiator" {:subroutines [(gain-credits-sub 2) trash-program-sub] :runner-abilities [(break-sub [:credit 2] 1)]}) (defcard "Nerine 2.0" (let [sub {:label "Do 1 brain damage and Corp may draw 1 card" :async true :msg "do 1 brain damage" :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (continue-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 2 2)]})) (defcard "<NAME>" {:subroutines [(do-net-damage 3)]}) (defcard "<NAME>" (let [gain-sub {:req (req (and (= 1 (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current"))) :msg "make News Hound gain \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 1 end-the-run {:back true}))} lose-sub {:req (req (and (zero? (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current") (active? (:card context)))) :msg "make News Hound lose \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 0 nil))}] {:on-rez {:effect (req (when (pos? (count (concat (get-in @state [:corp :current]) (get-in @state [:runner :current])))) (reset-variable-subs state side card 1 end-the-run {:back true})))} :events [(assoc gain-sub :event :play-event) (assoc gain-sub :event :play-operation) (assoc lose-sub :event :corp-trash) (assoc lose-sub :event :runner-trash) (assoc lose-sub :event :game-trash)] :subroutines [(tag-trace 3)]})) (defcard "NEXT Bronze" {:subroutines [end-the-run] :strength-bonus (req (next-ice-count corp))}) (defcard "NEXT Diamond" {:rez-cost-bonus (req (- (next-ice-count corp))) :subroutines [(do-brain-damage 1) (do-brain-damage 1) {:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}]}) (defcard "NEXT Gold" (letfn [(trash-programs [cnt state side card eid] (if (> cnt 0) (wait-for (resolve-ability state side trash-program-sub card nil) (trash-programs (dec cnt) state side card eid)) (effect-completed state side eid)))] {:subroutines [{:label "Do 1 net damage for each rezzed NEXT ice" :msg (msg "do " (next-ice-count corp) " net damage") :effect (effect (damage eid :net (next-ice-count corp) {:card card}))} {:label "Trash 1 program for each rezzed NEXT ice" :async true :effect (req (trash-programs (min (count (filter program? (all-active-installed state :runner))) (next-ice-count corp)) state side card eid))}]})) (defcard "NEXT Opal" (let [sub {:label "Install a card from HQ, paying all costs" :prompt "Choose a card in HQ to install" :req (req (some #(not (operation? %)) (:hand corp))) :choices {:card #(and (not (operation? %)) (in-hand? %) (corp? %))} :async true :effect (effect (corp-install eid target nil nil)) :msg (msg (corp-install-msg target))} ability {:req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}] {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}]})) (defcard "NEXT Sapphire" {:subroutines [{:label "Draw up to X cards" :prompt "Draw how many cards?" :msg (msg "draw " target " cards") :choices {:number (req (next-ice-count corp)) :default (req 1)} :async true :effect (effect (draw eid target nil))} {:label "Add up to X cards from Archives to HQ" :prompt "Select cards to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state side c :hand))) :msg (msg "add " (let [seen (filter :seen targets) m (count (filter #(not (:seen %)) targets))] (str (string/join ", " (map :title seen)) (when (pos? m) (str (when-not (empty? seen) " and ") (quantify m "unseen card"))))) " to HQ")} {:label "Shuffle up to X cards from HQ into R&D" :prompt "Select cards to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck)) :cancel-effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle " (count targets) " cards from HQ into R&D")}]}) (defcard "NEXT Silver" {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))}]}) (defcard "Nightdancer" (let [sub {:label (str "The Runner loses [Click], if able. " "You have an additional [Click] to spend during your next turn.") :msg (str "force the runner to lose a [Click], if able. " "Corp gains an additional [Click] to spend during their next turn") :effect (req (lose state :runner :click 1) (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}] {:subroutines [sub sub]})) (defcard "Oduduwa" {:on-encounter {:msg "place 1 advancement counter on Oduduwa" :async true :effect (effect (add-prop card :advance-counter 1 {:placed true}) (continue-ability (let [card (get-card state card) counters (get-counters card :advancement)] {:optional {:prompt (str "Place " (quantify counters "advancement counter") " on another ice?") :yes-ability {:msg (msg "place " (quantify counters "advancement counter") " on " (card-str state target)) :choices {:card ice? :not-self true} :effect (effect (add-prop target :advance-counter counters {:placed true}))}}}) (get-card state card) nil))} :subroutines [end-the-run end-the-run]}) (defcard "<NAME>" (space-ice trash-program-sub (resolve-another-subroutine) end-the-run)) (defcard "<NAME>" {:subroutines [{:async true :label "Place 3 advancement tokens on installed card" :msg "place 3 advancement tokens on installed card" :prompt "Choose an installed Corp card" :req (req (some (complement ice?) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (ice? %)))} :effect (req (let [c target title (if (:rezzed c) (:title c) "selected unrezzed card")] (add-counter state side c :advancement 3) (continue-ability state side {:player :runner :async true :waiting-prompt "Runner to resolve Otoroshi" :prompt (str "Access " title " or pay 3 [Credits]?") :choices ["Access card" (when (>= (:credit runner) 3) "Pay 3 [Credits]")] :msg (msg "force the Runner to " (if (= target "Access card") (str "access " title) "pay 3 [Credits]")) :effect (req (if (= target "Access card") (access-card state :runner eid c) (wait-for (pay state :runner card :credit 3) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} card nil)))}]}) (defcard "<NAME>" {:subroutines [{:choices {:card #(and (installed? %) (program? %))} :label "Add installed program to the top of the Runner's Stack" :msg "add an installed program to the top of the Runner's Stack" :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Runner's Stack")))}]}) (defcard "Pachinko" {:subroutines [end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Paper Wall" {:events [{:event :subroutines-broken :req (req (and (same-card? card target) (empty? (remove :broken (:subroutines target))))) :async true :effect (effect (trash :corp eid card {:cause :effect}))}] :subroutines [end-the-run]}) (defcard "<NAME>" (let [sub (end-the-run-unless-runner "takes 1 tag" "take 1 tag" (give-tags 1))] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [n (count (filter #(is-type? % target) (:hand runner)))] (system-msg state side (str "uses Peeping Tom to name " target ", then reveals " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip. Peeping Tom gains " n " subroutines")) (wait-for (reveal state side (:hand runner)) (gain-variable-subs state side card n sub) (effect-completed state side eid))))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]})) (defcard "Pop-up Window" {:on-encounter (gain-credits-sub 1) :subroutines [(end-the-run-unless-runner-pays 1)]}) (defcard "Pup" (let [sub {:player :runner :async true :label (str "Do 1 net damage unless the Runner pays 1 [Credits]") :prompt (str "Suffer 1 net damage or pay 1 [Credits]?") :choices ["Suffer 1 net damage" "Pay 1 [Credits]"] :effect (req (if (= "Suffer 1 net damage" target) (continue-ability state :corp (do-net-damage 1) card nil) (wait-for (pay state :runner card [:credit 1]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))}] {:subroutines [sub sub]})) (defcard "Quandary" {:subroutines [end-the-run]}) (defcard "Quicksand" {:on-encounter {:msg "add 1 power counter to Quicksand" :effect (effect (add-counter card :power 1) (update-all-ice))} :subroutines [end-the-run] :strength-bonus (req (get-counters card :power))}) (defcard "Rainbow" {:subroutines [end-the-run]}) (defcard "Ravana 1.0" (let [sub (resolve-another-subroutine #(has-subtype? % "Bioroid") "Resolve a subroutine on a rezzed bioroid ice")] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Red Tape" {:subroutines [{:label "Give +3 strength to all ICE for the remainder of the run" :msg "give +3 strength to all ICE for the remainder of the run" :effect (effect (pump-all-ice 3 :end-of-run))}]}) (defcard "Resistor" {:strength-bonus (req (count-tags state)) :subroutines [(trace-ability 4 end-the-run)]}) (defcard "Rime" {:implementation "Can be rezzed anytime already" :on-rez {:effect (effect (update-all-ice))} :subroutines [{:label "Runner loses 1 [Credit]" :msg "force the Runner to lose 1 [Credit]" :async true :effect (effect (lose-credits :runner eid 1))}] :constant-effects [{:type :ice-strength :req (req (protecting-same-server? card target)) :value 1}]}) (defcard "Rototurret" {:subroutines [trash-program-sub end-the-run]}) (defcard "Sadaka" (let [maybe-draw-effect {:optional {:player :corp :waiting-prompt "Corp to decide on Sadaka card draw action" :prompt "Draw 1 card?" :yes-ability {:async true :effect (effect (draw eid 1 nil)) :msg "draw 1 card"}}}] {:subroutines [{:label "Look at the top 3 cards of R&D" :req (req (not-empty (:deck corp))) :async true :effect (effect (continue-ability (let [top-cards (take 3 (:deck corp)) top-names (map :title top-cards)] {:waiting-prompt "Corp to decide on Sadaka R&D card actions" :prompt (str "Top 3 cards of R&D: " (string/join ", " top-names)) :choices ["Arrange cards" "Shuffle R&D"] :async true :effect (req (if (= target "Arrange cards") (wait-for (resolve-ability state side (reorder-choice :corp top-cards) card nil) (system-msg state :corp (str "rearranges the top " (quantify (count top-cards) "card") " of R&D")) (continue-ability state side maybe-draw-effect card nil)) (do (shuffle! state :corp :deck) (system-msg state :corp (str "shuffles R&D")) (continue-ability state side maybe-draw-effect card nil))))}) card nil))} {:label "Trash 1 card in HQ" :async true :effect (req (wait-for (resolve-ability state side {:waiting-prompt "Corp to select cards to trash with Sadaka" :prompt "Choose a card in HQ to trash" :choices (req (cancellable (:hand corp) :sorted)) :async true :cancel-effect (effect (system-msg "chooses not to trash a card from HQ") (effect-completed eid)) :effect (req (wait-for (trash state :corp target {:cause :subroutine}) (system-msg state :corp "trashes a card from HQ") (continue-ability state side trash-resource-sub card nil)))} card nil) (when current-ice (continue state :corp nil) (continue state :runner nil)) (system-msg state :corp "trashes Sadaka") (trash state :corp eid card nil)))}]})) (defcard "Sagittarius" (constellation-ice trash-program-sub)) (defcard "Saisentan" (let [sub {:label "Do 1 net damage" :async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [choice (get-in card [:special :saisentan]) cards async-result dmg (some #(when (= (:type %) choice) %) cards)] (if dmg (do (system-msg state :corp "uses Saisentan to deal a second net damage") (damage state side eid :net 1 {:card card})) (effect-completed state side eid)))))}] {:on-encounter {:waiting-prompt "Corp to choose Saisentan card type" :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "choose the card type " target) :effect (effect (update! (assoc-in card [:special :saisentan] target)))} :events [{:event :end-of-encounter :req (req (get-in card [:special :saisentan])) :effect (effect (update! (dissoc-in card [:special :saisentan])))}] :subroutines [sub sub sub]})) (defcard "Salvage" (zero-to-hero (tag-trace 2))) (defcard "Sand Storm" {:subroutines [{:async true :label "Move Sand Storm and the run to another server" :prompt "Choose another server and redirect the run to its outermost position" :choices (req (remove #{(zone->name (:server (:run @state)))} (cancellable servers))) :msg (msg "move Sand Storm and the run. The Runner is now running on " target ". Sand Storm is trashed") :effect (effect (redirect-run target :approach-ice) (trash eid card {:unpreventable true :cause :subroutine}))}]}) (defcard "Sandstone" {:subroutines [end-the-run] :strength-bonus (req (- (get-counters card :virus))) :on-encounter {:msg "place 1 virus counter on Sandstone" :effect (effect (add-counter card :virus 1) (update-ice-strength (get-card state card)))}}) (defcard "Sandman" {:subroutines [add-runner-card-to-grip add-runner-card-to-grip]}) (defcard "Sapper" {:flags {:rd-reveal (req true)} :subroutines [trash-program-sub] :access {:async true :optional {:req (req (and (not (in-discard? card)) (some program? (all-active-installed state :runner)))) :player :runner :waiting-prompt "Runner to decide to break Sapper subroutine" :prompt "Allow Sapper subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "Searchlight" (let [sub {:label "Trace X - Give the Runner 1 tag" :trace {:base (req (get-counters card :advancement)) :label "Give the Runner 1 tag" :successful (give-tags 1)}}] {:advanceable :always :subroutines [sub sub]})) (defcard "Seidr Adaptive Barrier" {:strength-bonus (req (count (:ices (card->server state card)))) :subroutines [end-the-run]}) (defcard "Self-Adapting Code Wall" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Sensei" {:subroutines [{:label "Give encountered ice \"End the run\"" :msg (msg "give encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :req (req (not (same-card? card (:ice context)))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "Shadow" (wall-ice [(gain-credits-sub 2) (tag-trace 3)])) (defcard "Sherlock 1.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the top of the Runner's Stack" :msg (msg "add " (:title target) " to the top of the Runner's Stack") :effect (effect (move :runner target :deck {:front true}))})] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Sherlock 2.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the bottom of the Runner's Stack" :msg (msg "add " (:title target) " to the bottom of the Runner's Stack") :effect (effect (move :runner target :deck))})] {:subroutines [sub sub (give-tags 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Sh<NAME>" {:on-rez take-bad-pub :subroutines [(trace-ability 1 (do-net-damage 1)) (trace-ability 2 (do-net-damage 2)) (trace-ability 3 {:label "Do 3 net damage and end the run" :msg "do 3 net damage and end the run" :effect (req (wait-for (damage state side :net 3 {:card card}) (end-run state side eid card)))})]}) (defcard "<NAME>" {:subroutines [{:label "Rearrange the top 3 cards of R&D" :msg "rearrange the top 3 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (effect (continue-ability (let [from (take 3 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))} {:optional {:prompt "Pay 1 [Credits] to keep the Runner from accessing the top card of R&D?" :yes-ability {:cost [:credit 1] :msg "keep the Runner from accessing the top card of R&D"} :no-ability {:async true :msg "make the Runner access the top card of R&D" :effect (effect (do-access :runner eid [:rd] {:no-root true}))}}}]}) (defcard "Slot Machine" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (effect-type [card] (keyword (str "slot-machine-top-3-" (:cid card)))) (name-builder [card] (str (:title card) " (" (:type card) ")")) (top-3-names [cards] (map name-builder cards)) (top-3-types [state card et] (->> (get-effects state :corp card et) first (keep :type) (into #{}) count)) (ability [] {:label "Encounter ability (manual)" :async true :effect (req (move state :runner (first (:deck runner)) :deck) (let [t3 (top-3 state) effect-type (effect-type card)] (register-floating-effect state side card {:type effect-type :duration :end-of-encounter :value t3}) (system-msg state side (str "uses Slot Machine to put the top card of the stack to the bottom," " then reveal the top 3 cards in the stack: " (string/join ", " (top-3-names t3)))) (reveal state side eid t3)))})] {:on-encounter (ability) :abilities [(ability)] :subroutines [{:label "Runner loses 3 [Credits]" :msg "force the Runner to lose 3 [Credits]" :async true :effect (effect (lose-credits :runner eid 3))} {:label "Gain 3 [Credits]" :async true :effect (req (let [et (effect-type card) unique-types (top-3-types state card et)] ;; When there are 3 cards in the deck, sub needs 2 or fewer unique types ;; When there are 2 cards in the deck, sub needs 1 unique type (if (or (and (<= unique-types 2) (= 3 (count (first (get-effects state :corp card et))))) (and (= unique-types 1) (= 2 (count (first (get-effects state :corp card et)))))) (do (system-msg state :corp (str "uses Slot Machine to gain 3 [Credits]")) (gain-credits state :corp eid 3)) (effect-completed state side eid))))} {:label "Place 3 advancement tokens" :async true :effect (effect (continue-ability (let [et (effect-type card) unique-types (top-3-types state card et)] (when (and (= 3 (count (first (get-effects state :corp card et)))) (= 1 unique-types)) {:choices {:card installed?} :prompt "Choose an installed card" :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 3 {:placed true}))})) card nil))}]})) (defcard "Snoop" {:on-encounter {:msg (msg "reveal the Runner's Grip (" (string/join ", " (map :title (:hand runner))) ")") :async true :effect (effect (reveal eid (:hand runner)))} :abilities [{:async true :req (req (pos? (get-counters card :power))) :cost [:power 1] :label "Reveal all cards in Grip and trash 1 card" :msg (msg "look at all cards in Grip and trash " (:title target) " using 1 power counter") :choices (req (cancellable (:hand runner) :sorted)) :prompt "Choose a card to trash" :effect (effect (reveal (:hand runner)) (trash eid target {:cause :subroutine}))}] :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Snowflake" {:subroutines [(do-psi end-the-run)]}) (defcard "Special Offer" {:subroutines [{:label "Gain 5 [Credits] and trash Special Offer" :msg "gains 5 [Credits] and trashes Special Offer" :async true :effect (req (wait-for (gain-credits state :corp 5) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "Spiderweb" {:subroutines [end-the-run end-the-run end-the-run]}) (defcard "Surveyor" (let [x (req (* 2 (count (:ices (card->server state card)))))] {:strength-bonus x :subroutines [{:label "Trace X - Give the Runner 2 tags" :trace {:base x :label "Give the Runner 2 tags" :successful (give-tags 2)}} {:label "Trace X - End the run" :trace {:base x :label "End the run" :successful end-the-run}}]})) (defcard "<NAME>" {:subroutines [{:req (req (not= (:server run) [:discard])) :msg "make the Runner continue the run on Archives" :effect (req (redirect-run state side "Archives" :approach-ice) (register-events state side card [{:event :approach-ice :duration :end-of-run :unregister-once-resolved true :msg "prevent the runner from jacking out" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :effect (req (swap! state update :run dissoc :cannot-jack-out))}]))}]))}]}) (defcard "Swarm" (let [sub {:player :runner :async true :label "Trash a program" :prompt "Let Corp trash 1 program or pay 3 [Credits]?" :choices ["Corp trash" "Pay 3 [Credits]"] :effect (req (if (= "Corp trash" target) (continue-ability state :corp trash-program-sub card nil) (wait-for (pay state :runner card [:credit 3]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :always :on-rez take-bad-pub :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) (defcard "<NAME>" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [{:async true :breakable breakable-fn :prompt "Select an AI program to trash" :msg (msg "trash " (:title target)) :label "Trash an AI program" :choices {:card #(and (installed? %) (program? %) (has-subtype? % "AI"))} :effect (effect (trash eid target {:cause :subroutine}))} (assoc (do-net-damage 1) :breakable breakable-fn)]})) (defcard "SYNC BRE" {:subroutines [(tag-trace 4) (trace-ability 2 {:label "Runner reduces cards accessed by 1 for this run" :async true :msg "reduce cards accessed for this run by 1" :effect (effect (access-bonus :total -1))})]}) (defcard "Tapestry" {:subroutines [runner-loses-click {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} {:req (req (pos? (count (:hand corp)))) :prompt "Choose a card in HQ to move to the top of R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "add 1 card in HQ to the top of R&D" :effect (effect (move target :deck {:front true}))}]}) (defcard "Taurus" (constellation-ice trash-hardware-sub)) (defcard "Thimblerig" (let [ability {:optional {:req (req (and (<= 2 (count (filter ice? (all-installed state :corp)))) (if run (same-card? (:ice context) card) true))) :prompt "Swap Thimblerig with another ice?" :yes-ability {:prompt "Choose a piece of ice to swap Thimblerig with" :choices {:card ice? :not-self true} :effect (effect (swap-ice card target)) :msg (msg "swap " (card-str state card) " with " (card-str state target))}}}] {:events [(assoc ability :event :pass-ice) (assoc ability :event :corp-turn-begins)] :subroutines [end-the-run]})) (defcard "Thoth" {:on-encounter (give-tags 1) :subroutines [(trace-ability 4 {:label "Do 1 net damage for each Runner tag" :async true :msg (msg "do " (count-tags state) " net damage") :effect (effect (damage eid :net (count-tags state) {:card card}))}) (trace-ability 4 {:label "Runner loses 1 [Credits] for each tag" :async true :msg (msg "force the Runner to lose " (count-tags state) " [Credits]") :effect (effect (lose-credits :runner eid (count-tags state)))})]}) (defcard "Tithonium" {:alternative-cost [:forfeit] :cannot-host true :subroutines [trash-program-sub trash-program-sub {:label "Trash a resource and end the run" :async true :effect (req (wait-for (resolve-ability state side {:req (req (pos? (count (filter resource? (all-installed state :runner))))) :async true :choices {:all true :card #(and (installed? %) (resource? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (complete-with-result state side eid target)))} card nil) (system-msg state side (str "uses Tithonium to " (if async-result (str "trash " (:title async-result) " and ends the run") "end the run"))) (end-run state side eid card)))}]}) (defcard "TL;DR" {:subroutines [{:label "Double subroutines on an ICE" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "duplicate each subroutine on " (:title (:ice context))) :effect (req (let [curr-subs (map #(assoc % :from-cid (:cid (:ice context))) (:subroutines (:ice context))) tldr-subs (map #(assoc % :from-cid (:cid card)) curr-subs) new-subs (->> (interleave curr-subs tldr-subs) (reduce (fn [ice sub] (add-sub ice sub (:from-cid sub) nil)) (assoc (:ice context) :subroutines [])) :subroutines (into [])) new-card (assoc (:ice context) :subroutines new-subs)] (update! state :corp new-card) (register-events state side card (let [cid (:cid card)] [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :req (req (get-card state new-card)) :effect (effect (remove-subs! (get-card state new-card) #(= cid (:from-cid %))))}]))))}]))}]}) (defcard "TMI" {:on-rez {:trace {:base 2 :msg "keep TMI rezzed" :label "Keep TMI rezzed" :unsuccessful {:effect (effect (derez card))}}} :subroutines [end-the-run]}) (defcard "Tollbooth" {:on-encounter {:async true :effect (req (wait-for (pay state :runner card [:credit 3]) (if (:cost-paid async-result) (do (system-msg state :runner (str (:msg async-result) " when encountering Tollbooth")) (effect-completed state side eid)) (do (system-msg state :runner "ends the run, as the Runner can't pay 3 [Credits] when encountering Tollbooth") (end-run state :corp eid card)))))} :subroutines [end-the-run]}) (defcard "Tour Guide" (let [ef (effect (reset-variable-subs card (count (filter asset? (all-active-installed state :corp))) end-the-run)) ability {:label "Reset number of subs" :silent (req true) :req (req (asset? target)) :effect ef} trash-req (req (and (asset? (:card target)) (installed? (:card target)) (rezzed? (:card target))))] {:on-rez {:effect ef} :events [{:event :rez :label "Reset number of subs" :silent (req true) :req (req (asset? (:card context))) :effect ef} (assoc ability :event :derez) (assoc ability :event :game-trash :req trash-req) (assoc ability :event :corp-trash :req trash-req) (assoc ability :event :runner-trash :req trash-req)]})) (defcard "Trebuchet" {:on-rez take-bad-pub :subroutines [{:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (req (trash state side eid target {:cause :subroutine}))} (trace-ability 6 {:label "The Runner cannot steal or trash Corp cards for the remainder of this run" :msg "prevent the Runner from stealing or trashing Corp cards for the remainder of the run" :effect (req (register-run-flag! state side card :can-steal (fn [state side card] ((constantly false) (toast state :runner "Cannot steal due to Trebuchet." "warning")))) (register-run-flag! state side card :can-trash (fn [state side card] ((constantly (not= (:side card) "Corp")) (toast state :runner "Cannot trash due to Trebuchet." "warning")))))})]}) (defcard "Tribunal" {:subroutines [runner-trash-installed-sub runner-trash-installed-sub runner-trash-installed-sub]}) (defcard "Troll" {:on-encounter (trace-ability 2 {:msg "force the Runner to lose [Click] or end the run" :player :runner :prompt "Choose one" :choices ["Lose [Click]" "End the run"] :async true :effect (req (if (and (= target "Lose [Click]") (can-pay? state :runner (assoc eid :source card :source-type :subroutine) card nil [:click 1])) (do (system-msg state :runner "loses [Click]") (lose state :runner :click 1) (effect-completed state :runner eid)) (do (system-msg state :corp "ends the run") (end-run state :corp eid card))))})}) (defcard "<NAME>" {:subroutines [(end-the-run-unless-corp-pays 1) (do-net-damage 1) (do-net-damage 1) (do-net-damage 1)]}) (defcard "<NAME>" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [(assoc (end-the-run-unless-runner "spends [Click][Click][Click]" "spend [Click][Click][Click]" (runner-pays [:click 3])) :breakable breakable-fn)] :strength-bonus (req (if (is-remote? (second (get-zone card))) 3 0))})) (defcard "<NAME>pi<NAME>" {:on-encounter {:msg "force the Runner to lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} :subroutines [(tag-trace 5)]}) (defcard "<NAME>" (zero-to-hero end-the-run)) (defcard "<NAME>" {:subroutines [(do-brain-damage 2) (combine-abilities trash-installed-sub (gain-credits-sub 3)) end-the-run] :runner-abilities [(bioroid-break 1 1 {:additional-ability {:effect (req (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}})]}) (defcard "Universal Connectivity Fee" {:subroutines [{:label "Force the Runner to lose credits" :msg (msg "force the Runner to lose " (if tagged "all credits" "1 [Credits]")) :async true :effect (req (if tagged (wait-for (lose-credits state :runner :all) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})) (lose-credits state :runner eid 1)))}]}) (defcard "Upayoga" {:subroutines [(do-psi {:label "Make the Runner lose 2 [Credits]" :msg "make the Runner lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))}) (resolve-another-subroutine #(has-subtype? % "Psi") "Resolve a subroutine on a rezzed psi ice")]}) (defcard "Uroboros" {:subroutines [(trace-ability 4 {:label "Prevent the Runner from making another run" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}) (trace-ability 4 end-the-run)]}) (defcard "Vanilla" {:subroutines [end-the-run]}) (defcard "Veritas" {:subroutines [{:label "Corp gains 2 [Credits]" :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :corp eid 2))} {:label "Runner loses 2 [Credits]" :msg "force the Runner to lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))} (trace-ability 2 (give-tags 1))]}) (defcard "Vikram 1.0" {:implementation "Program prevention is not implemented" :subroutines [{:msg "prevent the Runner from using programs for the remainder of this run"} (trace-ability 4 (do-brain-damage 1)) (trace-ability 4 (do-brain-damage 1))] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 1.0" {:subroutines [(do-brain-damage 1) end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 2.0" {:abilities [(power-counter-ability (do-brain-damage 1))] :subroutines [(trace-ability 2 add-power-counter) end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Viper" {:subroutines [(trace-ability 3 runner-loses-click) (trace-ability 3 end-the-run)]}) (defcard "<NAME>irgo" (constellation-ice (give-tags 1))) (defcard "Waiver" {:subroutines [(trace-ability 5 {:label "Reveal the grip and trash cards" :msg (msg "reveal all cards in the grip: " (string/join ", " (map :title (:hand runner)))) :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [delta (- target (second targets)) cards (filter #(<= (:cost %) delta) (:hand runner))] (system-msg state side (str "uses Waiver to trash " (string/join ", " (map :title cards)))) (trash-cards state side eid cards {:cause :subroutine}))))})]}) (defcard "Wall of Static" {:subroutines [end-the-run]}) (defcard "Wall of Thorns" {:subroutines [(do-net-damage 2) end-the-run]}) (defcard "Watchtower" {:subroutines [{:label "Search R&D and add 1 card to HQ" :prompt "Choose a card to add to HQ" :msg "add a card from R&D to HQ" :choices (req (cancellable (:deck corp) :sorted)) :cancel-effect (effect (system-msg "cancels the effect of Watchtower")) :effect (effect (shuffle! :deck) (move target :hand))}]}) (defcard "Weir" {:subroutines [runner-loses-click {:label "Runner trashes 1 card from their Grip" :req (req (pos? (count (:hand runner)))) :prompt "Choose a card to trash from your Grip" :player :runner :choices (req (:hand runner)) :not-distinct true :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " from their Grip")) (trash :runner eid target {:cause :subroutine}))}]}) (defcard "Wendigo" (implementation-note "Program prevention is not implemented" (morph-ice "Code Gate" "Barrier" {:msg "prevent the Runner from using a chosen program for the remainder of this run"}))) (defcard "Whirlpool" {:subroutines [{:label "The Runner cannot jack out for the remainder of this run" :msg "prevent the Runner from jacking out" :async true :effect (req (prevent-jack-out state side) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine}))}]}) (defcard "Winchester" (let [ab {:req (req (protecting-hq? card)) :effect (req (reset-variable-subs state :corp card 1 (trace-ability 3 end-the-run) {:back true}))}] {:subroutines [(trace-ability 4 trash-program-sub) (trace-ability 3 trash-hardware-sub)] :on-rez {:effect (effect (continue-ability ab card nil))} :events [(assoc ab :event :rez) (assoc ab :event :card-moved) (assoc ab :event :approach-ice) (assoc ab :event :swap :req (req (or (protecting-hq? target) (protecting-hq? (second targets)))))]})) (defcard "Woodcutter" (zero-to-hero (do-net-damage 1))) (defcard "Wormhole" (space-ice (resolve-another-subroutine))) (defcard "Wotan" {:subroutines [(end-the-run-unless-runner "spends [Click][Click]" "spend [Click][Click]" (runner-pays [:click 2])) (end-the-run-unless-runner-pays 3) (end-the-run-unless-runner "trashes an installed program" "trash an installed program" trash-program-sub) (end-the-run-unless-runner "takes 1 brain damage" "take 1 brain damage" (do-brain-damage 1))]}) (defcard "Wraparound" {:subroutines [end-the-run] :strength-bonus (req (if (some #(has-subtype? % "Fracter") (all-active-installed state :runner)) 0 7))}) (defcard "Yagura" {:subroutines [{:msg "look at the top card of R&D" :optional {:prompt (msg "Move " (:title (first (:deck corp))) " to the bottom of R&D?") :yes-ability {:msg "move the top card of R&D to the bottom" :effect (effect (move (first (:deck corp)) :deck))} :no-ability {:effect (effect (system-msg :corp (str "does not use Yagura to move the top card of R&D to the bottom")))}}} (do-net-damage 1)]}) (defcard "Zed 1.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [(do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Zed 2.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [trash-hardware-sub trash-hardware-sub (do-brain-damage 2)] :runner-abilities [(bioroid-break 2 2)]})
true
(ns game.cards.ice (:require [game.core :refer :all] [game.utils :refer :all] [jinteki.utils :refer :all] [clojure.string :as string])) ;;;; Helper functions specific for ICE (defn reset-variable-subs ([state side card total sub] (reset-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) old-subs (remove #(and (= (:cid card) (:from-cid %)) (:variable %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines (into [])) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn gain-variable-subs ([state side card total sub] (gain-variable-subs state side card total sub nil)) ([state side card total sub args] (let [args (merge {:variable true} args) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) card) :subroutines (into [])) new-card (assoc card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) (defn reset-printed-subs ([state side card total sub] (reset-printed-subs state side card total sub {:printed true})) ([state side card total sub args] (let [old-subs (remove #(and (= (:cid card) (:from-cid %)) (:printed %)) (:subroutines card)) new-card (assoc card :subroutines old-subs) new-subs (->> (range total) (reduce (fn [ice _] (add-sub ice sub (:cid ice) args)) new-card) :subroutines) new-card (assoc new-card :subroutines new-subs)] (update! state :corp new-card) (trigger-event state side :subroutines-changed (get-card state new-card))))) ;;; Runner abilites for breaking subs (defn bioroid-break ([cost qty] (bioroid-break cost qty nil)) ([cost qty args] (break-sub [:lose-click cost] qty nil args))) ;;; General subroutines (def end-the-run "Basic ETR subroutine" {:label "End the run" :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (def end-the-run-if-tagged "ETR subroutine if tagged" {:label "End the run if the Runner is tagged" :req (req tagged) :msg "end the run" :async true :effect (effect (end-run :corp eid card))}) (defn runner-pays "Ability to pay to avoid a subroutine by paying a resource" [cost] {:async true :effect (req (wait-for (pay state :runner card cost) (when-let [payment-str (:msg async-result)] (system-msg state :runner (str payment-str " due to " (:title card) " subroutine"))) (effect-completed state side eid)))}) (defn end-the-run-unless-runner-pays [amount] {:player :runner :async true :label (str "End the run unless the Runner pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side (runner-pays [:credit amount]) card nil)))}) (defn end-the-run-unless-corp-pays [amount] {:async true :label (str "End the run unless the Corp pays " amount " [Credits]") :prompt (str "End the run or pay " amount " [Credits]?") :choices ["End the run" (str "Pay " amount " [Credits]")] :effect (req (if (= "End the run" target) (end-run state :corp eid card) (wait-for (pay state :corp card [:credit amount]) (when-let [payment-str (:msg async-result)] (system-msg state :corp payment-str)) (effect-completed state side eid))))}) (defn end-the-run-unless-runner [label prompt ability] {:player :runner :async true :label (str "End the run unless the Runner " label) :prompt (str "End the run or " prompt "?") :choices ["End the run" (capitalize prompt)] :effect (req (if (= "End the run" target) (do (system-msg state :corp (str "uses " (:title card) " to end the run")) (end-run state :corp eid card)) (continue-ability state side ability card nil)))}) (defn give-tags "Basic give runner n tags subroutine." [n] {:label (str "Give the Runner " (quantify n "tag")) :msg (str "give the Runner " (quantify n "tag")) :async true :effect (effect (gain-tags :corp eid n))}) (def add-power-counter "Adds 1 power counter to the card." {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1))}) (defn trace-ability "Run a trace with specified base strength. If successful trigger specified ability" ([base {:keys [label] :as ability}] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability}}) ([base ability un-ability] (let [label (str (:label ability) " / " (:label un-ability))] {:label (str "Trace " base " - " label) :trace {:base base :label label :successful ability :unsuccessful un-ability}}))) (defn tag-trace "Trace ability for giving a tag, at specified base strength" ([base] (tag-trace base 1)) ([base n] (trace-ability base (give-tags n)))) (defn gain-credits-sub "Gain specified amount of credits" [credits] {:label (str "Gain " credits " [Credits]") :msg (str "gain " credits " [Credits]") :async true :effect (effect (gain-credits eid credits))}) (defn power-counter-ability "Does specified ability using a power counter." [{:keys [label message] :as ability}] (assoc ability :label label :msg message :cost [:power 1])) (defn do-psi "Start a psi game, if not equal do ability" ([{:keys [label] :as ability}] {:label (str "Psi Game - " label) :msg (str "start a psi game (" label ")") :psi {:not-equal ability}}) ([{:keys [label-neq] :as neq-ability} {:keys [label-eq] :as eq-ability}] {:label (str "Psi Game - " label-neq " / " label-eq) :msg (str "start a psi game (" label-neq " / " label-eq ")") :psi {:not-equal neq-ability :equal eq-ability}})) (def runner-loses-click ; Runner loses a click effect {:label "Force the Runner to lose 1 [Click]" :msg "force the Runner to lose 1 [Click] if able" :effect (effect (lose :runner :click 1))}) (def add-runner-card-to-grip "Add 1 installed Runner card to the grip" {:label "Add an installed Runner card to the grip" :req (req (not-empty (all-installed state :runner))) :waiting-prompt "Corp to select a target" :prompt "Choose a card" :choices {:card #(and (installed? %) (runner? %))} :msg "add 1 installed card to the Runner's Grip" :effect (effect (move :runner target :hand true) (system-msg (str "adds " (:title target) " to the Runner's Grip")))}) (def trash-program-sub {:prompt "Select a program to trash" :label "Trash a program" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-hardware-sub {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (hardware? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-resource-sub {:prompt "Select a resource to trash" :label "Trash a resource" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}) (def trash-installed-sub {:async true :prompt "Select an installed card to trash" :label "Trash an installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :effect (effect (trash eid target {:cause :subroutine}))}) (def runner-trash-installed-sub (assoc trash-installed-sub :player :runner :label "Force the Runner to trash an installed card" :msg (msg "force the Runner to trash " (:title target)))) ;;; For Advanceable ICE (defn wall-ice [subroutines] {:advanceable :always :subroutines subroutines :strength-bonus (req (get-counters card :advancement))}) (defn space-ice "Creates data for Space ICE with specified abilities." [& abilities] {:advanceable :always :subroutines (vec abilities) :rez-cost-bonus (req (* -3 (get-counters card :advancement)))}) ;;; For Grail ICE (defn grail-in-hand "Req that specified card is a Grail card in the Corp's hand." [card] (and (corp? card) (in-hand? card) (has-subtype? card "Grail"))) (def reveal-grail "Ability for revealing Grail ICE from HQ." {:label "Reveal up to 2 Grail ICE from HQ" :choices {:max 2 :card grail-in-hand} :async true :effect (effect (reveal eid targets)) :msg (let [sub-label #(:label (first (:subroutines (card-def %))))] (msg "reveal " (string/join ", " (map #(str (:title %) " (" (sub-label %) ")") targets))))}) (def resolve-grail "Ability for resolving a subroutine on a Grail ICE in HQ." {:label "Resolve a Grail ICE subroutine from HQ" :choices {:card grail-in-hand} :effect (req (doseq [ice targets] (let [subroutine (first (:subroutines (card-def ice)))] (resolve-ability state side subroutine card nil))))}) (defn grail-ice "Creates data for grail ICE" [ability] {:abilities [reveal-grail] :subroutines [ability resolve-grail]}) ;;; For NEXT ICE (defn next-ice-count "Counts number of rezzed NEXT ICE - for use with NEXT Bronze and NEXT Gold" [corp] (let [servers (flatten (seq (:servers corp))) rezzed-next? #(and (rezzed? %) (has-subtype? % "NEXT"))] (reduce (fn [c server] (+ c (count (filter rezzed-next? (:ices server))))) 0 servers))) ;;; For Morph ICE (defn morph-ice "Creates the data for morph ICE with specified types and ability." [base other ability] {:advanceable :always :constant-effects [{:type :lose-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value base} {:type :gain-subtype :req (req (and (same-card? card target) (odd? (get-counters (get-card state card) :advancement)))) :value other}] :subroutines [ability]}) ;;; For Constellation ICE (defn constellation-ice "Generates map for Constellation ICE with specified effect." [ability] {:subroutines [(-> (trace-ability 2 ability) (assoc-in [:trace :kicker] ability) (assoc-in [:trace :kicker-min] 5))]}) ;; For advance-only-while-rezzed, sub-growing ICE (defn zero-to-hero "Salvage, Tyrant, Woodcutter" [sub] (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :while-rezzed :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) ;; For 7 Wonders ICE (defn wonder-sub "Checks total number of advancement counters on a piece of ice against number" [card number] (<= number (get-counters card :advancement))) (defn resolve-another-subroutine "For cards like Orion or Upayoga." ([] (resolve-another-subroutine (constantly true) "Resolve a subroutine on another ice")) ([pred] (resolve-another-subroutine pred "Resolve a subroutine on another ice")) ([pred label] (let [pred #(and (ice? %) (rezzed? %) (pred %))] {:async true :label label :effect (effect (continue-ability (when (< 1 (count (filter pred (all-active-installed state :corp)))) {:async true :prompt "Select the ice" :choices {:card pred :all true} :effect (effect (continue-ability (let [ice target] {:async true :prompt "Select the subroutine" :choices (req (unbroken-subroutines-choice ice)) :msg (msg "resolve the subroutine (\"[subroutine] " target "\") from " (:title ice)) :effect (req (let [sub (first (filter #(= target (make-label (:sub-effect %))) (:subroutines ice)))] (continue-ability state side (:sub-effect sub) ice nil)))}) card nil))}) card nil))}))) ;;; Helper function for adding implementation notes to ICE defined with functions (defn- implementation-note "Adds an implementation note to the ice-definition" [note ice-def] (assoc ice-def :implementation note)) (def take-bad-pub ; Bad pub on rez effect {:async true :effect (effect (system-msg (str "takes 1 bad publicity from " (:title card))) (gain-bad-publicity :corp eid 1))}) ;; Card definitions (defcard "PI:NAME:<NAME>END_PI" (let [breakable-fn (req (if (= :hq (second (get-zone card))) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:subroutines [{:msg "make the Runner lose 2 [Credits]" :breakable breakable-fn :async true :effect (effect (lose-credits :runner eid 2))} (assoc end-the-run :breakable breakable-fn)]})) (defcard "PI:NAME:<NAME>END_PIiki" {:subroutines [(do-psi {:label "Runner draws 2 cards" :msg "make the Runner draw 2 cards" :async true :effect (effect (draw :runner eid 2 nil))}) (do-net-damage 1) (do-net-damage 1)]}) (defcard "Aimor" {:subroutines [{:async true :label "Trash the top 3 cards of the Stack. Trash Aimor." :effect (req (system-msg state :corp (str "uses Aimor to trash " (string/join ", " (map :title (take 3 (:deck runner)))) " from the Runner's Stack")) (wait-for (mill state :corp :runner 3) (system-msg state side (str "trashes Aimor")) (trash state side eid card {:cause :subroutine})))}]}) (defcard "PI:NAME:<NAME>END_PI" (let [breakable-fn (req (if (<= 3 (get-counters card :advancement)) (empty? (filter #(and (:broken %) (:printed %)) (:subroutines card))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1[Credit]. Place 1 advancement token." :breakable breakable-fn :msg (msg "gain 1 [Credit] and place 1 advancement token on " (card-str state target)) :prompt "Choose an installed card" :choices {:card installed?} :async true :effect (effect (add-prop target :advance-counter 1 {:placed true}) (gain-credits eid 1))} (assoc end-the-run :breakable breakable-fn)] :strength-bonus (req (if (<= 3 (get-counters card :advancement)) 3 0))})) (defcard "PI:NAME:<NAME>END_PI" (let [corp-draw {:optional {:waiting-prompt "Corp to draw a card" :prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} runner-draw {:player :runner :optional {:waiting-prompt "Runner to decide on card draw" :prompt "Pay 2 [Credits] to draw 1 card?" :yes-ability {:async true :effect (req (wait-for (pay state :runner card [:credit 2]) (if (:cost-paid async-result) (do (system-msg state :runner "pays 2 [Credits] to draw 1 card") (draw state :runner eid 1 nil)) (do (system-msg state :runner "does not draw 1 card") (effect-completed state side eid)))))} :no-ability {:effect (effect (system-msg :runner "does not draw 1 card"))}}}] {:subroutines [{:msg "rearrange the top 5 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (req (let [from (take 5 (:deck corp))] (continue-ability state side (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from)) card nil)))} {:label "Draw 1 card, runner draws 1 card" :async true :effect (req (wait-for (resolve-ability state side corp-draw card nil) (continue-ability state :runner runner-draw card nil)))} (do-net-damage 1)] :events [(assoc (do-net-damage 3) :event :end-of-encounter :req (req (and (= (:ice context) card) (seq (remove :broken (:subroutines (:ice context)))))))]})) (defcard "Archangel" {:flags {:rd-reveal (req true)} :access {:optional {:req (req (not (in-discard? card))) :waiting-prompt "Corp to decide to trigger Archangel" :prompt "Pay 3 [Credits] to force Runner to encounter Archangel?" :player :corp :yes-ability {:cost [:credit 3] :async true :msg "force the Runner to encounter Archangel" :effect (effect (continue-ability :runner {:optional {:player :runner :prompt "You are encountering Archangel. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! eid card))}}} card nil))} :no-ability {:effect (effect (system-msg :corp "declines to force the Runner to encounter Archangel"))}}} :subroutines [(trace-ability 6 add-runner-card-to-grip)]}) (defcard "PI:NAME:<NAME>END_PIer" {:additional-cost [:forfeit] :subroutines [(gain-credits-sub 2) trash-program-sub trash-program-sub end-the-run]}) (defcard "PI:NAME:<NAME>END_PIitect" {:flags {:untrashable-while-rezzed true} :subroutines [{:label "Look at the top 5 cards of R&D" :prompt "Choose a card to install" :async true :activatemsg "uses Architect to look at the top 5 cards of R&D" :req (req (and (not (string? target)) (not (operation? target)))) :not-distinct true :choices (req (conj (take 5 (:deck corp)) "No install")) :effect (effect (system-msg (str "chooses the card in position " (+ 1 (.indexOf (take 5 (:deck corp)) target)) " from R&D (top is 1)")) (corp-install eid target nil {:ignore-all-cost true}))} {:label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :async true :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}]}) (defcard "Ashigaru" {:on-rez {:effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (corp? target) (or (in-hand? target) (= :hand (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (count (:hand corp)) end-the-run))}]}) (defcard "Assassin" {:subroutines [(trace-ability 5 (do-net-damage 3)) (trace-ability 4 trash-program-sub)]}) (defcard "Asteroid Belt" (space-ice end-the-run)) (defcard "Authenticator" {:on-encounter {:optional {:req (req (not (:bypass run))) :player :runner :prompt "Take 1 tag to bypass?" :yes-ability {:async true :effect (req (system-msg state :runner "takes 1 tag on encountering Authenticator to bypass it") (bypass-ice state) (gain-tags state :runner eid 1 {:unpreventable true}))}}} :subroutines [(gain-credits-sub 2) end-the-run]}) (defcard "Bailiff" {:implementation "Gain credit is manual" :abilities [(gain-credits-sub 1)] :subroutines [end-the-run]}) (defcard "Bandwidth" {:subroutines [{:msg "give the Runner 1 tag" :async true :effect (req (wait-for (gain-tags state :corp 1) (register-events state side card [{:event :successful-run :duration :end-of-run :unregister-once-resolved true :async true :msg "make the Runner lose 1 tag" :effect (effect (lose-tags :corp eid 1))}]) (effect-completed state side eid)))}]}) (defcard "Bastion" {:subroutines [end-the-run]}) (defcard "Battlement" {:subroutines [end-the-run end-the-run]}) (defcard "Blockchain" (let [sub-count (fn [corp] (quot (count (filter #(and (operation? %) (has-subtype? % "Transaction") (faceup? %)) (:discard corp))) 2)) sub {:label "Gain 1 [Credits], Runner loses 1 [Credits]" :msg "gain 1 [Credits] and force the Runner to lose 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 1) (lose-credits state :runner eid 1)))}] {:on-rez {:effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))} :events [{:event :card-moved :req (req (let [target (nth targets 1)] (and (operation? target) (has-subtype? target "Transaction") (or (in-discard? target) (= :discard (first (:previous-zone target))))))) :effect (effect (reset-variable-subs card (sub-count corp) sub {:variable true :front true}))}] :subroutines [sub end-the-run]})) (defcard "Bloodletter" {:subroutines [{:async true :label "Runner trashes 1 program or top 2 cards of their Stack" :effect (req (if (empty? (filter program? (all-active-installed state :runner))) (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner {:waiting-prompt "Runner to choose an option for Bloodletter" :prompt "Trash 1 program or trash top 2 cards of the Stack?" :choices (req [(when (seq (filter program? (all-active-installed state :runner))) "Trash 1 program") (when (<= 1 (count (:deck runner))) "Trash top 2 of Stack")]) :async true :effect (req (if (= target "Trash top 2 of Stack") (do (system-msg state :runner "trashes the top 2 cards of their Stack") (mill state :runner eid :runner 2)) (continue-ability state :runner trash-program-sub card nil)))} card nil)))}]}) (defcard "Bloom" {:subroutines [{:label "Install a piece of ice from HQ protecting another server, ignoring all costs" :prompt "Choose ICE to install from HQ in another server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (let [this (zone->name (second (get-zone card))) nice target] (continue-ability state side {:prompt (str "Choose a location to install " (:title target)) :choices (req (remove #(= this %) (corp-install-list state nice))) :async true :effect (effect (corp-install eid nice target {:ignore-all-cost true}))} card nil)))} {:label "Install a piece of ice from HQ in the next innermost position, protecting this server, ignoring all costs" :prompt "Choose ICE to install from HQ in this server" :async true :choices {:card #(and (ice? %) (in-hand? %))} :effect (req (corp-install state side eid target (zone->name (target-server run)) {:ignore-all-cost true :index (max (dec run-position) 0)}) (swap! state update-in [:run :position] inc))}]}) (defcard "Border Control" {:abilities [{:label "End the run" :msg (msg "end the run") :async true :cost [:trash] :effect (effect (end-run eid card))}] :subroutines [{:label "Gain 1 [Credits] for each ice protecting this server" :msg (msg "gain " (count (:ices (card->server state card))) " [Credits]") :async true :effect (req (let [num-ice (count (:ices (card->server state card)))] (gain-credits state :corp eid num-ice)))} end-the-run]}) (defcard "Brainstorm" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-brain-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "Builder" (let [sub {:label "Place 1 advancement token on an ICE that can be advanced protecting this server" :msg (msg "place 1 advancement token on " (card-str state target)) :choices {:card #(and (ice? %) (can-be-advanced? %))} :effect (effect (add-prop target :advance-counter 1 {:placed true}))}] {:abilities [{:label "Move Builder to the outermost position of any server" :cost [:click 1] :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)))}] :subroutines [sub sub]})) (defcard "Bullfrog" {:subroutines [(do-psi {:label "Move Bullfrog to another server" :player :corp :prompt "Choose a server" :choices (req servers) :msg (msg "move it to the outermost position of " target) :effect (effect (move card (conj (server->zone state target) :ices)) (redirect-run target) (effect-completed eid))})]}) (defcard "Bulwark" (let [sub {:msg "gain 2 [Credits] and end the run" :async true :effect (req (wait-for (gain-credits state side 2) (end-run state side eid card)))}] {:on-rez take-bad-pub :on-encounter {:req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg "gain 2 [Credits] if there is an installed AI" :async true :effect (effect (gain-credits eid 2))} :subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") sub sub]})) (defcard "Burke Bugs" {:subroutines [(trace-ability 0 (assoc trash-program-sub :not-distinct true :player :runner :msg "force the Runner to trash a program" :label "Force the Runner to trash a program"))]}) (defcard "Caduceus" {:subroutines [(trace-ability 3 (gain-credits-sub 3)) (trace-ability 2 end-the-run)]}) (defcard "Cell Portal" {:subroutines [{:msg "make the Runner approach the outermost ICE" :effect (req (let [server (zone->name (target-server run))] (redirect-run state side server :approach-ice) (derez state side card)))}]}) (defcard "Changeling" (morph-ice "Barrier" "Sentry" end-the-run)) (defcard "Checkpoint" {:on-rez take-bad-pub :subroutines [(trace-ability 5 {:label "Do 3 meat damage when this run is successful" :msg "do 3 meat damage when this run is successful" :effect (effect (register-events card [{:event :run-ends :duration :end-of-run :async true :req (req (:successful target)) :msg "do 3 meat damage" :effect (effect (damage eid :meat 3 {:card card}))}]))})]}) (defcard "Chetana" {:subroutines [{:msg "make each player gain 2 [Credits]" :async true :effect (req (wait-for (gain-credits state :runner 2) (gain-credits state :corp eid 2)))} (do-psi {:label "Do 1 net damage for each card in the Runner's grip" :msg (msg "do " (count (get-in @state [:runner :hand])) " net damage") :effect (effect (damage eid :net (count (get-in @state [:runner :hand])) {:card card}))})]}) (defcard "Chimera" {:on-rez {:prompt "Choose one subtype" :choices ["Barrier" "Code Gate" "Sentry"] :msg (msg "make it gain " target) :effect (effect (update! (assoc card :subtype-target target)))} :constant-effects [{:type :gain-subtype :req (req (and (same-card? card target) (:subtype-target card))) :value (req (:subtype-target card))}] :events [{:event :runner-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))} {:event :corp-turn-ends :req (req (rezzed? card)) :effect (effect (derez :corp card))}] :subroutines [end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" {:implementation "Trash effect when using an AI to break is activated manually" :abilities [{:async true :label "Trash the top 2 cards of the Runner's Stack" :req (req (some #(has-subtype? % "AI") (all-active-installed state :runner))) :msg (msg (str "trash " (string/join ", " (map :title (take 2 (:deck runner)))) " from the Runner's Stack")) :effect (effect (mill :corp eid :runner 2))}] :subroutines [(do-net-damage 2) (do-net-damage 2) end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" {:flags {:rd-reveal (req true)} :subroutines [(do-net-damage 2)] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Chrysalis subroutine" :prompt "You are encountering PI:NAME:<NAME>END_PI. Allow its subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Give +2 strength to next ICE Runner encounters" :req (req this-server) :msg (msg "give +2 strength to the next ICE the Runner encounters") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [target-ice (:ice context)] (register-floating-effect state side card {:type :ice-strength :duration :end-of-encounter :value 2 :req (req (same-card? target target-ice))}) (register-events state side card [(assoc (do-net-damage 3) :event :end-of-encounter :duration :end-of-run :unregister-once-resolved true :req (req (and (same-card? (:ice context) target-ice) (seq (remove :broken (:subroutines (:ice context)))))))])))}]))}]}) (defcard "Clairvoyant Monitor" {:subroutines [(do-psi {:label "Place 1 advancement token and end the run" :player :corp :prompt "Select a target for Clairvoyant Monitor" :msg (msg "place 1 advancement token on " (card-str state target) " and end the run") :choices {:card installed?} :effect (effect (add-prop target :advance-counter 1 {:placed true}) (end-run eid card))})]}) (defcard "Cobra" {:subroutines [trash-program-sub (do-net-damage 2)]}) (defcard "Colossus" (wall-ice [{:label "Give the Runner 1 tag (Give the Runner 2 tags)" :async true :msg (msg "give the Runner " (if (wonder-sub card 3) "2 tags" "1 tag")) :effect (effect (gain-tags :corp eid (if (wonder-sub card 3) 2 1)))} {:label "Trash 1 program (Trash 1 program and 1 resource)" :async true :msg (msg "trash 1 program" (when (wonder-sub card 3) " and 1 resource")) :effect (req (wait-for (resolve-ability state side trash-program-sub card nil) (if (wonder-sub card 3) (continue-ability state side {:prompt "Choose a resource to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (resource? %))} :cancel-effect (req (effect-completed state side eid)) :async true :effect (effect (trash eid target {:cause :subroutine}))} card nil) (effect-completed state side eid))))}])) (defcard "Congratulations!" {:events [{:event :pass-ice :req (req (same-card? (:ice context) card)) :msg "gain 1 [Credits]" :async true :effect (effect (gain-credits :corp eid 1))}] :subroutines [{:label "Gain 2 [Credits]. The Runner gains 1 [Credits]" :msg "gain 2 [Credits]. The Runner gains 1 [Credits]" :async true :effect (req (wait-for (gain-credits state :corp 2) (gain-credits state :runner eid 1)))}]}) (defcard "Conundrum" {:subroutines [(assoc trash-program-sub :player :runner :msg "force the Runner to trash 1 program" :label "The Runner trashes 1 program") runner-loses-click end-the-run] :strength-bonus (req (if (some #(has-subtype? % "AI") (all-active-installed state :runner)) 3 0))}) (defcard "Cortex Lock" {:subroutines [{:label "Do 1 net damage for each unused memory unit the Runner has" :msg (msg "do " (available-mu state) " net damage") :effect (effect (damage eid :net (available-mu state) {:card card}))}]}) (defcard "Crick" {:subroutines [{:label "install a card from Archives" :prompt "Select a card to install from Archives" :show-discard true :async true :choices {:card #(and (not (operation? %)) (in-discard? %) (corp? %))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil nil))}] :strength-bonus (req (if (= (second (get-zone card)) :archives) 3 0))}) (defcard "Curtain Wall" {:subroutines [end-the-run end-the-run end-the-run] :strength-bonus (req (let [ices (:ices (card->server state card))] (if (same-card? card (last ices)) 4 0))) :events [{:event :trash :req (req (and (not (same-card? card target)) (= (card->server state card) (card->server state target)))) :effect (effect (update-ice-strength card))} {:event :corp-install :req (req (and (not (same-card? card (:card context))) (= (card->server state card) (card->server state (:card context))))) :effect (effect (update-ice-strength card))}]}) (defcard "Data Hound" (letfn [(dh-trash [cards] {:prompt "Choose a card to trash" :choices cards :async true :msg (msg "trash " (:title target)) :effect (req (wait-for (trash state side target {:unpreventable true :cause :subroutine}) (continue-ability state side (reorder-choice :runner :runner (remove-once #(= % target) cards) '() (count (remove-once #(= % target) cards)) (remove-once #(= % target) cards)) card nil)))})] {:subroutines [(trace-ability 2 {:async true :label "Look at the top of the stack" :msg "look at top X cards of the stack" :waiting-prompt "Corp to rearrange the top cards of the stack" :effect (req (let [c (- target (second targets)) from (take c (:deck runner))] (system-msg state :corp (str "looks at the top " (quantify c "card") " of the stack")) (if (< 1 c) (continue-ability state side (dh-trash from) card nil) (wait-for (trash state side (first from) {:unpreventable true :cause :subroutine}) (system-msg state :corp (str "trashes " (:title (first from)))) (effect-completed state side eid)))))})]})) (defcard "Data Loop" {:on-encounter {:req (req (pos? (count (:hand runner)))) :async true :effect (effect (continue-ability :runner (let [n (min 2 (count (:hand runner)))] {:prompt (str "Choose " (quantify n "card") " in your Grip to add to the top of the Stack (second card targeted will be topmost)") :choices {:max n :all true :card #(and (in-hand? %) (runner? %))} :msg (msg "add " n " cards from their Grip to the top of the Stack") :effect (req (doseq [c targets] (move state :runner c :deck {:front true})))}) card nil))} :subroutines [end-the-run-if-tagged end-the-run]}) (defcard "Data Mine" {:subroutines [{:msg "do 1 net damage" :async true :effect (req (wait-for (damage state :runner :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))}]}) (defcard "Data Raven" {:abilities [(power-counter-ability (give-tags 1))] :on-encounter {:msg "force the Runner to take 1 tag or end the run" :player :runner :prompt "Choose one" :choices ["Take 1 tag" "End the run"] :async true :effect (req (if (= target "Take 1 tag") (do (system-msg state :runner "chooses to take 1 tag") (gain-tags state :runner eid 1)) (do (system-msg state :runner "ends the run") (end-run state :runner eid card))))} :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Data Ward" {:on-encounter {:player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Take 1 tag"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state :runner card :credit 3) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)) (do (system-msg state :runner "takes 1 tag on encountering Data Ward") (gain-tags state :runner eid 1))))} :subroutines [end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Datapike" {:subroutines [{:msg "force the Runner to pay 2 [Credits] if able" :async true :effect (req (wait-for (pay state :runner card :credit 2) (when-let [payment-str (:msg async-result)] (system-msg state :runner payment-str)) (effect-completed state side eid)))} end-the-run]}) (defcard "DNA Tracker" (let [sub {:msg "do 1 net damage and make the Runner lose 2 [Credits]" :async true :effect (req (wait-for (damage state side :net 1 {:card card}) (lose-credits state :runner eid 2)))}] {:subroutines [sub sub sub]})) (defcard "Dracō" {:on-rez {:prompt "How many power counters?" :choices :credit :msg (msg "add " target " power counters") :effect (effect (add-counter card :power target) (update-ice-strength card))} :strength-bonus (req (get-counters card :power)) :subroutines [(trace-ability 2 {:label "Give the Runner 1 tag and end the run" :msg "give the Runner 1 tag and end the run" :async true :effect (req (wait-for (gain-tags state :corp 1) (end-run state :corp eid card)))})]}) (defcard "Drafter" {:subroutines [{:label "Add 1 card from Archives to HQ" :prompt "Select a card from Archives to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %))} :msg (msg "add " (if (faceup? target) (:title target) "an unseen card") " to HQ") :effect (effect (move target :hand))} {:async true :label "Install a card from HQ or Archives" :prompt "Select a card to install from Archives or HQ" :show-discard true :choices {:card #(and (corp? %) (not (operation? %)) (or (in-hand? %) (in-discard? %)))} :msg (msg (corp-install-msg target)) :effect (effect (corp-install eid target nil {:ignore-all-cost true}))}]}) (defcard "Eli 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Eli 2.0" {:subroutines [{:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} end-the-run end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Endless EULA" (let [sub (end-the-run-unless-runner-pays 1)] (letfn [(break-fn [unbroken-subs total] {:async true :effect (req (if (seq unbroken-subs) (wait-for (pay state :runner (make-eid state {:source-type :subroutine}) card [:credit 1]) (system-msg state :runner (:msg async-result)) (continue-ability state side (break-fn (rest unbroken-subs) (inc total)) card nil)) (let [msgs (when (pos? total) (str "resolves " (quantify total "unbroken subroutine") " on Endless EULA" " (\"[subroutine] " (:label sub) "\")"))] (when (pos? total) (system-msg state side msgs)) (effect-completed state side eid))))})] {:subroutines [sub sub sub sub sub sub] :runner-abilities [{:req (req (<= (count (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card))) (total-available-credits state :runner eid card))) :async true :label "Pay for all unbroken subs" :effect (req (let [unbroken-subs (remove #(or (:broken %) (= false (:resolve %))) (:subroutines card)) eid (assoc eid :source-type :subroutine)] (->> unbroken-subs (reduce resolve-subroutine card) (update! state side)) (continue-ability state side (break-fn unbroken-subs 0) card nil)))}]}))) (defcard "Enforcer 1.0" {:additional-cost [:forfeit] :subroutines [trash-program-sub (do-brain-damage 1) {:label "Trash a console" :prompt "Select a console to trash" :choices {:card #(has-subtype? % "Console")} :msg (msg "trash " (:title target)) :async true :effect (effect (trash eid target {:cause :subroutine}))} {:msg "trash all virtual resources" :async true :effect (req (let [cards (filter #(has-subtype? % "Virtual") (all-active-installed state :runner))] (trash-cards state side eid cards {:cause :subroutine})))}] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Engram Flush" (let [sub {:async true :label "Reveal the grip" :msg (msg "reveal " (quantify (count (:hand runner)) "card") " from grip: " (string/join ", " (map :title (:hand runner)))) :effect (effect (reveal eid (:hand runner)))}] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :effect (req (let [cardtype target] (system-msg state side (str "uses " (:title card) " to name " target)) (register-events state side card [{:event :corp-reveal :duration :end-of-encounter :async true :req (req (and ; all revealed cards are in grip (every? in-hand? targets) ; entire grip was revealed (= (count targets) (count (:hand runner))) ; there are cards with the named card type (some #(is-type? % cardtype) targets))) :prompt "Select revealed card to trash" :choices (req (concat (filter #(is-type? % cardtype) targets) ["None"])) :msg (msg "trash " (:title target) " from grip") :effect (req (if (= "None" target) (effect-completed state side eid) (trash state side eid target {:cause :subroutine})))}])))} :subroutines [sub sub]})) (defcard "Enigma" {:subroutines [runner-loses-click end-the-run]}) (defcard "Envelope" {:subroutines [(do-net-damage 1) end-the-run]}) (defcard "Errand Boy" (let [sub {:async true :label "Draw a card or gain 1 [Credits]" :prompt "Choose one:" :choices ["Gain 1 [Credits]" "Draw 1 card"] :msg (req (if (= target "Gain 1 [Credits]") "gain 1 [Credits]" "draw 1 card")) :effect (req (if (= target "Gain 1 [Credits]") (gain-credits state :corp eid 1) (draw state :corp eid 1 nil)))}] {:subroutines [sub sub sub]})) (defcard "Excalibur" {:subroutines [{:label "The Runner cannot make another run this turn" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}]}) (defcard "Executive Functioning" {:subroutines [(trace-ability 4 (do-brain-damage 1))]}) (defcard "F2P" {:subroutines [add-runner-card-to-grip (give-tags 1)] :runner-abilities [(break-sub [:credit 2] 1 nil {:req (req (not tagged))})]}) (defcard "Fairchild" {:subroutines [(end-the-run-unless-runner-pays 4) (end-the-run-unless-runner-pays 4) (end-the-run-unless-runner "trashes an installed card" "trash an installed card" runner-trash-installed-sub) (end-the-run-unless-runner "suffers 1 brain damage" "suffer 1 brain damage" (do-brain-damage 1))]}) (defcard "Fairchild 1.0" (let [sub {:label "Force the Runner to pay 1 [Credits] or trash an installed card" :msg "force the Runner to pay 1 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 1 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 1 [Credits]") (wait-for (pay state side card :credit 1) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Fairchild 2.0" (let [sub {:label "Force the Runner to pay 2 [Credits] or trash an installed card" :msg "force the Runner to pay 2 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 2 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 2 [Credits]") (wait-for (pay state side card :credit 2) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub (do-brain-damage 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "Fairchild 3.0" (let [sub {:label "Force the Runner to pay 3 [Credits] or trash an installed card" :msg "force the Runner to pay 3 [Credits] or trash an installed card" :player :runner :prompt "Choose one" :choices ["Pay 3 [Credits]" "Trash an installed card"] :async true :effect (req (if (= target "Pay 3 [Credits]") (wait-for (pay state side card :credit 3) (system-msg state side (:msg async-result)) (effect-completed state side eid)) (continue-ability state :runner runner-trash-installed-sub card nil)))}] {:subroutines [sub sub {:label "Do 1 brain damage or end the run" :prompt "Choose one" :choices ["Do 1 brain damage" "End the run"] :msg (msg (string/lower-case target)) :async true :effect (req (if (= target "Do 1 brain damage") (damage state side eid :brain 1 {:card card}) (end-run state side eid card)))}] :runner-abilities [(bioroid-break 3 3)]})) (defcard "PI:NAME:<NAME>END_PI" {:on-rez take-bad-pub :subroutines [(do-brain-damage 1) end-the-run]}) (defcard "Fire Wall" (wall-ice [end-the-run])) (defcard "Flare" {:subroutines [(trace-ability 6 {:label "Trash 1 hardware, do 2 meat damage, and end the run" :async true :effect (effect (continue-ability {:prompt "Select a piece of hardware to trash" :label "Trash a piece of hardware" :choices {:card hardware?} :msg (msg "trash " (:title target)) :async true :effect (req (wait-for (trash state side target {:cause :subroutine}) (system-msg state :corp (str "uses Flare to trash " (:title target))) (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))) :cancel-effect (req (wait-for (damage state side :meat 2 {:unpreventable true :card card}) (system-msg state :corp (str "uses Flare to deal 2 meat damage")) (system-msg state :corp (str "uses Flare to end the run")) (end-run state side eid card)))} card nil))})]}) (defcard "Formicary" {:derezzed-events [{:event :approach-server :interactive (req true) :optional {:prompt "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI?" :yes-ability {:msg "rez and move Formicary. The Runner is now approaching Formicary" :async true :effect (req (wait-for (rez state side card) (move state side (get-card state card) [:servers (target-server run) :ices] {:front true}) (swap! state assoc-in [:run :position] 1) (set-next-phase state :encounter-ice) (set-current-ice state) (update-all-ice state side) (update-all-icebreakers state side) (effect-completed state side eid) (start-next-phase state side nil)))}}}] :subroutines [{:label "End the run unless the Runner suffers 2 net damage" :player :runner :async true :prompt "Suffer 2 net damage or end the run?" :choices ["2 net damage" "End the run"] :effect (req (if (= target "End the run") (do (system-msg state :runner "chooses to end the run") (end-run state :corp eid card)) (damage state :runner eid :net 2 {:card card :unpreventable true})))}]}) (defcard "Free Lunch" {:abilities [{:cost [:power 1] :label "Runner loses 1 [Credits]" :msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))}] :subroutines [add-power-counter add-power-counter]}) (defcard "GPI:NAME:<NAME>END_PI" (grail-ice end-the-run)) (defcard "Gatekeeper" (let [draw-ab {:async true :prompt "Draw how many cards?" :choices {:number (req 3) :max (req 3) :default (req 1)} :msg (msg "draw " target " cards") :effect (effect (draw eid target nil))} reveal-and-shuffle {:prompt "Reveal and shuffle up to 3 agendas" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (agenda? %)) :max (req 3)} :async true :effect (req (wait-for (reveal state side targets) (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck) (effect-completed state :corp eid))) :cancel-effect (effect (shuffle! :deck) (effect-completed eid)) :msg (msg "add " (str (string/join ", " (map :title targets))) " to R&D")} draw-reveal-shuffle {:async true :label "Draw cards, reveal and shuffle agendas" :effect (req (wait-for (resolve-ability state side draw-ab card nil) (continue-ability state side reveal-and-shuffle card nil)))}] {:strength-bonus (req (if (= :this-turn (:rezzed card)) 6 0)) :subroutines [draw-reveal-shuffle end-the-run]})) (defcard "Gemini" (constellation-ice (do-net-damage 1))) (defcard "PI:NAME:<NAME>END_PI" (letfn [(gf-lose-credits [state side eid n] (if (pos? n) (wait-for (lose-credits state :runner 1) (gf-lose-credits state side eid (dec n))) (effect-completed state side eid)))] {:implementation "Auto breaking will break even with too few credits" :on-break-subs {:req (req (some :printed (second targets))) :msg (msg (let [n-subs (count (filter :printed (second targets)))] (str "force the runner to lose " n-subs " [Credits] for breaking printed subs"))) :async true :effect (effect (gf-lose-credits eid (count (filter :printed (second targets)))))} :subroutines [(end-the-run-unless-runner-pays 3) (end-the-run-unless-runner-pays 3)]})) (defcard "PI:NAME:<NAME>END_PI" {:on-rez take-bad-pub :subroutines [trash-program-sub]}) (defcard "Guard" {:constant-effects [{:type :bypass-ice :req (req (same-card? card target)) :value false}] :subroutines [end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [(tag-trace 7)] :strength-bonus (req (if (= (second (get-zone card)) :rd) 3 0))}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:req (req run) :label "Reduce Runner's hand size by 2" :msg "reduce the Runner's maximum hand size by 2 until the start of the next Corp turn" :effect (effect (register-floating-effect card {:type :hand-size :duration :until-corp-turn-begins :req (req (= :runner side)) :value -2}))}]}) (defcard "PI:NAME:<NAME>END_PI" (wall-ice [end-the-run end-the-run])) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Trash 1 program" :prompt "Choose a program that is not a decoder, fracter or killer" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (program? %) (not (has-subtype? % "Decoder")) (not (has-subtype? % "Fracter")) (not (has-subtype? % "Killer")))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))} end-the-run] :strength-bonus (req (- (count (filter #(has-subtype? % "Icebreaker") (all-active-installed state :runner)))))}) (defcard "Hailstorm" {:subroutines [{:label "Remove a card in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a card in the Runner's Heap" :choices (req (:discard runner)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg)) } card nil))} end-the-run]}) (defcard "Harvester" (let [sub {:label "Runner draws 3 cards and discards down to maximum hand size" :msg "make the Runner draw 3 cards and discard down to their maximum hand size" :async true :effect (req (wait-for (draw state :runner 3 nil) (continue-ability state :runner (let [delta (- (count (get-in @state [:runner :hand])) (hand-size state :runner))] (when (pos? delta) {:prompt (msg "Select " delta " cards to discard") :player :runner :choices {:max delta :card #(in-hand? %)} :async true :effect (req (wait-for (trash-cards state :runner targets) (system-msg state :runner (str "trashes " (string/join ", " (map :title targets)))) (effect-completed state side eid)))})) card nil)))}] {:subroutines [sub sub]})) (defcard "Heimdall 1.0" {:subroutines [(do-brain-damage 1) end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Heimdall 2.0" {:subroutines [(do-brain-damage 1) {:msg "do 1 brain damage and end the run" :effect (req (wait-for (damage state side :brain 1 {:card card}) (end-run state side eid card)))} end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Herald" {:flags {:rd-reveal (req true)} :subroutines [(gain-credits-sub 2) {:async true :label "Pay up to 2 [Credits] to place up to 2 advancement tokens" :prompt "How many advancement tokens?" :choices (req (map str (range (inc (min 2 (:credit corp)))))) :effect (req (let [c (str->int target)] (if (can-pay? state side (assoc eid :source card :source-type :subroutine) card (:title card) :credit c) (let [new-eid (make-eid state {:source card :source-type :subroutine})] (wait-for (pay state :corp new-eid card :credit c) (system-msg state :corp (:msg async-result)) (continue-ability state side {:msg (msg "pay " c "[Credits] and place " (quantify c " advancement token") " on " (card-str state target)) :choices {:card can-be-advanced?} :effect (effect (add-prop target :advance-counter c {:placed true}))} card nil))) (effect-completed state side eid))))}] :access {:optional {:req (req (not (in-discard? card))) :player :runner :waiting-prompt "Runner to decide to break Herald subroutines" :prompt "You are encountering Herald. Allow its subroutines to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "PI:NAME:<NAME>END_PI" {:abilities [{:msg "add it to HQ" :cost [:credit 1] :effect (effect (move card :hand))}] :subroutines [end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" (let [corp-points (fn [corp] (min 5 (max 0 (- 5 (:agenda-point corp 0))))) ability {:silent (req true) :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :agenda-scored) (assoc ability :event :as-agenda :req (req (= "Corp" (:as-agenda-side target))))] :abilities [{:label "Lose subroutines" :msg (msg "lose " (- 5 (corp-points corp)) " subroutines") :effect (effect (reset-printed-subs card (corp-points corp) end-the-run))}] :subroutines [end-the-run end-the-run end-the-run end-the-run end-the-run]})) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [(trace-ability 4 {:label "Runner cannot access any cards this run" :msg "stop the Runner from accessing any cards this run" :effect (effect (prevent-access))}) {:label "Trash an icebreaker" :prompt "Choose an icebreaker to trash" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (has-subtype? % "Icebreaker"))} :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}]}) (defcard "PI:NAME:<NAME>END_PI" (letfn [(hort [n] {:prompt "Choose a card to add to HQ with Hortum" :async true :choices (req (cancellable (:deck corp) :sorted)) :msg "add 1 card to HQ from R&D" :cancel-effect (req (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid)) :effect (req (move state side target :hand) (if (< n 2) (continue-ability state side (hort (inc n)) card nil) (do (shuffle! state side :deck) (system-msg state side (str "shuffles R&D")) (effect-completed state side eid))))})] (let [breakable-fn (req (when (or (> 3 (get-counters card :advancement)) (not (has-subtype? target "AI"))) :unrestricted))] {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 4 [Credits])" :breakable breakable-fn :msg (msg "gain " (if (wonder-sub card 3) "4" "1") " [Credits]") :async true :effect (effect (gain-credits :corp eid (if (wonder-sub card 3) 4 1)))} {:label "End the run (Search R&D for up to 2 cards and add them to HQ, shuffle R&D, end the run)" :async true :breakable breakable-fn :effect (req (if (wonder-sub card 3) (wait-for (resolve-ability state side (hort 1) card nil) (do (system-msg state side (str "uses Hortum to add 2 cards to HQ from R&D, " "shuffle R&D, and end the run")) (end-run state side eid card))) (do (system-msg state side (str "uses Hortum to end the run")) (end-run state side eid card))))}]}))) (defcard "Hourglass" {:subroutines [runner-loses-click runner-loses-click runner-loses-click]}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Install a piece of Bioroid ICE from HQ or Archives" :req (req (some #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid")) (concat (:hand corp) (:discard corp)))) :async true :prompt "Install ICE from HQ or Archives?" :show-discard true :choices {:card #(and (corp? %) (or (in-hand? %) (in-discard? %)) (has-subtype? % "Bioroid"))} :effect (req (wait-for (corp-install state side (make-eid state eid) target (zone->name (target-server run)) {:ignore-all-cost true :index (card-index state card)}) (let [new-ice async-result] (register-events state side card [{:event :run-ends :duration :end-of-run :async true :effect (effect (derez new-ice) (trash eid card {:cause :subroutine}))}]))))}]}) (defcard "PI:NAME:<NAME>END_PIudson 1.0" (let [sub {:msg "prevent the Runner from accessing more than 1 card during this run" :effect (effect (max-access 1))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "PI:NAME:<NAME>END_PIunter" {:subroutines [(tag-trace 3)]}) (defcard "Hydra" (letfn [(otherwise-tag [message ability] {:msg (msg (if tagged message "give the Runner 1 tag")) :label (str (capitalize message) " if the Runner is tagged; otherwise, give the Runner 1 tag") :async true :effect (req (if tagged (ability state :runner eid card nil) (gain-tags state :runner eid 1)))})] {:subroutines [(otherwise-tag "do 3 net damage" (effect (damage :runner eid :net 3 {:card card}))) (otherwise-tag "gain 5 [Credits]" (effect (gain-credits :corp eid 5))) (otherwise-tag "end the run" (effect (end-run eid card)))]})) (defcard "Ice Wall" (wall-ice [end-the-run])) (defcard "Ichi 1.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 1 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Ichi 2.0" {:subroutines [trash-program-sub trash-program-sub (trace-ability 3 {:label "Give the Runner 1 tag and do 1 brain damage" :msg "give the Runner 1 tag and do 1 brain damage" :async true :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (gain-tags state :corp eid 1)))})] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Inazuma" {:subroutines [{:msg "prevent the Runner from breaking subroutines on the next piece of ICE they encounter this run" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "prevent the runner from breaking subroutines on " (:title (:ice context))) :effect (effect (register-floating-effect card (let [encountered-ice (:ice context)] {:type :cannot-break-subs-on-ice :duration :end-of-encounter :req (req (same-card? encountered-ice target)) :value true})))}]))} {:msg "prevent the Runner from jacking out until after the next piece of ICE" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :effect (req (let [encountered-ice (:ice context)] (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :msg (msg "can jack out again after encountering " (:title encountered-ice)) :effect (req (swap! state update :run dissoc :cannot-jack-out)) :req (req (same-card? encountered-ice (:ice context)))}])))}]))}]}) (defcard "Information Overload" {:on-encounter (tag-trace 1) :on-rez {:effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))} :events [{:event :tags-changed :effect (effect (reset-variable-subs card (count-tags state) runner-trash-installed-sub))}]}) (defcard "Interrupt 0" (let [sub {:label "Make the Runner pay 1 [Credits] to use icebreaker" :msg "make the Runner pay 1 [Credits] to use icebreakers to break subroutines during this run" :effect (effect (register-floating-effect card {:type :break-sub-additional-cost :duration :end-of-run :req (req (and ; The card is an icebreaker (has-subtype? target "Icebreaker") ; and is using a break ability (contains? (second targets) :break) (pos? (:break (second targets) 0)))) :value [:credit 1]}))}] {:subroutines [sub sub]})) (defcard "IP Block" {:on-encounter (assoc (give-tags 1) :req (req (seq (filter #(has-subtype? % "AI") (all-active-installed state :runner)))) :msg "give the runner 1 tag because there is an installed AI") :subroutines [(tag-trace 3) end-the-run-if-tagged]}) (defcard "IQ" {:subroutines [end-the-run] :strength-bonus (req (count (:hand corp))) :rez-cost-bonus (req (count (:hand corp))) :leave-play (req (remove-watch state (keyword (str "iq" (:cid card)))))}) (defcard "Ireress" (let [sub {:msg "make the Runner lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} ability {:effect (effect (reset-variable-subs card (count-bad-pub state) sub))}] {:events [(assoc ability :event :rez :req (req (same-card? card (:card context)))) (assoc ability :event :corp-gain-bad-publicity) (assoc ability :event :corp-lose-bad-publicity)]})) (defcard "It's a Trap!" {:expose {:msg "do 2 net damage" :async true :effect (effect (damage eid :net 2 {:card card}))} :subroutines [(assoc runner-trash-installed-sub :effect (req (wait-for (trash state side target {:cause :subroutine}) (trash state side eid card {:cause :subroutine}))))]}) (defcard "PI:NAME:<NAME>END_PIus 1.0" {:subroutines [(do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "PI:NAME:<NAME>END_PI" {:on-encounter {:msg "prevent the Runner from installing cards for the rest of the turn" :effect (effect (register-turn-flag! card :runner-lock-install (constantly true)))} :subroutines [{:label "Choose 2 installed Runner cards, if able. The Runner must add 1 of those to the top of the Stack." :req (req (>= (count (all-installed state :runner)) 2)) :async true :prompt "Select 2 installed Runner cards" :choices {:card #(and (runner? %) (installed? %)) :max 2 :all true} :msg (msg "add either " (card-str state (first targets)) " or " (card-str state (second targets)) " to the Stack") :effect (effect (continue-ability (when (= 2 (count targets)) {:player :runner :waiting-prompt "Runner to decide which card to move" :prompt "Select a card to move to the Stack" :choices {:card #(some (partial same-card? %) targets)} :effect (req (move state :runner target :deck {:front true}) (system-msg state :runner (str "selected " (card-str state target) " to move to the Stack")))}) card nil))}]}) (defcard "Kakugo" {:events [{:event :pass-ice :async true :req (req (same-card? (:ice context) card)) :msg "do 1 net damage" :effect (effect (damage eid :net 1 {:card card}))}] :subroutines [end-the-run]}) (defcard "Kamali 1.0" (letfn [(better-name [kind] (if (= "hardware" kind) "piece of hardware" kind)) (runner-trash [kind] {:prompt (str "Select an installed " (better-name kind) " to trash") :label (str "Trash an installed " (better-name kind)) :msg (msg "trash " (:title target)) :async true :choices {:card #(and (installed? %) (is-type? % (capitalize kind)))} :cancel-effect (effect (system-msg (str "fails to trash an installed " (better-name kind))) (effect-completed eid)) :effect (effect (trash eid target {:cause :subroutine}))}) (sub-map [kind] {:player :runner :async true :waiting-prompt "Runner to decide on Kamali 1.0 action" :prompt "Choose one" :choices ["Take 1 brain damage" (str "Trash an installed " (better-name kind))] :effect (req (if (= target "Take 1 brain damage") (do (system-msg state :corp "uses Kamali 1.0 to give the Runner 1 brain damage") (damage state :runner eid :brain 1 {:card card})) (continue-ability state :runner (runner-trash kind) card nil)))}) (brain-trash [kind] {:label (str "Force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :msg (str "force the Runner to take 1 brain damage or trash an installed " (better-name kind)) :async true :effect (req (wait-for (resolve-ability state side (sub-map kind) card nil) (clear-wait-prompt state :corp)))})] {:subroutines [(brain-trash "resource") (brain-trash "hardware") (brain-trash "program")] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Karunā" (let [offer-jack-out {:optional {:waiting-prompt "Runner to decide on jack out" :player :runner :prompt "Jack out?" :yes-ability {:async true :effect (effect (jack-out eid))} :no-ability {:effect (effect (system-msg :runner "chooses to continue"))}}}] {:subroutines [{:label "Do 2 net damage" :async true :effect (req (wait-for (resolve-ability state side (do-net-damage 2) card nil) (continue-ability state side offer-jack-out card nil)))} (do-net-damage 2)]})) (defcard "Kitsune" {:subroutines [{:optional {:req (req (pos? (count (:hand corp)))) :prompt "Force the Runner to access a card in HQ?" :yes-ability {:async true :prompt "Select a card in HQ to force access" :choices {:card (every-pred in-hand? corp?) :all true} :label "Force the Runner to access a card in HQ" :msg (msg "force the Runner to access " (:title target)) :effect (req (wait-for (do-access state :runner [:hq] {:no-root true :access-first target}) (trash state side eid card {:cause :subroutine})))}}}]}) (defcard "PI:NAME:<NAME>END_PI" {:on-encounter {:effect (effect (gain-variable-subs card (count (:hand runner)) (do-net-damage 1)))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]}) (defcard "PI:NAME:<NAME>END_PI" {:implementation "Encounter effect is manual" :on-encounter (do-psi {:label "Force the runner to encounter another ice" :prompt "Choose a piece of ice" :choices {:card ice? :not-self true} :msg (msg "force the Runner to encounter " (card-str state target)) :effect (req (effect-completed state side eid))})}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Force the Runner to trash an installed piece of hardware" :player :runner :async true :msg (msg "force the Runner to trash " (:title target)) :prompt "Select a piece of hardware to trash" :choices {:card #(and (installed? %) (hardware? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "PI:NAME:<NAME>END_PI" (grail-ice trash-program-sub)) (defcard "Little Engine" {:subroutines [end-the-run end-the-run {:msg "make the Runner gain 5 [Credits]" :async true :effect (effect (gain-credits :runner eid 5))}]}) (defcard "Lockdown" {:subroutines [{:label "The Runner cannot draw cards for the remainder of this turn" :msg "prevent the Runner from drawing cards" :effect (effect (prevent-draw))}]}) (defcard "Loki" {:on-encounter {:req (req (<= 2 (count (filter ice? (all-active-installed state :corp))))) :choices {:card #(and (ice? %) (active? %)) :not-self true} :effect (req (let [target-subtypes (:subtype target)] (register-floating-effect state :corp card {:type :gain-subtype :duration :end-of-run :req (req (same-card? card target)) :value (:subtypes target)}) (doseq [sub (:subroutines target)] (add-sub! state side (get-card state card) sub (:cid target) {:front true})) (register-events state side card (let [cid (:cid target)] [{:event :run-ends :unregister-once-resolved true :req (req (get-card state card)) :effect (effect (remove-subs! (get-card state card) #(= cid (:from-cid %))))}]))))} :subroutines [{:label "End the run unless the Runner shuffles their Grip into the Stack" :async true :effect (req (if (zero? (count (:hand runner))) (do (system-msg state :corp (str "uses Loki to end the run")) (end-run state side eid card)) (continue-ability state :runner {:optional {:waiting-prompt "Runner to decide to shuffle their Grip into the Stack" :prompt "Reshuffle your Grip into the Stack?" :player :runner :yes-ability {:effect (req (doseq [c (:hand runner)] (move state :runner c :deck)) (shuffle! state :runner :deck) (system-msg state :runner "shuffles their Grip into their Stack"))} :no-ability {:async true :effect (effect (system-msg :runner "doesn't shuffle their Grip into their Stack. Loki ends the run") (end-run eid card))}}} card nil)))}]}) (defcard "Loot Box" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (top-3-names [state] (map :title (top-3 state)))] {:subroutines [(end-the-run-unless-runner-pays 2) {:label "Reveal the top 3 cards of the Stack" :async true :effect (req (system-msg state side (str "uses Loot Box to reveal the top 3 cards of the stack: " (string/join ", " (top-3-names state)))) (wait-for (reveal state side (top-3 state)) (continue-ability state side {:waiting-prompt "Corp to choose a card to add to the Grip" :prompt "Choose a card to add to the Grip" :choices (req (top-3 state)) :msg (msg "add " (:title target) " to the Grip, gain " (:cost target) " [Credits] and shuffle the Stack. Loot Box is trashed") :async true :effect (req (move state :runner target :hand) (wait-for (gain-credits state :corp (:cost target)) (shuffle! state :runner :deck) (trash state side eid card {:cause :subroutine})))} card nil)))}]})) (defcard "Lotus Field" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Lycan" (morph-ice "Sentry" "Code Gate" trash-program-sub)) (defcard "Machicolation A" {:subroutines [trash-program-sub trash-program-sub trash-hardware-sub {:label "Runner loses 3[credit], if able. End the run." :msg "make the Runner lose 3[credit] and end the run" :async true :effect (req (if (>= (:credit runner) 3) (wait-for (lose-credits state :runner 3) (end-run state :corp eid card)) (end-run state :corp eid card)))}]}) (defcard "Machicolation B" {:subroutines [trash-resource-sub trash-resource-sub (do-net-damage 1) {:label "Runner loses 1[click], if able. End the run." :msg "make the Runner lose 1[click] and end the run" :async true :effect (req (lose state :runner :click 1) (end-run state :corp eid card))}]}) (defcard "Macrophage" {:subroutines [(trace-ability 4 {:label "Purge virus counters" :msg "purge virus counters" :effect (effect (purge))}) (trace-ability 3 {:label "Trash a virus" :prompt "Choose a virus to trash" :choices {:card #(and (installed? %) (has-subtype? % "Virus"))} :msg (msg "trash " (:title target)) :async true :effect (effect (clear-wait-prompt :runner) (trash eid target {:cause :subroutine}))}) (trace-ability 2 {:label "Remove a virus in the Heap from the game" :async true :effect (effect (continue-ability {:async true :req (req (not (zone-locked? state :runner :discard))) :prompt "Choose a virus in the Heap to remove from the game" :choices (req (cancellable (filter #(has-subtype? % "Virus") (:discard runner)) :sorted)) :msg (msg "remove " (:title target) " from the game") :effect (effect (move :runner target :rfg))} card nil))}) (trace-ability 1 end-the-run)]}) (defcard "Magnet" (letfn [(disable-hosted [state side c] (doseq [hc (:hosted (get-card state c))] (unregister-events state side hc) (update! state side (dissoc hc :abilities))))] {:on-rez {:async true :effect (req (let [magnet card] (wait-for (resolve-ability state side {:req (req (some #(some program? (:hosted %)) (remove-once #(same-card? % magnet) (filter ice? (all-installed state corp))))) :prompt "Select a Program to host on Magnet" :choices {:card #(and (program? %) (ice? (:host %)) (not (same-card? (:host %) magnet)))} :effect (effect (host card target))} card nil) (disable-hosted state side card) (effect-completed state side eid))))} :derez-effect {:req (req (not-empty (:hosted card))) :effect (req (doseq [c (get-in card [:hosted])] (card-init state side c {:resolve-effect false})))} :events [{:event :runner-install :req (req (same-card? card (:host (:card context)))) :effect (req (disable-hosted state side card) (update-ice-strength state side card))}] :subroutines [end-the-run]})) (defcard "Mamba" {:abilities [(power-counter-ability (do-net-damage 1))] :subroutines [(do-net-damage 1) (do-psi {:label "Add 1 power counter" :msg "add 1 power counter" :effect (effect (add-counter card :power 1) (effect-completed eid))})]}) (defcard "Marker" {:subroutines [{:label "Give next encountered ice \"End the run\"" :msg (msg "give next encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :req (req (rezzed? (:ice context))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "PI:NAME:<NAME>END_PIus 1.0" {:subroutines [runner-trash-installed-sub end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "PI:NAME:<NAME>END_PI" (let [ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}] {:advanceable :always :on-rez {:effect (effect (add-prop card :advance-counter 1))} :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) end-the-run))}]})) (defcard "PI:NAME:<NAME>END_PI" {:on-encounter {:cost [:credit 1] :choices {:card can-be-advanced?} :msg (msg "place 1 advancement token on " (card-str state target)) :effect (effect (add-prop target :advance-counter 1))} :subroutines [(tag-trace 2)]}) (defcard "PI:NAME:<NAME>END_PI" {:advanceable :always :subroutines [{:label "Gain 1 [Credits] (Gain 3 [Credits])" :msg (msg "gain " (if (wonder-sub card 3) 3 1) "[Credits]") :async true :effect (effect (gain-credits eid (if (wonder-sub card 3) 3 1)))} {:label "Do 1 net damage (Do 3 net damage)" :async true :msg (msg "do " (if (wonder-sub card 3) 3 1) " net damage") :effect (effect (damage eid :net (if (wonder-sub card 3) 3 1) {:card card}))} {:label "Give the Runner 1 tag (and end the run)" :async true :msg (msg "give the Runner 1 tag" (when (wonder-sub card 3) " and end the run")) :effect (req (gain-tags state :corp eid 1) (if (wonder-sub card 3) (end-run state side eid card) (effect-completed state side eid)))}]}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Gain 4 [Credits] and end the run" :waiting-prompt "Runner to choose an option for PI:NAME:<NAME>END_PIian" :prompt "Choose one" :choices ["End the run" "Add PI:NAME:<NAME>END_PIidian to score area"] :player :runner :async true :effect (req (if (= target "End the run") (do (system-msg state :corp "uses PI:NAME:<NAME>END_PIidian to gain 4 [Credits] and end the run") (wait-for (gain-credits state :corp 4) (end-run state :runner eid card))) (do (system-msg state :runner "adds PI:NAME:<NAME>END_PIian to their score area as an agenda worth -1 agenda points") (wait-for (as-agenda state :runner card -1) (when current-ice (continue state :corp nil) (continue state :runner nil)) (effect-completed state side eid)))))}]}) (defcard "PI:NAME:<NAME>END_PI" (grail-ice (do-net-damage 2))) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [end-the-run] :strength-bonus (req (if (= (second (get-zone card)) :hq) 3 0))}) (defcard "PI:NAME:<NAME>END_PIamorph" {:subroutines [{:label "Swap two ICE or swap two installed non-ICE" :msg "swap two ICE or swap two installed non-ICE" :async true :prompt "Choose one" :req (req (or (<= 2 (count (filter ice? (all-installed state :corp)))) (<= 2 (count (remove ice? (all-installed state :corp)))))) :choices (req [(when (<= 2 (count (filter ice? (all-installed state :corp)))) "Swap two ICE") (when (<= 2 (count (remove ice? (all-installed state :corp)))) "Swap two non-ICE")]) :effect (effect (continue-ability (if (= target "Swap two ICE") {:prompt "Select the two ICE to swap" :choices {:card #(and (installed? %) (ice? %)) :not-self true :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-ice state side targets))} {:prompt "Select the two cards to swap" :choices {:card #(and (installed? %) (not (ice? %))) :max 2 :all true} :msg (msg "swap the positions of " (card-str state (first targets)) " and " (card-str state (second targets))) :effect (req (apply swap-installed state side targets))}) card nil))}]}) (defcard "Mganga" {:subroutines [(do-psi {:async true :label "do 2 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 2 {:card card}) (trash state :corp eid card {:cause :subroutine})))} {:async true :label "do 1 net damage" :player :corp :effect (req (wait-for (damage state :corp :net 1 {:card card}) (trash state :corp eid card {:cause :subroutine})))})]}) (defcard "Mind Game" {:subroutines [(do-psi {:label "Redirect the run to another server" :player :corp :prompt "Choose a server" :choices (req (remove #{(-> @state :run :server central->name)} servers)) :msg (msg "redirect the run to " target " and for the remainder of the run, the runner must add 1 installed card to the bottom of their stack as an additional cost to jack out") :effect (effect (redirect-run target :approach-ice) (register-floating-effect card {:type :jack-out-additional-cost :duration :end-of-run :value [:add-installed-to-bottom-of-deck 1]}) (effect-completed eid) (start-next-phase nil))})]}) (defcard "Minelayer" {:subroutines [{:msg "install an ICE from HQ" :async true :choices {:card #(and (ice? %) (in-hand? %))} :prompt "Choose an ICE to install from HQ" :effect (effect (corp-install eid target (zone->name (target-server run)) {:ignore-all-cost true}))}]}) (defcard "PI:NAME:<NAME>END_PIāju" {:events [{:event :end-of-encounter :req (req (and (same-card? card (:ice context)) (:broken (first (filter :printed (:subroutines (:ice context))))))) :msg "make the Runner continue the run on Archives. Mirāju is derezzed" :effect (req (redirect-run state side "Archives" :approach-ice) (derez state side card))}] :subroutines [{:async true :label "Draw 1 card, then shuffle 1 card from HQ into R&D" :effect (req (wait-for (resolve-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil) (continue-ability state side {:prompt "Choose 1 card in HQ to shuffle into R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "shuffle 1 card in HQ into R&D" :effect (effect (move target :deck) (shuffle! :deck))} card nil)))}]}) (defcard "PI:NAME:<NAME>END_PI" (letfn [(net-or-trash [net-dmg mill-cnt] {:label (str "Do " net-dmg " net damage") :player :runner :waiting-prompt "Runner to choose an option for Mlinzi" :prompt "Take net damage or trash cards from the stack?" :choices (req [(str "Take " net-dmg " net damage") (when (<= mill-cnt (count (:deck runner))) (str "Trash the top " mill-cnt " cards of the stack"))]) :async true :effect (req (if (= target (str "Take " net-dmg " net damage")) (do (system-msg state :corp (str "uses Mlinzi to do " net-dmg " net damage")) (damage state :runner eid :net net-dmg {:card card})) (do (system-msg state :corp (str "uses Mlinzi to trash " (string/join ", " (map :title (take mill-cnt (:deck runner)))) " from the runner's stack")) (mill state :runner eid :runner mill-cnt))))})] {:subroutines [(net-or-trash 1 2) (net-or-trash 2 3) (net-or-trash 3 4)]})) (defcard "PI:NAME:<NAME>END_PI" (let [mg {:req (req (ice? target)) :effect (effect (update-all-subtypes))}] {:constant-effects [{:type :gain-subtype :req (req (same-card? card target)) :value (req (->> (vals (:servers corp)) (mapcat :ices) (filter #(and (rezzed? %) (not (same-card? card %)))) (mapcat :subtypes)))}] :subroutines [end-the-run] :events [{:event :rez :req (req (ice? (:card context))) :effect (effect (update-all-subtypes))} (assoc mg :event :card-moved) (assoc mg :event :derez) (assoc mg :event :ice-subtype-changed)]})) (defcard "PI:NAME:<NAME>END_PI" {:on-rez take-bad-pub :subroutines [(tag-trace 1) (tag-trace 2) (tag-trace 3) end-the-run-if-tagged]}) (defcard "Najja 1.0" {:subroutines [end-the-run end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Nebula" (space-ice trash-program-sub)) (defcard "Negotiator" {:subroutines [(gain-credits-sub 2) trash-program-sub] :runner-abilities [(break-sub [:credit 2] 1)]}) (defcard "Nerine 2.0" (let [sub {:label "Do 1 brain damage and Corp may draw 1 card" :async true :msg "do 1 brain damage" :effect (req (wait-for (damage state :runner :brain 1 {:card card}) (continue-ability state side {:optional {:prompt "Draw 1 card?" :yes-ability {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))}}} card nil)))}] {:subroutines [sub sub] :runner-abilities [(bioroid-break 2 2)]})) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [(do-net-damage 3)]}) (defcard "PI:NAME:<NAME>END_PI" (let [gain-sub {:req (req (and (= 1 (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current"))) :msg "make News Hound gain \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 1 end-the-run {:back true}))} lose-sub {:req (req (and (zero? (count (concat (:current corp) (:current runner)))) (has-subtype? (:card context) "Current") (active? (:card context)))) :msg "make News Hound lose \"[subroutine] End the run\"" :effect (effect (reset-variable-subs card 0 nil))}] {:on-rez {:effect (req (when (pos? (count (concat (get-in @state [:corp :current]) (get-in @state [:runner :current])))) (reset-variable-subs state side card 1 end-the-run {:back true})))} :events [(assoc gain-sub :event :play-event) (assoc gain-sub :event :play-operation) (assoc lose-sub :event :corp-trash) (assoc lose-sub :event :runner-trash) (assoc lose-sub :event :game-trash)] :subroutines [(tag-trace 3)]})) (defcard "NEXT Bronze" {:subroutines [end-the-run] :strength-bonus (req (next-ice-count corp))}) (defcard "NEXT Diamond" {:rez-cost-bonus (req (- (next-ice-count corp))) :subroutines [(do-brain-damage 1) (do-brain-damage 1) {:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (effect (trash eid target {:cause :subroutine}))}]}) (defcard "NEXT Gold" (letfn [(trash-programs [cnt state side card eid] (if (> cnt 0) (wait-for (resolve-ability state side trash-program-sub card nil) (trash-programs (dec cnt) state side card eid)) (effect-completed state side eid)))] {:subroutines [{:label "Do 1 net damage for each rezzed NEXT ice" :msg (msg "do " (next-ice-count corp) " net damage") :effect (effect (damage eid :net (next-ice-count corp) {:card card}))} {:label "Trash 1 program for each rezzed NEXT ice" :async true :effect (req (trash-programs (min (count (filter program? (all-active-installed state :runner))) (next-ice-count corp)) state side card eid))}]})) (defcard "NEXT Opal" (let [sub {:label "Install a card from HQ, paying all costs" :prompt "Choose a card in HQ to install" :req (req (some #(not (operation? %)) (:hand corp))) :choices {:card #(and (not (operation? %)) (in-hand? %) (corp? %))} :async true :effect (effect (corp-install eid target nil nil)) :msg (msg (corp-install-msg target))} ability {:req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}] {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) sub))}]})) (defcard "NEXT Sapphire" {:subroutines [{:label "Draw up to X cards" :prompt "Draw how many cards?" :msg (msg "draw " target " cards") :choices {:number (req (next-ice-count corp)) :default (req 1)} :async true :effect (effect (draw eid target nil))} {:label "Add up to X cards from Archives to HQ" :prompt "Select cards to add to HQ" :show-discard true :choices {:card #(and (corp? %) (in-discard? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state side c :hand))) :msg (msg "add " (let [seen (filter :seen targets) m (count (filter #(not (:seen %)) targets))] (str (string/join ", " (map :title seen)) (when (pos? m) (str (when-not (empty? seen) " and ") (quantify m "unseen card"))))) " to HQ")} {:label "Shuffle up to X cards from HQ into R&D" :prompt "Select cards to shuffle into R&D" :choices {:card #(and (corp? %) (in-hand? %)) :max (req (next-ice-count corp))} :effect (req (doseq [c targets] (move state :corp c :deck)) (shuffle! state :corp :deck)) :cancel-effect (effect (shuffle! :corp :deck)) :msg (msg "shuffle " (count targets) " cards from HQ into R&D")}]}) (defcard "NEXT Silver" {:events [{:event :rez :req (req (and (ice? (:card context)) (has-subtype? (:card context) "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))} {:event :derez :req (req (and (ice? target) (has-subtype? target "NEXT"))) :effect (effect (reset-variable-subs card (next-ice-count corp) end-the-run))}]}) (defcard "Nightdancer" (let [sub {:label (str "The Runner loses [Click], if able. " "You have an additional [Click] to spend during your next turn.") :msg (str "force the runner to lose a [Click], if able. " "Corp gains an additional [Click] to spend during their next turn") :effect (req (lose state :runner :click 1) (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}] {:subroutines [sub sub]})) (defcard "Oduduwa" {:on-encounter {:msg "place 1 advancement counter on Oduduwa" :async true :effect (effect (add-prop card :advance-counter 1 {:placed true}) (continue-ability (let [card (get-card state card) counters (get-counters card :advancement)] {:optional {:prompt (str "Place " (quantify counters "advancement counter") " on another ice?") :yes-ability {:msg (msg "place " (quantify counters "advancement counter") " on " (card-str state target)) :choices {:card ice? :not-self true} :effect (effect (add-prop target :advance-counter counters {:placed true}))}}}) (get-card state card) nil))} :subroutines [end-the-run end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" (space-ice trash-program-sub (resolve-another-subroutine) end-the-run)) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:async true :label "Place 3 advancement tokens on installed card" :msg "place 3 advancement tokens on installed card" :prompt "Choose an installed Corp card" :req (req (some (complement ice?) (all-installed state :corp))) :choices {:card #(and (corp? %) (installed? %) (not (ice? %)))} :effect (req (let [c target title (if (:rezzed c) (:title c) "selected unrezzed card")] (add-counter state side c :advancement 3) (continue-ability state side {:player :runner :async true :waiting-prompt "Runner to resolve Otoroshi" :prompt (str "Access " title " or pay 3 [Credits]?") :choices ["Access card" (when (>= (:credit runner) 3) "Pay 3 [Credits]")] :msg (msg "force the Runner to " (if (= target "Access card") (str "access " title) "pay 3 [Credits]")) :effect (req (if (= target "Access card") (access-card state :runner eid c) (wait-for (pay state :runner card :credit 3) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} card nil)))}]}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:choices {:card #(and (installed? %) (program? %))} :label "Add installed program to the top of the Runner's Stack" :msg "add an installed program to the top of the Runner's Stack" :effect (effect (move :runner target :deck {:front true}) (system-msg (str "adds " (:title target) " to the top of the Runner's Stack")))}]}) (defcard "Pachinko" {:subroutines [end-the-run-if-tagged end-the-run-if-tagged]}) (defcard "Paper Wall" {:events [{:event :subroutines-broken :req (req (and (same-card? card target) (empty? (remove :broken (:subroutines target))))) :async true :effect (effect (trash :corp eid card {:cause :effect}))}] :subroutines [end-the-run]}) (defcard "PI:NAME:<NAME>END_PI" (let [sub (end-the-run-unless-runner "takes 1 tag" "take 1 tag" (give-tags 1))] {:on-encounter {:prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :async true :effect (req (let [n (count (filter #(is-type? % target) (:hand runner)))] (system-msg state side (str "uses Peeping Tom to name " target ", then reveals " (string/join ", " (map :title (:hand runner))) " in the Runner's Grip. Peeping Tom gains " n " subroutines")) (wait-for (reveal state side (:hand runner)) (gain-variable-subs state side card n sub) (effect-completed state side eid))))} :events [{:event :run-ends :effect (effect (reset-variable-subs card 0 nil))}]})) (defcard "Pop-up Window" {:on-encounter (gain-credits-sub 1) :subroutines [(end-the-run-unless-runner-pays 1)]}) (defcard "Pup" (let [sub {:player :runner :async true :label (str "Do 1 net damage unless the Runner pays 1 [Credits]") :prompt (str "Suffer 1 net damage or pay 1 [Credits]?") :choices ["Suffer 1 net damage" "Pay 1 [Credits]"] :effect (req (if (= "Suffer 1 net damage" target) (continue-ability state :corp (do-net-damage 1) card nil) (wait-for (pay state :runner card [:credit 1]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))}] {:subroutines [sub sub]})) (defcard "Quandary" {:subroutines [end-the-run]}) (defcard "Quicksand" {:on-encounter {:msg "add 1 power counter to Quicksand" :effect (effect (add-counter card :power 1) (update-all-ice))} :subroutines [end-the-run] :strength-bonus (req (get-counters card :power))}) (defcard "Rainbow" {:subroutines [end-the-run]}) (defcard "Ravana 1.0" (let [sub (resolve-another-subroutine #(has-subtype? % "Bioroid") "Resolve a subroutine on a rezzed bioroid ice")] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Red Tape" {:subroutines [{:label "Give +3 strength to all ICE for the remainder of the run" :msg "give +3 strength to all ICE for the remainder of the run" :effect (effect (pump-all-ice 3 :end-of-run))}]}) (defcard "Resistor" {:strength-bonus (req (count-tags state)) :subroutines [(trace-ability 4 end-the-run)]}) (defcard "Rime" {:implementation "Can be rezzed anytime already" :on-rez {:effect (effect (update-all-ice))} :subroutines [{:label "Runner loses 1 [Credit]" :msg "force the Runner to lose 1 [Credit]" :async true :effect (effect (lose-credits :runner eid 1))}] :constant-effects [{:type :ice-strength :req (req (protecting-same-server? card target)) :value 1}]}) (defcard "Rototurret" {:subroutines [trash-program-sub end-the-run]}) (defcard "Sadaka" (let [maybe-draw-effect {:optional {:player :corp :waiting-prompt "Corp to decide on Sadaka card draw action" :prompt "Draw 1 card?" :yes-ability {:async true :effect (effect (draw eid 1 nil)) :msg "draw 1 card"}}}] {:subroutines [{:label "Look at the top 3 cards of R&D" :req (req (not-empty (:deck corp))) :async true :effect (effect (continue-ability (let [top-cards (take 3 (:deck corp)) top-names (map :title top-cards)] {:waiting-prompt "Corp to decide on Sadaka R&D card actions" :prompt (str "Top 3 cards of R&D: " (string/join ", " top-names)) :choices ["Arrange cards" "Shuffle R&D"] :async true :effect (req (if (= target "Arrange cards") (wait-for (resolve-ability state side (reorder-choice :corp top-cards) card nil) (system-msg state :corp (str "rearranges the top " (quantify (count top-cards) "card") " of R&D")) (continue-ability state side maybe-draw-effect card nil)) (do (shuffle! state :corp :deck) (system-msg state :corp (str "shuffles R&D")) (continue-ability state side maybe-draw-effect card nil))))}) card nil))} {:label "Trash 1 card in HQ" :async true :effect (req (wait-for (resolve-ability state side {:waiting-prompt "Corp to select cards to trash with Sadaka" :prompt "Choose a card in HQ to trash" :choices (req (cancellable (:hand corp) :sorted)) :async true :cancel-effect (effect (system-msg "chooses not to trash a card from HQ") (effect-completed eid)) :effect (req (wait-for (trash state :corp target {:cause :subroutine}) (system-msg state :corp "trashes a card from HQ") (continue-ability state side trash-resource-sub card nil)))} card nil) (when current-ice (continue state :corp nil) (continue state :runner nil)) (system-msg state :corp "trashes Sadaka") (trash state :corp eid card nil)))}]})) (defcard "Sagittarius" (constellation-ice trash-program-sub)) (defcard "Saisentan" (let [sub {:label "Do 1 net damage" :async true :msg "do 1 net damage" :effect (req (wait-for (damage state side :net 1 {:card card}) (let [choice (get-in card [:special :saisentan]) cards async-result dmg (some #(when (= (:type %) choice) %) cards)] (if dmg (do (system-msg state :corp "uses Saisentan to deal a second net damage") (damage state side eid :net 1 {:card card})) (effect-completed state side eid)))))}] {:on-encounter {:waiting-prompt "Corp to choose Saisentan card type" :prompt "Choose a card type" :choices ["Event" "Hardware" "Program" "Resource"] :msg (msg "choose the card type " target) :effect (effect (update! (assoc-in card [:special :saisentan] target)))} :events [{:event :end-of-encounter :req (req (get-in card [:special :saisentan])) :effect (effect (update! (dissoc-in card [:special :saisentan])))}] :subroutines [sub sub sub]})) (defcard "Salvage" (zero-to-hero (tag-trace 2))) (defcard "Sand Storm" {:subroutines [{:async true :label "Move Sand Storm and the run to another server" :prompt "Choose another server and redirect the run to its outermost position" :choices (req (remove #{(zone->name (:server (:run @state)))} (cancellable servers))) :msg (msg "move Sand Storm and the run. The Runner is now running on " target ". Sand Storm is trashed") :effect (effect (redirect-run target :approach-ice) (trash eid card {:unpreventable true :cause :subroutine}))}]}) (defcard "Sandstone" {:subroutines [end-the-run] :strength-bonus (req (- (get-counters card :virus))) :on-encounter {:msg "place 1 virus counter on Sandstone" :effect (effect (add-counter card :virus 1) (update-ice-strength (get-card state card)))}}) (defcard "Sandman" {:subroutines [add-runner-card-to-grip add-runner-card-to-grip]}) (defcard "Sapper" {:flags {:rd-reveal (req true)} :subroutines [trash-program-sub] :access {:async true :optional {:req (req (and (not (in-discard? card)) (some program? (all-active-installed state :runner)))) :player :runner :waiting-prompt "Runner to decide to break Sapper subroutine" :prompt "Allow Sapper subroutine to fire?" :yes-ability {:async true :effect (effect (resolve-unbroken-subs! :corp eid card))}}}}) (defcard "Searchlight" (let [sub {:label "Trace X - Give the Runner 1 tag" :trace {:base (req (get-counters card :advancement)) :label "Give the Runner 1 tag" :successful (give-tags 1)}}] {:advanceable :always :subroutines [sub sub]})) (defcard "Seidr Adaptive Barrier" {:strength-bonus (req (count (:ices (card->server state card)))) :subroutines [end-the-run]}) (defcard "Self-Adapting Code Wall" {:subroutines [end-the-run] :flags {:cannot-lower-strength true}}) (defcard "Sensei" {:subroutines [{:label "Give encountered ice \"End the run\"" :msg (msg "give encountered ice \"[Subroutine] End the run\" after all its other subroutines for the remainder of the run") :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :req (req (not (same-card? card (:ice context)))) :msg (msg "give " (:title (:ice context)) "\"[Subroutine] End the run\" after all its other subroutines") :effect (effect (add-sub! (:ice context) end-the-run (:cid card) {:back true}))} {:event :end-of-encounter :duration :end-of-run :effect (effect (remove-sub! (:ice context) #(= (:cid card) (:from-cid %))))}]))}]}) (defcard "Shadow" (wall-ice [(gain-credits-sub 2) (tag-trace 3)])) (defcard "Sherlock 1.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the top of the Runner's Stack" :msg (msg "add " (:title target) " to the top of the Runner's Stack") :effect (effect (move :runner target :deck {:front true}))})] {:subroutines [sub sub] :runner-abilities [(bioroid-break 1 1)]})) (defcard "Sherlock 2.0" (let [sub (trace-ability 4 {:choices {:card #(and (installed? %) (program? %))} :label "Add an installed program to the bottom of the Runner's Stack" :msg (msg "add " (:title target) " to the bottom of the Runner's Stack") :effect (effect (move :runner target :deck))})] {:subroutines [sub sub (give-tags 1)] :runner-abilities [(bioroid-break 2 2)]})) (defcard "ShPI:NAME:<NAME>END_PI" {:on-rez take-bad-pub :subroutines [(trace-ability 1 (do-net-damage 1)) (trace-ability 2 (do-net-damage 2)) (trace-ability 3 {:label "Do 3 net damage and end the run" :msg "do 3 net damage and end the run" :effect (req (wait-for (damage state side :net 3 {:card card}) (end-run state side eid card)))})]}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:label "Rearrange the top 3 cards of R&D" :msg "rearrange the top 3 cards of R&D" :async true :waiting-prompt "Corp to rearrange the top cards of R&D" :effect (effect (continue-ability (let [from (take 3 (:deck corp))] (when (pos? (count from)) (reorder-choice :corp :runner from '() (count from) from))) card nil))} {:optional {:prompt "Pay 1 [Credits] to keep the Runner from accessing the top card of R&D?" :yes-ability {:cost [:credit 1] :msg "keep the Runner from accessing the top card of R&D"} :no-ability {:async true :msg "make the Runner access the top card of R&D" :effect (effect (do-access :runner eid [:rd] {:no-root true}))}}}]}) (defcard "Slot Machine" (letfn [(top-3 [state] (take 3 (get-in @state [:runner :deck]))) (effect-type [card] (keyword (str "slot-machine-top-3-" (:cid card)))) (name-builder [card] (str (:title card) " (" (:type card) ")")) (top-3-names [cards] (map name-builder cards)) (top-3-types [state card et] (->> (get-effects state :corp card et) first (keep :type) (into #{}) count)) (ability [] {:label "Encounter ability (manual)" :async true :effect (req (move state :runner (first (:deck runner)) :deck) (let [t3 (top-3 state) effect-type (effect-type card)] (register-floating-effect state side card {:type effect-type :duration :end-of-encounter :value t3}) (system-msg state side (str "uses Slot Machine to put the top card of the stack to the bottom," " then reveal the top 3 cards in the stack: " (string/join ", " (top-3-names t3)))) (reveal state side eid t3)))})] {:on-encounter (ability) :abilities [(ability)] :subroutines [{:label "Runner loses 3 [Credits]" :msg "force the Runner to lose 3 [Credits]" :async true :effect (effect (lose-credits :runner eid 3))} {:label "Gain 3 [Credits]" :async true :effect (req (let [et (effect-type card) unique-types (top-3-types state card et)] ;; When there are 3 cards in the deck, sub needs 2 or fewer unique types ;; When there are 2 cards in the deck, sub needs 1 unique type (if (or (and (<= unique-types 2) (= 3 (count (first (get-effects state :corp card et))))) (and (= unique-types 1) (= 2 (count (first (get-effects state :corp card et)))))) (do (system-msg state :corp (str "uses Slot Machine to gain 3 [Credits]")) (gain-credits state :corp eid 3)) (effect-completed state side eid))))} {:label "Place 3 advancement tokens" :async true :effect (effect (continue-ability (let [et (effect-type card) unique-types (top-3-types state card et)] (when (and (= 3 (count (first (get-effects state :corp card et)))) (= 1 unique-types)) {:choices {:card installed?} :prompt "Choose an installed card" :msg (msg "place 3 advancement tokens on " (card-str state target)) :effect (effect (add-prop target :advance-counter 3 {:placed true}))})) card nil))}]})) (defcard "Snoop" {:on-encounter {:msg (msg "reveal the Runner's Grip (" (string/join ", " (map :title (:hand runner))) ")") :async true :effect (effect (reveal eid (:hand runner)))} :abilities [{:async true :req (req (pos? (get-counters card :power))) :cost [:power 1] :label "Reveal all cards in Grip and trash 1 card" :msg (msg "look at all cards in Grip and trash " (:title target) " using 1 power counter") :choices (req (cancellable (:hand runner) :sorted)) :prompt "Choose a card to trash" :effect (effect (reveal (:hand runner)) (trash eid target {:cause :subroutine}))}] :subroutines [(trace-ability 3 add-power-counter)]}) (defcard "Snowflake" {:subroutines [(do-psi end-the-run)]}) (defcard "Special Offer" {:subroutines [{:label "Gain 5 [Credits] and trash Special Offer" :msg "gains 5 [Credits] and trashes Special Offer" :async true :effect (req (wait-for (gain-credits state :corp 5) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})))}]}) (defcard "Spiderweb" {:subroutines [end-the-run end-the-run end-the-run]}) (defcard "Surveyor" (let [x (req (* 2 (count (:ices (card->server state card)))))] {:strength-bonus x :subroutines [{:label "Trace X - Give the Runner 2 tags" :trace {:base x :label "Give the Runner 2 tags" :successful (give-tags 2)}} {:label "Trace X - End the run" :trace {:base x :label "End the run" :successful end-the-run}}]})) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [{:req (req (not= (:server run) [:discard])) :msg "make the Runner continue the run on Archives" :effect (req (redirect-run state side "Archives" :approach-ice) (register-events state side card [{:event :approach-ice :duration :end-of-run :unregister-once-resolved true :msg "prevent the runner from jacking out" :effect (req (prevent-jack-out state side) (register-events state side card [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :effect (req (swap! state update :run dissoc :cannot-jack-out))}]))}]))}]}) (defcard "Swarm" (let [sub {:player :runner :async true :label "Trash a program" :prompt "Let Corp trash 1 program or pay 3 [Credits]?" :choices ["Corp trash" "Pay 3 [Credits]"] :effect (req (if (= "Corp trash" target) (continue-ability state :corp trash-program-sub card nil) (wait-for (pay state :runner card [:credit 3]) (system-msg state :runner (:msg async-result)) (effect-completed state side eid))))} ability {:req (req (same-card? card target)) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}] {:advanceable :always :on-rez take-bad-pub :events [(assoc ability :event :advance) (assoc ability :event :advancement-placed) {:event :rez :req (req (same-card? card (:card context))) :effect (effect (reset-variable-subs card (get-counters card :advancement) sub))}]})) (defcard "PI:NAME:<NAME>END_PI" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [{:async true :breakable breakable-fn :prompt "Select an AI program to trash" :msg (msg "trash " (:title target)) :label "Trash an AI program" :choices {:card #(and (installed? %) (program? %) (has-subtype? % "AI"))} :effect (effect (trash eid target {:cause :subroutine}))} (assoc (do-net-damage 1) :breakable breakable-fn)]})) (defcard "SYNC BRE" {:subroutines [(tag-trace 4) (trace-ability 2 {:label "Runner reduces cards accessed by 1 for this run" :async true :msg "reduce cards accessed for this run by 1" :effect (effect (access-bonus :total -1))})]}) (defcard "Tapestry" {:subroutines [runner-loses-click {:async true :msg "draw 1 card" :effect (effect (draw eid 1 nil))} {:req (req (pos? (count (:hand corp)))) :prompt "Choose a card in HQ to move to the top of R&D" :choices {:card #(and (in-hand? %) (corp? %))} :msg "add 1 card in HQ to the top of R&D" :effect (effect (move target :deck {:front true}))}]}) (defcard "Taurus" (constellation-ice trash-hardware-sub)) (defcard "Thimblerig" (let [ability {:optional {:req (req (and (<= 2 (count (filter ice? (all-installed state :corp)))) (if run (same-card? (:ice context) card) true))) :prompt "Swap Thimblerig with another ice?" :yes-ability {:prompt "Choose a piece of ice to swap Thimblerig with" :choices {:card ice? :not-self true} :effect (effect (swap-ice card target)) :msg (msg "swap " (card-str state card) " with " (card-str state target))}}}] {:events [(assoc ability :event :pass-ice) (assoc ability :event :corp-turn-begins)] :subroutines [end-the-run]})) (defcard "Thoth" {:on-encounter (give-tags 1) :subroutines [(trace-ability 4 {:label "Do 1 net damage for each Runner tag" :async true :msg (msg "do " (count-tags state) " net damage") :effect (effect (damage eid :net (count-tags state) {:card card}))}) (trace-ability 4 {:label "Runner loses 1 [Credits] for each tag" :async true :msg (msg "force the Runner to lose " (count-tags state) " [Credits]") :effect (effect (lose-credits :runner eid (count-tags state)))})]}) (defcard "Tithonium" {:alternative-cost [:forfeit] :cannot-host true :subroutines [trash-program-sub trash-program-sub {:label "Trash a resource and end the run" :async true :effect (req (wait-for (resolve-ability state side {:req (req (pos? (count (filter resource? (all-installed state :runner))))) :async true :choices {:all true :card #(and (installed? %) (resource? %))} :effect (req (wait-for (trash state side target {:cause :subroutine}) (complete-with-result state side eid target)))} card nil) (system-msg state side (str "uses Tithonium to " (if async-result (str "trash " (:title async-result) " and ends the run") "end the run"))) (end-run state side eid card)))}]}) (defcard "TL;DR" {:subroutines [{:label "Double subroutines on an ICE" :effect (effect (register-events card [{:event :encounter-ice :duration :end-of-run :unregister-once-resolved true :msg (msg "duplicate each subroutine on " (:title (:ice context))) :effect (req (let [curr-subs (map #(assoc % :from-cid (:cid (:ice context))) (:subroutines (:ice context))) tldr-subs (map #(assoc % :from-cid (:cid card)) curr-subs) new-subs (->> (interleave curr-subs tldr-subs) (reduce (fn [ice sub] (add-sub ice sub (:from-cid sub) nil)) (assoc (:ice context) :subroutines [])) :subroutines (into [])) new-card (assoc (:ice context) :subroutines new-subs)] (update! state :corp new-card) (register-events state side card (let [cid (:cid card)] [{:event :end-of-encounter :duration :end-of-encounter :unregister-once-resolved true :req (req (get-card state new-card)) :effect (effect (remove-subs! (get-card state new-card) #(= cid (:from-cid %))))}]))))}]))}]}) (defcard "TMI" {:on-rez {:trace {:base 2 :msg "keep TMI rezzed" :label "Keep TMI rezzed" :unsuccessful {:effect (effect (derez card))}}} :subroutines [end-the-run]}) (defcard "Tollbooth" {:on-encounter {:async true :effect (req (wait-for (pay state :runner card [:credit 3]) (if (:cost-paid async-result) (do (system-msg state :runner (str (:msg async-result) " when encountering Tollbooth")) (effect-completed state side eid)) (do (system-msg state :runner "ends the run, as the Runner can't pay 3 [Credits] when encountering Tollbooth") (end-run state :corp eid card)))))} :subroutines [end-the-run]}) (defcard "Tour Guide" (let [ef (effect (reset-variable-subs card (count (filter asset? (all-active-installed state :corp))) end-the-run)) ability {:label "Reset number of subs" :silent (req true) :req (req (asset? target)) :effect ef} trash-req (req (and (asset? (:card target)) (installed? (:card target)) (rezzed? (:card target))))] {:on-rez {:effect ef} :events [{:event :rez :label "Reset number of subs" :silent (req true) :req (req (asset? (:card context))) :effect ef} (assoc ability :event :derez) (assoc ability :event :game-trash :req trash-req) (assoc ability :event :corp-trash :req trash-req) (assoc ability :event :runner-trash :req trash-req)]})) (defcard "Trebuchet" {:on-rez take-bad-pub :subroutines [{:prompt "Select a card to trash" :label "Trash 1 installed Runner card" :msg (msg "trash " (:title target)) :choices {:card #(and (installed? %) (runner? %))} :async true :effect (req (trash state side eid target {:cause :subroutine}))} (trace-ability 6 {:label "The Runner cannot steal or trash Corp cards for the remainder of this run" :msg "prevent the Runner from stealing or trashing Corp cards for the remainder of the run" :effect (req (register-run-flag! state side card :can-steal (fn [state side card] ((constantly false) (toast state :runner "Cannot steal due to Trebuchet." "warning")))) (register-run-flag! state side card :can-trash (fn [state side card] ((constantly (not= (:side card) "Corp")) (toast state :runner "Cannot trash due to Trebuchet." "warning")))))})]}) (defcard "Tribunal" {:subroutines [runner-trash-installed-sub runner-trash-installed-sub runner-trash-installed-sub]}) (defcard "Troll" {:on-encounter (trace-ability 2 {:msg "force the Runner to lose [Click] or end the run" :player :runner :prompt "Choose one" :choices ["Lose [Click]" "End the run"] :async true :effect (req (if (and (= target "Lose [Click]") (can-pay? state :runner (assoc eid :source card :source-type :subroutine) card nil [:click 1])) (do (system-msg state :runner "loses [Click]") (lose state :runner :click 1) (effect-completed state :runner eid)) (do (system-msg state :corp "ends the run") (end-run state :corp eid card))))})}) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [(end-the-run-unless-corp-pays 1) (do-net-damage 1) (do-net-damage 1) (do-net-damage 1)]}) (defcard "PI:NAME:<NAME>END_PI" (let [breakable-fn (req (when-not (has-subtype? target "AI") :unrestricted))] {:subroutines [(assoc (end-the-run-unless-runner "spends [Click][Click][Click]" "spend [Click][Click][Click]" (runner-pays [:click 3])) :breakable breakable-fn)] :strength-bonus (req (if (is-remote? (second (get-zone card))) 3 0))})) (defcard "PI:NAME:<NAME>END_PIpiPI:NAME:<NAME>END_PI" {:on-encounter {:msg "force the Runner to lose 1 [Credits]" :async true :effect (effect (lose-credits :runner eid 1))} :subroutines [(tag-trace 5)]}) (defcard "PI:NAME:<NAME>END_PI" (zero-to-hero end-the-run)) (defcard "PI:NAME:<NAME>END_PI" {:subroutines [(do-brain-damage 2) (combine-abilities trash-installed-sub (gain-credits-sub 3)) end-the-run] :runner-abilities [(bioroid-break 1 1 {:additional-ability {:effect (req (swap! state update-in [:corp :extra-click-temp] (fnil inc 0)))}})]}) (defcard "Universal Connectivity Fee" {:subroutines [{:label "Force the Runner to lose credits" :msg (msg "force the Runner to lose " (if tagged "all credits" "1 [Credits]")) :async true :effect (req (if tagged (wait-for (lose-credits state :runner :all) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine})) (lose-credits state :runner eid 1)))}]}) (defcard "Upayoga" {:subroutines [(do-psi {:label "Make the Runner lose 2 [Credits]" :msg "make the Runner lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))}) (resolve-another-subroutine #(has-subtype? % "Psi") "Resolve a subroutine on a rezzed psi ice")]}) (defcard "Uroboros" {:subroutines [(trace-ability 4 {:label "Prevent the Runner from making another run" :msg "prevent the Runner from making another run" :effect (effect (register-turn-flag! card :can-run nil))}) (trace-ability 4 end-the-run)]}) (defcard "Vanilla" {:subroutines [end-the-run]}) (defcard "Veritas" {:subroutines [{:label "Corp gains 2 [Credits]" :msg "gain 2 [Credits]" :async true :effect (effect (gain-credits :corp eid 2))} {:label "Runner loses 2 [Credits]" :msg "force the Runner to lose 2 [Credits]" :async true :effect (effect (lose-credits :runner eid 2))} (trace-ability 2 (give-tags 1))]}) (defcard "Vikram 1.0" {:implementation "Program prevention is not implemented" :subroutines [{:msg "prevent the Runner from using programs for the remainder of this run"} (trace-ability 4 (do-brain-damage 1)) (trace-ability 4 (do-brain-damage 1))] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 1.0" {:subroutines [(do-brain-damage 1) end-the-run] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Viktor 2.0" {:abilities [(power-counter-ability (do-brain-damage 1))] :subroutines [(trace-ability 2 add-power-counter) end-the-run] :runner-abilities [(bioroid-break 2 2)]}) (defcard "Viper" {:subroutines [(trace-ability 3 runner-loses-click) (trace-ability 3 end-the-run)]}) (defcard "PI:NAME:<NAME>END_PIirgo" (constellation-ice (give-tags 1))) (defcard "Waiver" {:subroutines [(trace-ability 5 {:label "Reveal the grip and trash cards" :msg (msg "reveal all cards in the grip: " (string/join ", " (map :title (:hand runner)))) :async true :effect (req (wait-for (reveal state side (:hand runner)) (let [delta (- target (second targets)) cards (filter #(<= (:cost %) delta) (:hand runner))] (system-msg state side (str "uses Waiver to trash " (string/join ", " (map :title cards)))) (trash-cards state side eid cards {:cause :subroutine}))))})]}) (defcard "Wall of Static" {:subroutines [end-the-run]}) (defcard "Wall of Thorns" {:subroutines [(do-net-damage 2) end-the-run]}) (defcard "Watchtower" {:subroutines [{:label "Search R&D and add 1 card to HQ" :prompt "Choose a card to add to HQ" :msg "add a card from R&D to HQ" :choices (req (cancellable (:deck corp) :sorted)) :cancel-effect (effect (system-msg "cancels the effect of Watchtower")) :effect (effect (shuffle! :deck) (move target :hand))}]}) (defcard "Weir" {:subroutines [runner-loses-click {:label "Runner trashes 1 card from their Grip" :req (req (pos? (count (:hand runner)))) :prompt "Choose a card to trash from your Grip" :player :runner :choices (req (:hand runner)) :not-distinct true :async true :effect (effect (system-msg :runner (str "trashes " (:title target) " from their Grip")) (trash :runner eid target {:cause :subroutine}))}]}) (defcard "Wendigo" (implementation-note "Program prevention is not implemented" (morph-ice "Code Gate" "Barrier" {:msg "prevent the Runner from using a chosen program for the remainder of this run"}))) (defcard "Whirlpool" {:subroutines [{:label "The Runner cannot jack out for the remainder of this run" :msg "prevent the Runner from jacking out" :async true :effect (req (prevent-jack-out state side) (when current-ice (continue state :corp nil) (continue state :runner nil)) (trash state side eid card {:cause :subroutine}))}]}) (defcard "Winchester" (let [ab {:req (req (protecting-hq? card)) :effect (req (reset-variable-subs state :corp card 1 (trace-ability 3 end-the-run) {:back true}))}] {:subroutines [(trace-ability 4 trash-program-sub) (trace-ability 3 trash-hardware-sub)] :on-rez {:effect (effect (continue-ability ab card nil))} :events [(assoc ab :event :rez) (assoc ab :event :card-moved) (assoc ab :event :approach-ice) (assoc ab :event :swap :req (req (or (protecting-hq? target) (protecting-hq? (second targets)))))]})) (defcard "Woodcutter" (zero-to-hero (do-net-damage 1))) (defcard "Wormhole" (space-ice (resolve-another-subroutine))) (defcard "Wotan" {:subroutines [(end-the-run-unless-runner "spends [Click][Click]" "spend [Click][Click]" (runner-pays [:click 2])) (end-the-run-unless-runner-pays 3) (end-the-run-unless-runner "trashes an installed program" "trash an installed program" trash-program-sub) (end-the-run-unless-runner "takes 1 brain damage" "take 1 brain damage" (do-brain-damage 1))]}) (defcard "Wraparound" {:subroutines [end-the-run] :strength-bonus (req (if (some #(has-subtype? % "Fracter") (all-active-installed state :runner)) 0 7))}) (defcard "Yagura" {:subroutines [{:msg "look at the top card of R&D" :optional {:prompt (msg "Move " (:title (first (:deck corp))) " to the bottom of R&D?") :yes-ability {:msg "move the top card of R&D to the bottom" :effect (effect (move (first (:deck corp)) :deck))} :no-ability {:effect (effect (system-msg :corp (str "does not use Yagura to move the top card of R&D to the bottom")))}}} (do-net-damage 1)]}) (defcard "Zed 1.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [(do-brain-damage 1) (do-brain-damage 1)] :runner-abilities [(bioroid-break 1 1)]}) (defcard "Zed 2.0" {:implementation "Restriction on having spent [click] is not implemented" :subroutines [trash-hardware-sub trash-hardware-sub (do-brain-damage 2)] :runner-abilities [(bioroid-break 2 2)]})
[ { "context": " Person {:person/id 1\n :person/name \"Joe\"})\n\n (app/current-state app)\n ;=> #:person{:id ", "end": 802, "score": 0.9997965693473816, "start": 799, "tag": "NAME", "value": "Joe" }, { "context": "app)\n ;=> #:person{:id {1 #:person{:id 1, :name \"Joe\"}}}\n\n ; the tree data is put into a table\n\n (me", "end": 881, "score": 0.9998037219047546, "start": 878, "tag": "NAME", "value": "Joe" }, { "context": " Person {:person/id 2\n :person/name \"Sally\"})\n\n (app/current-state app)\n ;=> #:person{:id ", "end": 1012, "score": 0.9997952580451965, "start": 1007, "tag": "NAME", "value": "Sally" }, { "context": "app)\n ;=> #:person{:id {1 #:person{:id 1, :name \"Joe\"}, 2 #:person{:id 2, :name \"Sally\"}}}\n\n ; this f", "end": 1091, "score": 0.9998053312301636, "start": 1088, "tag": "NAME", "value": "Joe" }, { "context": "son{:id 1, :name \"Joe\"}, 2 #:person{:id 2, :name \"Sally\"}}}\n\n ; this function is accumulative\n\n (app/sc", "end": 1125, "score": 0.9998193979263306, "start": 1120, "tag": "NAME", "value": "Sally" }, { "context": "chedule-render! app)\n ; check web page:\n ; Name: Joe\n (+ 1),)\n", "end": 1228, "score": 0.9997276663780212, "start": 1225, "tag": "NAME", "value": "Joe" } ]
clj/ex/fulcro/src/app/app00f.cljs
mertnuhoglu/study
1
(ns app.app00f (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.algorithms.merge :as merge])) ; video: Part 2 ; Normalize the tree 01 ; 14:40 (defonce app (app/fulcro-app)) (defsc Person [this {:person/keys [id name ] :as props}] {:query [:person/id :person/name] :ident :person/id} (dom/div (dom/div "Name: " name))) (def ui-person (comp/factory Person {:keyfn :person/id})) (defsc Sample [this {:keys [sample]}] {} (dom/div (ui-person sample))) (comment (in-ns 'app.app00f) (app/mount! app Sample "app") (reset! (::app/state-atom app) {}) (merge/merge-component! app Person {:person/id 1 :person/name "Joe"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "Joe"}}} ; the tree data is put into a table (merge/merge-component! app Person {:person/id 2 :person/name "Sally"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "Joe"}, 2 #:person{:id 2, :name "Sally"}}} ; this function is accumulative (app/schedule-render! app) ; check web page: ; Name: Joe (+ 1),)
5610
(ns app.app00f (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.algorithms.merge :as merge])) ; video: Part 2 ; Normalize the tree 01 ; 14:40 (defonce app (app/fulcro-app)) (defsc Person [this {:person/keys [id name ] :as props}] {:query [:person/id :person/name] :ident :person/id} (dom/div (dom/div "Name: " name))) (def ui-person (comp/factory Person {:keyfn :person/id})) (defsc Sample [this {:keys [sample]}] {} (dom/div (ui-person sample))) (comment (in-ns 'app.app00f) (app/mount! app Sample "app") (reset! (::app/state-atom app) {}) (merge/merge-component! app Person {:person/id 1 :person/name "<NAME>"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "<NAME>"}}} ; the tree data is put into a table (merge/merge-component! app Person {:person/id 2 :person/name "<NAME>"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "<NAME>"}, 2 #:person{:id 2, :name "<NAME>"}}} ; this function is accumulative (app/schedule-render! app) ; check web page: ; Name: <NAME> (+ 1),)
true
(ns app.app00f (:require [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom] [com.fulcrologic.fulcro.application :as app] [com.fulcrologic.fulcro.algorithms.merge :as merge])) ; video: Part 2 ; Normalize the tree 01 ; 14:40 (defonce app (app/fulcro-app)) (defsc Person [this {:person/keys [id name ] :as props}] {:query [:person/id :person/name] :ident :person/id} (dom/div (dom/div "Name: " name))) (def ui-person (comp/factory Person {:keyfn :person/id})) (defsc Sample [this {:keys [sample]}] {} (dom/div (ui-person sample))) (comment (in-ns 'app.app00f) (app/mount! app Sample "app") (reset! (::app/state-atom app) {}) (merge/merge-component! app Person {:person/id 1 :person/name "PI:NAME:<NAME>END_PI"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "PI:NAME:<NAME>END_PI"}}} ; the tree data is put into a table (merge/merge-component! app Person {:person/id 2 :person/name "PI:NAME:<NAME>END_PI"}) (app/current-state app) ;=> #:person{:id {1 #:person{:id 1, :name "PI:NAME:<NAME>END_PI"}, 2 #:person{:id 2, :name "PI:NAME:<NAME>END_PI"}}} ; this function is accumulative (app/schedule-render! app) ; check web page: ; Name: PI:NAME:<NAME>END_PI (+ 1),)
[ { "context": ";;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio", "end": 32, "score": 0.9998077750205994, "start": 19, "tag": "NAME", "value": "David Edwards" } ]
src/rpn/parser.clj
davidledwards/rpn-clojure
1
;;; Copyright 2020 David Edwards ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser "Parser. p0 ::= <p2> <p1> p1 ::= '+' <p2> <p1> ::= '-' <p2> <p1> ::= e p2 ::= <p4> <p3> p3 ::= '*' <p4> <p3> ::= '/' <p4> <p3> ::= '%' <p4> <p3> ::= '^' <p4> <p3> ::= e p4 ::= <p6> <p5> p5 ::= 'min' <p6> <p5> ::= 'max' <p6> <p5> ::= e p6 ::= '(' <p0> ')' ::= <symbol> ::= <number>" (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.ast :as ast])) (defn- effective-lexeme [token] (token/lexeme (or token token/EOS-token))) (defn- match [in token] (let [t (first in)] (if (token/same-kind? t token) (rest in) (throw (Exception. (str (effective-lexeme t) ": expecting '" (token/lexeme token) "'")))))) (declare p0) ;; ;; p6 ::= '(' <p0> ')' ;; ::= <symbol> ;; ::= <number> ;; (defn- p6 [in] (let [t (first in)] (case (token/kind t) :left-paren (let [[ast in-rest] (p0 (rest in))] [ast (match in-rest token/right-paren-token)]) :symbol [(ast/symbol-AST (token/lexeme t)) (rest in)] :number [(ast/number-AST (Double/parseDouble (token/lexeme t))) (rest in)] (throw (Exception. (str (effective-lexeme t) ": expecting '{', <symbol> or <number>")))))) (def ^:private p5-ops {:min ast/min-AST :max ast/max-AST}) ;; ;; p5 ::= 'min' <p6> <p5> ;; ::= 'max' <p6> <p5> ;; ::= e ;; (defn- p5 [l in] (if-let [op (p5-ops (token/kind (first in)))] (let [[r in-rest] (p6 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p4 ::= <p6> <p5> ;; (defn- p4 [in] (let [[l in-rest] (p6 in)] (p5 l in-rest))) (def ^:private p3-ops {:star ast/multiply-AST :slash ast/divide-AST :percent ast/modulo-AST :caret ast/power-AST}) ;; ;; p3 ::= '*' <p4> <p3> ;; ::= '/' <p4> <p3> ;; ::= '%' <p4> <p3> ;; ::= '^' <p4> <p3> ;; ::= e ;; (defn- p3 [l in] (if-let [op (p3-ops (token/kind (first in)))] (let [[r in-rest] (p4 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p2 ::= <p4> <p3> ;; (defn- p2 [in] (let [[l in-rest] (p4 in)] (p3 l in-rest))) (def ^:private p1-ops {:plus ast/add-AST :minus ast/subtract-AST}) ;; ;; p1 ::= '+' <p2> <p1> ;; ::= '-' <p2> <p1> ;; ::= e ;; (defn- p1 [l in] (if-let [op (p1-ops (token/kind (first in)))] (let [[r in-rest] (p2 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p0 ::= <p2> <p1> ;; (defn- p0 [in] (let [[l in-rest] (p2 in)] (p1 l in-rest))) (defn parser "A recursive-descent parser that transforms a sequence of tokens from `in` into an AST." [in] (let [[ast in-rest] (p0 in) t (first in-rest)] (if (nil? t) ast (throw (Exception. (str (token/lexeme t) ": expecting " (token/lexeme token/EOS-token)))))))
23335
;;; Copyright 2020 <NAME> ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser "Parser. p0 ::= <p2> <p1> p1 ::= '+' <p2> <p1> ::= '-' <p2> <p1> ::= e p2 ::= <p4> <p3> p3 ::= '*' <p4> <p3> ::= '/' <p4> <p3> ::= '%' <p4> <p3> ::= '^' <p4> <p3> ::= e p4 ::= <p6> <p5> p5 ::= 'min' <p6> <p5> ::= 'max' <p6> <p5> ::= e p6 ::= '(' <p0> ')' ::= <symbol> ::= <number>" (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.ast :as ast])) (defn- effective-lexeme [token] (token/lexeme (or token token/EOS-token))) (defn- match [in token] (let [t (first in)] (if (token/same-kind? t token) (rest in) (throw (Exception. (str (effective-lexeme t) ": expecting '" (token/lexeme token) "'")))))) (declare p0) ;; ;; p6 ::= '(' <p0> ')' ;; ::= <symbol> ;; ::= <number> ;; (defn- p6 [in] (let [t (first in)] (case (token/kind t) :left-paren (let [[ast in-rest] (p0 (rest in))] [ast (match in-rest token/right-paren-token)]) :symbol [(ast/symbol-AST (token/lexeme t)) (rest in)] :number [(ast/number-AST (Double/parseDouble (token/lexeme t))) (rest in)] (throw (Exception. (str (effective-lexeme t) ": expecting '{', <symbol> or <number>")))))) (def ^:private p5-ops {:min ast/min-AST :max ast/max-AST}) ;; ;; p5 ::= 'min' <p6> <p5> ;; ::= 'max' <p6> <p5> ;; ::= e ;; (defn- p5 [l in] (if-let [op (p5-ops (token/kind (first in)))] (let [[r in-rest] (p6 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p4 ::= <p6> <p5> ;; (defn- p4 [in] (let [[l in-rest] (p6 in)] (p5 l in-rest))) (def ^:private p3-ops {:star ast/multiply-AST :slash ast/divide-AST :percent ast/modulo-AST :caret ast/power-AST}) ;; ;; p3 ::= '*' <p4> <p3> ;; ::= '/' <p4> <p3> ;; ::= '%' <p4> <p3> ;; ::= '^' <p4> <p3> ;; ::= e ;; (defn- p3 [l in] (if-let [op (p3-ops (token/kind (first in)))] (let [[r in-rest] (p4 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p2 ::= <p4> <p3> ;; (defn- p2 [in] (let [[l in-rest] (p4 in)] (p3 l in-rest))) (def ^:private p1-ops {:plus ast/add-AST :minus ast/subtract-AST}) ;; ;; p1 ::= '+' <p2> <p1> ;; ::= '-' <p2> <p1> ;; ::= e ;; (defn- p1 [l in] (if-let [op (p1-ops (token/kind (first in)))] (let [[r in-rest] (p2 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p0 ::= <p2> <p1> ;; (defn- p0 [in] (let [[l in-rest] (p2 in)] (p1 l in-rest))) (defn parser "A recursive-descent parser that transforms a sequence of tokens from `in` into an AST." [in] (let [[ast in-rest] (p0 in) t (first in-rest)] (if (nil? t) ast (throw (Exception. (str (token/lexeme t) ": expecting " (token/lexeme token/EOS-token)))))))
true
;;; Copyright 2020 PI:NAME:<NAME>END_PI ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. ;;; (ns rpn.parser "Parser. p0 ::= <p2> <p1> p1 ::= '+' <p2> <p1> ::= '-' <p2> <p1> ::= e p2 ::= <p4> <p3> p3 ::= '*' <p4> <p3> ::= '/' <p4> <p3> ::= '%' <p4> <p3> ::= '^' <p4> <p3> ::= e p4 ::= <p6> <p5> p5 ::= 'min' <p6> <p5> ::= 'max' <p6> <p5> ::= e p6 ::= '(' <p0> ')' ::= <symbol> ::= <number>" (:require [rpn.token :as token]) (:require [rpn.lexer :as lexer]) (:require [rpn.ast :as ast])) (defn- effective-lexeme [token] (token/lexeme (or token token/EOS-token))) (defn- match [in token] (let [t (first in)] (if (token/same-kind? t token) (rest in) (throw (Exception. (str (effective-lexeme t) ": expecting '" (token/lexeme token) "'")))))) (declare p0) ;; ;; p6 ::= '(' <p0> ')' ;; ::= <symbol> ;; ::= <number> ;; (defn- p6 [in] (let [t (first in)] (case (token/kind t) :left-paren (let [[ast in-rest] (p0 (rest in))] [ast (match in-rest token/right-paren-token)]) :symbol [(ast/symbol-AST (token/lexeme t)) (rest in)] :number [(ast/number-AST (Double/parseDouble (token/lexeme t))) (rest in)] (throw (Exception. (str (effective-lexeme t) ": expecting '{', <symbol> or <number>")))))) (def ^:private p5-ops {:min ast/min-AST :max ast/max-AST}) ;; ;; p5 ::= 'min' <p6> <p5> ;; ::= 'max' <p6> <p5> ;; ::= e ;; (defn- p5 [l in] (if-let [op (p5-ops (token/kind (first in)))] (let [[r in-rest] (p6 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p4 ::= <p6> <p5> ;; (defn- p4 [in] (let [[l in-rest] (p6 in)] (p5 l in-rest))) (def ^:private p3-ops {:star ast/multiply-AST :slash ast/divide-AST :percent ast/modulo-AST :caret ast/power-AST}) ;; ;; p3 ::= '*' <p4> <p3> ;; ::= '/' <p4> <p3> ;; ::= '%' <p4> <p3> ;; ::= '^' <p4> <p3> ;; ::= e ;; (defn- p3 [l in] (if-let [op (p3-ops (token/kind (first in)))] (let [[r in-rest] (p4 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p2 ::= <p4> <p3> ;; (defn- p2 [in] (let [[l in-rest] (p4 in)] (p3 l in-rest))) (def ^:private p1-ops {:plus ast/add-AST :minus ast/subtract-AST}) ;; ;; p1 ::= '+' <p2> <p1> ;; ::= '-' <p2> <p1> ;; ::= e ;; (defn- p1 [l in] (if-let [op (p1-ops (token/kind (first in)))] (let [[r in-rest] (p2 (rest in))] (recur (op l r) in-rest)) [l in])) ;; ;; p0 ::= <p2> <p1> ;; (defn- p0 [in] (let [[l in-rest] (p2 in)] (p1 l in-rest))) (defn parser "A recursive-descent parser that transforms a sequence of tokens from `in` into an AST." [in] (let [[ast in-rest] (p0 in) t (first in-rest)] (if (nil? t) ast (throw (Exception. (str (token/lexeme t) ": expecting " (token/lexeme token/EOS-token)))))))
[ { "context": "c]\n [:a {:href \"/profile\"}\n \"Oleg Akbarov\"]]]]))\n", "end": 837, "score": 0.9995277523994446, "start": 825, "tag": "NAME", "value": "Oleg Akbarov" } ]
data/train/clojure/cdedb37cce90b96a6967e5e5d74fadf86bf59f46header.cljs
harshp8l/deep-learning-lang-detection
84
(ns nexus.templates.header (:require [nexus.routes :as routes] [re-frame.core :refer [dispatch dispatch-sync subscribe]])) (defn header [] (fn [] [:div.header [:div.header_wrapper [:div.header_left [:a.header_logo {:href "/profile"}] [:ul.header_crumbs [:li [:a {:href "/bots"} "My Bots"]] [:li [:a {:href "/editor"} "Weather bot"]]]] [:div.header_right [:div.btn.header_save_button {:on-click #(dispatch [:course/create-save])} "Save"] [:div.btn.header_test_button {:on-click #(dispatch [:show_state])} "Test"] [:div.header_userpic] [:a {:href "/profile"} "Oleg Akbarov"]]]]))
2055
(ns nexus.templates.header (:require [nexus.routes :as routes] [re-frame.core :refer [dispatch dispatch-sync subscribe]])) (defn header [] (fn [] [:div.header [:div.header_wrapper [:div.header_left [:a.header_logo {:href "/profile"}] [:ul.header_crumbs [:li [:a {:href "/bots"} "My Bots"]] [:li [:a {:href "/editor"} "Weather bot"]]]] [:div.header_right [:div.btn.header_save_button {:on-click #(dispatch [:course/create-save])} "Save"] [:div.btn.header_test_button {:on-click #(dispatch [:show_state])} "Test"] [:div.header_userpic] [:a {:href "/profile"} "<NAME>"]]]]))
true
(ns nexus.templates.header (:require [nexus.routes :as routes] [re-frame.core :refer [dispatch dispatch-sync subscribe]])) (defn header [] (fn [] [:div.header [:div.header_wrapper [:div.header_left [:a.header_logo {:href "/profile"}] [:ul.header_crumbs [:li [:a {:href "/bots"} "My Bots"]] [:li [:a {:href "/editor"} "Weather bot"]]]] [:div.header_right [:div.btn.header_save_button {:on-click #(dispatch [:course/create-save])} "Save"] [:div.btn.header_test_button {:on-click #(dispatch [:show_state])} "Test"] [:div.header_userpic] [:a {:href "/profile"} "PI:NAME:<NAME>END_PI"]]]]))
[ { "context": "-testing-schema-test-check.core-test\n ^{:author \"Leeor Engel\"}\n (:require [prop-testing-schema-test-check.cor", "end": 69, "score": 0.9998881220817566, "start": 58, "tag": "NAME", "value": "Leeor Engel" } ]
test/prop_testing_schema_test_check/core_test.clj
leeorengel/clojure-prop-testing-schema-test.check
1
(ns prop-testing-schema-test-check.core-test ^{:author "Leeor Engel"} (:require [prop-testing-schema-test-check.core :refer :all] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer :all] [com.gfredericks.test.chuck.properties :as tcp] [schema.core :as s] [schema.test] [schema.experimental.generators :as sgen]) (:import (clojure.test.check.generators Generator) (prop_testing_schema_test_check.core Melody))) (use-fixtures :once schema.test/validate-schemas) (def PositiveInt (s/constrained s/Int pos?)) ;; ;; Generators ;; (def RestGenerator (sgen/always -1)) ;; Not using the schema genator here because s/constrained will not always gaurantee valid inputs (def NoteGenerator (gen/choose MIN-NOTE MAX-NOTE)) (s/defn notes-gen :- Generator [size :- PositiveInt] (gen/vector NoteGenerator size)) (s/defn rests-gen :- Generator [size :- PositiveInt] (gen/vector RestGenerator size)) (s/defn notes-and-rests-gen :- Generator [size :- PositiveInt num-notes :- PositiveInt] (gen/bind (notes-gen num-notes) (fn [v] (let [remaining (- size num-notes)] (if (zero? remaining) (gen/return v) (gen/fmap (fn [rests] (shuffle (into v rests))) (rests-gen remaining))))))) (s/defn melody-gen :- Generator ([size :- PositiveInt num-notes :- PositiveInt] (sgen/generator Melody {[NoteOrRest] (notes-and-rests-gen size num-notes)}))) ;; ;; test.check version ;; (defspec with-new-notes-test-check 1000 (let [test-gens (gen/let [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] [melody notes])] (prop/for-all [[melody notes] test-gens] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))) ;; ;; test.chuck version ;; (defspec with-new-notes-test-chuck 1000 (tcp/for-all [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))
64555
(ns prop-testing-schema-test-check.core-test ^{:author "<NAME>"} (:require [prop-testing-schema-test-check.core :refer :all] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer :all] [com.gfredericks.test.chuck.properties :as tcp] [schema.core :as s] [schema.test] [schema.experimental.generators :as sgen]) (:import (clojure.test.check.generators Generator) (prop_testing_schema_test_check.core Melody))) (use-fixtures :once schema.test/validate-schemas) (def PositiveInt (s/constrained s/Int pos?)) ;; ;; Generators ;; (def RestGenerator (sgen/always -1)) ;; Not using the schema genator here because s/constrained will not always gaurantee valid inputs (def NoteGenerator (gen/choose MIN-NOTE MAX-NOTE)) (s/defn notes-gen :- Generator [size :- PositiveInt] (gen/vector NoteGenerator size)) (s/defn rests-gen :- Generator [size :- PositiveInt] (gen/vector RestGenerator size)) (s/defn notes-and-rests-gen :- Generator [size :- PositiveInt num-notes :- PositiveInt] (gen/bind (notes-gen num-notes) (fn [v] (let [remaining (- size num-notes)] (if (zero? remaining) (gen/return v) (gen/fmap (fn [rests] (shuffle (into v rests))) (rests-gen remaining))))))) (s/defn melody-gen :- Generator ([size :- PositiveInt num-notes :- PositiveInt] (sgen/generator Melody {[NoteOrRest] (notes-and-rests-gen size num-notes)}))) ;; ;; test.check version ;; (defspec with-new-notes-test-check 1000 (let [test-gens (gen/let [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] [melody notes])] (prop/for-all [[melody notes] test-gens] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))) ;; ;; test.chuck version ;; (defspec with-new-notes-test-chuck 1000 (tcp/for-all [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))
true
(ns prop-testing-schema-test-check.core-test ^{:author "PI:NAME:<NAME>END_PI"} (:require [prop-testing-schema-test-check.core :refer :all] [clojure.test :refer :all] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :refer :all] [com.gfredericks.test.chuck.properties :as tcp] [schema.core :as s] [schema.test] [schema.experimental.generators :as sgen]) (:import (clojure.test.check.generators Generator) (prop_testing_schema_test_check.core Melody))) (use-fixtures :once schema.test/validate-schemas) (def PositiveInt (s/constrained s/Int pos?)) ;; ;; Generators ;; (def RestGenerator (sgen/always -1)) ;; Not using the schema genator here because s/constrained will not always gaurantee valid inputs (def NoteGenerator (gen/choose MIN-NOTE MAX-NOTE)) (s/defn notes-gen :- Generator [size :- PositiveInt] (gen/vector NoteGenerator size)) (s/defn rests-gen :- Generator [size :- PositiveInt] (gen/vector RestGenerator size)) (s/defn notes-and-rests-gen :- Generator [size :- PositiveInt num-notes :- PositiveInt] (gen/bind (notes-gen num-notes) (fn [v] (let [remaining (- size num-notes)] (if (zero? remaining) (gen/return v) (gen/fmap (fn [rests] (shuffle (into v rests))) (rests-gen remaining))))))) (s/defn melody-gen :- Generator ([size :- PositiveInt num-notes :- PositiveInt] (sgen/generator Melody {[NoteOrRest] (notes-and-rests-gen size num-notes)}))) ;; ;; test.check version ;; (defspec with-new-notes-test-check 1000 (let [test-gens (gen/let [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] [melody notes])] (prop/for-all [[melody notes] test-gens] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))) ;; ;; test.chuck version ;; (defspec with-new-notes-test-chuck 1000 (tcp/for-all [num-notes gen/s-pos-int melody-num-rests gen/s-pos-int total-melody-num-notes (gen/return (+ num-notes melody-num-rests)) melody (melody-gen total-melody-num-notes num-notes) notes (notes-gen num-notes)] (let [new-melody (with-new-notes melody notes)] (and (= (count notes) (note-count (:notes new-melody))) (= notes (remove rest? (:notes new-melody)))))))
[ { "context": "lojure.pprint :refer [pprint])))\n\n(def token-acc \"forbeginners\")\n(def swap-acc \"dontworrybet\")\n(def sta", "end": 183, "score": 0.5888593792915344, "start": 180, "tag": "USERNAME", "value": "for" }, { "context": "ure.pprint :refer [pprint])))\n\n(def token-acc \"forbeginners\")\n(def swap-acc \"dontworrybet\")\n(def stake-acc \"s", "end": 192, "score": 0.7388840913772583, "start": 183, "tag": "PASSWORD", "value": "beginners" }, { "context": "))\n\n(def token-acc \"forbeginners\")\n(def swap-acc \"dontworrybet\")\n(def stake-acc \"stktest11111\")\n(def bk-acc \"for", "end": 222, "score": 0.5993741750717163, "start": 210, "tag": "PASSWORD", "value": "dontworrybet" }, { "context": "\n(def swap-acc \"dontworrybet\")\n(def stake-acc \"stktest11111\")\n(def bk-acc \"foreveryoung\")\n\n(def tkn-sym \"", "end": 249, "score": 0.6561113595962524, "start": 244, "tag": "KEY", "value": "test1" }, { "context": "wap-acc \"dontworrybet\")\n(def stake-acc \"stktest11111\")\n(def bk-acc \"foreveryoung\")\n\n(def tkn-sym \"UTL", "end": 252, "score": 0.5564224123954773, "start": 251, "tag": "KEY", "value": "1" }, { "context": ")\n(def stake-acc \"stktest11111\")\n(def bk-acc \"foreveryoung\")\n\n(def tkn-sym \"UTL\")\n(def clm-sym \"GOV\")\n(d", "end": 277, "score": 0.4238084852695465, "start": 273, "tag": "PASSWORD", "value": "very" }, { "context": "ef stake-acc \"stktest11111\")\n(def bk-acc \"foreveryoung\")\n\n(def tkn-sym \"UTL\")\n(def clm-sym \"GOV\")\n(def t", "end": 281, "score": 0.42809250950813293, "start": 277, "tag": "KEY", "value": "oung" } ]
deploy/jungle.cljs
jabbarn/effect-network
35
(ns jungle (:require [eos-cljs.core :as eos] [cljs.core :refer [*command-line-args*]] [clojure.string :as string] (clojure.pprint :refer [pprint]))) (def token-acc "forbeginners") (def swap-acc "dontworrybet") (def stake-acc "stktest11111") (def bk-acc "foreveryoung") (def tkn-sym "UTL") (def clm-sym "GOV") (def tkn-total-supply "650000000.0000") (def clm-total-supply "20000000000.0000") (def sec-per-day 86400) (def stake-config {:token_contract token-acc :stake_symbol (str "4," tkn-sym) :claim_symbol (str "4," clm-sym) :age_limit (* 200 sec-per-day) :scale_factor (* 10000000000 sec-per-day) :unstake_delay_sec (* 7 sec-per-day) :stake_bonus_age (* 50 sec-per-day) :stake_bonus_deadline "2019-04-18T15:59:44.500"}) (def swap-config {:token_contract token-acc :token_symbol tkn-sym :issue_memo (str "Welcome to EOS " tkn-sym "!") :tx_max_age 10000 :min_tx_value 1 :max_tx_value 100000}) (defn usage [opts] (->> ["Run as `npm run deploy jungle <PRIVATE KEY FOR SIGNING>`" "" "The private key is used for signing all transactions." "" "Code will be deployed to:" (str "- " token-acc " (token)") (str "- " swap-acc " (swap)") (str "- " stake-acc " (stake)") "" (str bk-acc " is a book keeper which is allowed to posttx") ""] (string/join "\n"))) (defn -main [] (if (empty? *command-line-args*) (print (usage nil)) (let [[privatekey] *command-line-args*] (eos/set-api! (assoc (:jungle eos/apis) :priv-keys [privatekey])) (-> ;; deploy fresh code (eos/deploy token-acc "contracts/token/token") (.catch prn) (.then #(eos/deploy swap-acc "contracts/swap/swap")) (.catch prn) (.then #(eos/deploy stake-acc "contracts/stake/stake")) (.catch prn) ;; set authorities (.then #(eos/update-auth swap-acc "active" [{:permission {:actor swap-acc :permission "eosio.code"} :weight 1}])) (.then #(eos/update-auth stake-acc "active" [{:permission {:actor stake-acc :permission "eosio.code"} :weight 1}])) eos/wait-block ;; create the token (.then #(print "\n========================\nCREATE TOKEN" tkn-sym " in " token-acc "\n========================\n")) (.then #(eos/transact token-acc "create" {:issuer swap-acc :maximum_supply (str tkn-total-supply " " tkn-sym)})) (.catch prn) (.then #(eos/transact token-acc "create" {:issuer stake-acc :maximum_supply (str clm-total-supply " " clm-sym)})) (.catch prn) ;; initialize stake and swap (.then #(eos/transact stake-acc "init" stake-config [{:actor stake-acc :permission "owner"}])) (.catch prn) (.then #(eos/transact swap-acc "init" swap-config [{:actor swap-acc :permission "owner"}])) (.catch prn) ;; add a bookkeeper that can post neo txs (.then #(eos/transact swap-acc "mkbookkeeper" {:account bk-acc} [{:actor swap-acc :permission "owner"}])) (.catch prn) (.then #(print "\nDone!\n"))))))
34774
(ns jungle (:require [eos-cljs.core :as eos] [cljs.core :refer [*command-line-args*]] [clojure.string :as string] (clojure.pprint :refer [pprint]))) (def token-acc "for<PASSWORD>") (def swap-acc "<PASSWORD>") (def stake-acc "stk<KEY>11<KEY>1") (def bk-acc "fore<PASSWORD> <KEY>") (def tkn-sym "UTL") (def clm-sym "GOV") (def tkn-total-supply "650000000.0000") (def clm-total-supply "20000000000.0000") (def sec-per-day 86400) (def stake-config {:token_contract token-acc :stake_symbol (str "4," tkn-sym) :claim_symbol (str "4," clm-sym) :age_limit (* 200 sec-per-day) :scale_factor (* 10000000000 sec-per-day) :unstake_delay_sec (* 7 sec-per-day) :stake_bonus_age (* 50 sec-per-day) :stake_bonus_deadline "2019-04-18T15:59:44.500"}) (def swap-config {:token_contract token-acc :token_symbol tkn-sym :issue_memo (str "Welcome to EOS " tkn-sym "!") :tx_max_age 10000 :min_tx_value 1 :max_tx_value 100000}) (defn usage [opts] (->> ["Run as `npm run deploy jungle <PRIVATE KEY FOR SIGNING>`" "" "The private key is used for signing all transactions." "" "Code will be deployed to:" (str "- " token-acc " (token)") (str "- " swap-acc " (swap)") (str "- " stake-acc " (stake)") "" (str bk-acc " is a book keeper which is allowed to posttx") ""] (string/join "\n"))) (defn -main [] (if (empty? *command-line-args*) (print (usage nil)) (let [[privatekey] *command-line-args*] (eos/set-api! (assoc (:jungle eos/apis) :priv-keys [privatekey])) (-> ;; deploy fresh code (eos/deploy token-acc "contracts/token/token") (.catch prn) (.then #(eos/deploy swap-acc "contracts/swap/swap")) (.catch prn) (.then #(eos/deploy stake-acc "contracts/stake/stake")) (.catch prn) ;; set authorities (.then #(eos/update-auth swap-acc "active" [{:permission {:actor swap-acc :permission "eosio.code"} :weight 1}])) (.then #(eos/update-auth stake-acc "active" [{:permission {:actor stake-acc :permission "eosio.code"} :weight 1}])) eos/wait-block ;; create the token (.then #(print "\n========================\nCREATE TOKEN" tkn-sym " in " token-acc "\n========================\n")) (.then #(eos/transact token-acc "create" {:issuer swap-acc :maximum_supply (str tkn-total-supply " " tkn-sym)})) (.catch prn) (.then #(eos/transact token-acc "create" {:issuer stake-acc :maximum_supply (str clm-total-supply " " clm-sym)})) (.catch prn) ;; initialize stake and swap (.then #(eos/transact stake-acc "init" stake-config [{:actor stake-acc :permission "owner"}])) (.catch prn) (.then #(eos/transact swap-acc "init" swap-config [{:actor swap-acc :permission "owner"}])) (.catch prn) ;; add a bookkeeper that can post neo txs (.then #(eos/transact swap-acc "mkbookkeeper" {:account bk-acc} [{:actor swap-acc :permission "owner"}])) (.catch prn) (.then #(print "\nDone!\n"))))))
true
(ns jungle (:require [eos-cljs.core :as eos] [cljs.core :refer [*command-line-args*]] [clojure.string :as string] (clojure.pprint :refer [pprint]))) (def token-acc "forPI:PASSWORD:<PASSWORD>END_PI") (def swap-acc "PI:PASSWORD:<PASSWORD>END_PI") (def stake-acc "stkPI:KEY:<KEY>END_PI11PI:KEY:<KEY>END_PI1") (def bk-acc "forePI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI") (def tkn-sym "UTL") (def clm-sym "GOV") (def tkn-total-supply "650000000.0000") (def clm-total-supply "20000000000.0000") (def sec-per-day 86400) (def stake-config {:token_contract token-acc :stake_symbol (str "4," tkn-sym) :claim_symbol (str "4," clm-sym) :age_limit (* 200 sec-per-day) :scale_factor (* 10000000000 sec-per-day) :unstake_delay_sec (* 7 sec-per-day) :stake_bonus_age (* 50 sec-per-day) :stake_bonus_deadline "2019-04-18T15:59:44.500"}) (def swap-config {:token_contract token-acc :token_symbol tkn-sym :issue_memo (str "Welcome to EOS " tkn-sym "!") :tx_max_age 10000 :min_tx_value 1 :max_tx_value 100000}) (defn usage [opts] (->> ["Run as `npm run deploy jungle <PRIVATE KEY FOR SIGNING>`" "" "The private key is used for signing all transactions." "" "Code will be deployed to:" (str "- " token-acc " (token)") (str "- " swap-acc " (swap)") (str "- " stake-acc " (stake)") "" (str bk-acc " is a book keeper which is allowed to posttx") ""] (string/join "\n"))) (defn -main [] (if (empty? *command-line-args*) (print (usage nil)) (let [[privatekey] *command-line-args*] (eos/set-api! (assoc (:jungle eos/apis) :priv-keys [privatekey])) (-> ;; deploy fresh code (eos/deploy token-acc "contracts/token/token") (.catch prn) (.then #(eos/deploy swap-acc "contracts/swap/swap")) (.catch prn) (.then #(eos/deploy stake-acc "contracts/stake/stake")) (.catch prn) ;; set authorities (.then #(eos/update-auth swap-acc "active" [{:permission {:actor swap-acc :permission "eosio.code"} :weight 1}])) (.then #(eos/update-auth stake-acc "active" [{:permission {:actor stake-acc :permission "eosio.code"} :weight 1}])) eos/wait-block ;; create the token (.then #(print "\n========================\nCREATE TOKEN" tkn-sym " in " token-acc "\n========================\n")) (.then #(eos/transact token-acc "create" {:issuer swap-acc :maximum_supply (str tkn-total-supply " " tkn-sym)})) (.catch prn) (.then #(eos/transact token-acc "create" {:issuer stake-acc :maximum_supply (str clm-total-supply " " clm-sym)})) (.catch prn) ;; initialize stake and swap (.then #(eos/transact stake-acc "init" stake-config [{:actor stake-acc :permission "owner"}])) (.catch prn) (.then #(eos/transact swap-acc "init" swap-config [{:actor swap-acc :permission "owner"}])) (.catch prn) ;; add a bookkeeper that can post neo txs (.then #(eos/transact swap-acc "mkbookkeeper" {:account bk-acc} [{:actor swap-acc :permission "owner"}])) (.catch prn) (.then #(print "\nDone!\n"))))))
[ { "context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The", "end": 45, "score": 0.999850332736969, "start": 27, "tag": "NAME", "value": "Michael S. Klishin" }, { "context": ";; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team\n;;\n;; The use and dist", "end": 58, "score": 0.9998159408569336, "start": 47, "tag": "NAME", "value": "Alex Petrov" } ]
src/clojure/pantomime/languages.clj
dthadi3/pantomime
119
;; Copyright (c) 2011-2014 Michael S. Klishin, Alex Petrov, and the ClojureWerkz Team ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns pantomime.languages "Natural language detection functions. Note that not all languages are currently supported by Tika, and, in turn, Pantomime." (:require [clojure.java.io :as io]) (:import org.apache.tika.language.LanguageIdentifier java.net.URL java.io.File java.io.InputStream)) ;; ;; API ;; (defprotocol LanguageDetection (detect-language [arg] "Identifies natural language of the input")) (extend-protocol LanguageDetection String (detect-language [^String source] (.getLanguage (LanguageIdentifier. source))) File (detect-language [^File source] (detect-language (slurp source))) InputStream (detect-language [^InputStream source] (detect-language (slurp (io/as-file source)))) URL (detect-language [^URL source] (detect-language (slurp source)))) (def supported-languages "A set of languages supported by the Tika language detector, and, in turn, Pantomime" (set (sort (LanguageIdentifier/getSupportedLanguages))))
27900
;; Copyright (c) 2011-2014 <NAME>, <NAME>, and the ClojureWerkz Team ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns pantomime.languages "Natural language detection functions. Note that not all languages are currently supported by Tika, and, in turn, Pantomime." (:require [clojure.java.io :as io]) (:import org.apache.tika.language.LanguageIdentifier java.net.URL java.io.File java.io.InputStream)) ;; ;; API ;; (defprotocol LanguageDetection (detect-language [arg] "Identifies natural language of the input")) (extend-protocol LanguageDetection String (detect-language [^String source] (.getLanguage (LanguageIdentifier. source))) File (detect-language [^File source] (detect-language (slurp source))) InputStream (detect-language [^InputStream source] (detect-language (slurp (io/as-file source)))) URL (detect-language [^URL source] (detect-language (slurp source)))) (def supported-languages "A set of languages supported by the Tika language detector, and, in turn, Pantomime" (set (sort (LanguageIdentifier/getSupportedLanguages))))
true
;; Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and the ClojureWerkz Team ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns pantomime.languages "Natural language detection functions. Note that not all languages are currently supported by Tika, and, in turn, Pantomime." (:require [clojure.java.io :as io]) (:import org.apache.tika.language.LanguageIdentifier java.net.URL java.io.File java.io.InputStream)) ;; ;; API ;; (defprotocol LanguageDetection (detect-language [arg] "Identifies natural language of the input")) (extend-protocol LanguageDetection String (detect-language [^String source] (.getLanguage (LanguageIdentifier. source))) File (detect-language [^File source] (detect-language (slurp source))) InputStream (detect-language [^InputStream source] (detect-language (slurp (io/as-file source)))) URL (detect-language [^URL source] (detect-language (slurp source)))) (def supported-languages "A set of languages supported by the Tika language detector, and, in turn, Pantomime" (set (sort (LanguageIdentifier/getSupportedLanguages))))
[ { "context": ";;;;;;;;;;;;;;\n\n(defn select-topics []\n [:div \"Hi User, You will select topics here.\"])\n\n;;;;;;;;;;;;;;;", "end": 2373, "score": 0.6692606210708618, "start": 2369, "tag": "NAME", "value": "User" } ]
src/links/app.cljs
entranceplus/link-server
0
(ns links.app (:require [snow.comm.core :as comm] [snow.router :as router] [reagent.core :as r] [re-frame.core :as rf] [stylefy.core :as stylefy :refer [use-style]] ["react-pose" :as rpose :default posed])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Available routes in our app ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def route-map {:home "/" :select-topics "/topics" :sources "/sources"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; css used for login page ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def loading-after {:width "40%" :height "100vh" :transition "all 0.3s ease-in" :background "#374A67" }) (def home-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :height "100vh" }) (def form-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "stretch" :margin-top "70px"}) (def input-style {:text-align "center" :background-color "#CB9CF2" :height "30px" :line-height "30px" :border "1px solid purple" :border-radius "2px"}) (def input-container-style {:padding "5px 0px 5px 0px"}) ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; login-page component ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn home-page [] [:div (use-style home-container) [:h1 (use-style {:flex-grow "0"}) "Around"] [:div "Somethings are around"] [:div (use-style form-container) [:div (use-style input-container-style) [:input (use-style input-style {:type "text" :placeholder "Enter username"})]] [:div (use-style input-container-style) [:input (use-style input-style {:type "password" :placeholder "Enter password"})]] [:div (use-style input-container-style) [:div (use-style input-style) "Get Started"]]]]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; select topic component could go here ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn select-topics [] [:div "Hi User, You will select topics here."]) ;;;;;;;;;;;;;;;;;;;;;;;;; ;; top level component ;; ;;;;;;;;;;;;;;;;;;;;;;;;; (defn page [route params] "based on the route load the correct child" [:div (stylefy/use-style loading-after) (case route :home [home-page] :select-topics [select-topics] :sources [:div "Sources"] [:div "Not Found"])]) ;; event handler to ensure navigation works (rf/reg-event-fx :navigate (fn [{:keys [db]} [_ page param]] (let [db (assoc db :page page :page-param param)] (case page {:db db})))) (defn on-navigate "Function called on route change. This loads the page component passing it the route the user currently is at." [route params query] (rf/dispatch-sync [:navigate {:route route :params params :perform? false}]) (r/render [page route params] (js/document.getElementById "root"))) (defn main [] "start stuff" ;; start communication with backend (comm/start!) ;; initialize stylefy (used for writing css in cljs) (stylefy/init) ;; start front end router (router/start! route-map on-navigate) ;; do intial animation (js/anime (clj->js {:targets ".app" :translateX [{:value 0 :duration 1200} {:value "-60%" :duration 800}] :duration 2000})) ;; print as always (println "Well.. Hello there!!!!")) (main)
13087
(ns links.app (:require [snow.comm.core :as comm] [snow.router :as router] [reagent.core :as r] [re-frame.core :as rf] [stylefy.core :as stylefy :refer [use-style]] ["react-pose" :as rpose :default posed])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Available routes in our app ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def route-map {:home "/" :select-topics "/topics" :sources "/sources"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; css used for login page ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def loading-after {:width "40%" :height "100vh" :transition "all 0.3s ease-in" :background "#374A67" }) (def home-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :height "100vh" }) (def form-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "stretch" :margin-top "70px"}) (def input-style {:text-align "center" :background-color "#CB9CF2" :height "30px" :line-height "30px" :border "1px solid purple" :border-radius "2px"}) (def input-container-style {:padding "5px 0px 5px 0px"}) ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; login-page component ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn home-page [] [:div (use-style home-container) [:h1 (use-style {:flex-grow "0"}) "Around"] [:div "Somethings are around"] [:div (use-style form-container) [:div (use-style input-container-style) [:input (use-style input-style {:type "text" :placeholder "Enter username"})]] [:div (use-style input-container-style) [:input (use-style input-style {:type "password" :placeholder "Enter password"})]] [:div (use-style input-container-style) [:div (use-style input-style) "Get Started"]]]]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; select topic component could go here ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn select-topics [] [:div "Hi <NAME>, You will select topics here."]) ;;;;;;;;;;;;;;;;;;;;;;;;; ;; top level component ;; ;;;;;;;;;;;;;;;;;;;;;;;;; (defn page [route params] "based on the route load the correct child" [:div (stylefy/use-style loading-after) (case route :home [home-page] :select-topics [select-topics] :sources [:div "Sources"] [:div "Not Found"])]) ;; event handler to ensure navigation works (rf/reg-event-fx :navigate (fn [{:keys [db]} [_ page param]] (let [db (assoc db :page page :page-param param)] (case page {:db db})))) (defn on-navigate "Function called on route change. This loads the page component passing it the route the user currently is at." [route params query] (rf/dispatch-sync [:navigate {:route route :params params :perform? false}]) (r/render [page route params] (js/document.getElementById "root"))) (defn main [] "start stuff" ;; start communication with backend (comm/start!) ;; initialize stylefy (used for writing css in cljs) (stylefy/init) ;; start front end router (router/start! route-map on-navigate) ;; do intial animation (js/anime (clj->js {:targets ".app" :translateX [{:value 0 :duration 1200} {:value "-60%" :duration 800}] :duration 2000})) ;; print as always (println "Well.. Hello there!!!!")) (main)
true
(ns links.app (:require [snow.comm.core :as comm] [snow.router :as router] [reagent.core :as r] [re-frame.core :as rf] [stylefy.core :as stylefy :refer [use-style]] ["react-pose" :as rpose :default posed])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Available routes in our app ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def route-map {:home "/" :select-topics "/topics" :sources "/sources"}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; css used for login page ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def loading-after {:width "40%" :height "100vh" :transition "all 0.3s ease-in" :background "#374A67" }) (def home-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "center" :height "100vh" }) (def form-container {:display "flex" :flex-direction "column" :justify-content "center" :align-items "stretch" :margin-top "70px"}) (def input-style {:text-align "center" :background-color "#CB9CF2" :height "30px" :line-height "30px" :border "1px solid purple" :border-radius "2px"}) (def input-container-style {:padding "5px 0px 5px 0px"}) ;;;;;;;;;;;;;;;;;;;;;;;;;; ;; login-page component ;; ;;;;;;;;;;;;;;;;;;;;;;;;;; (defn home-page [] [:div (use-style home-container) [:h1 (use-style {:flex-grow "0"}) "Around"] [:div "Somethings are around"] [:div (use-style form-container) [:div (use-style input-container-style) [:input (use-style input-style {:type "text" :placeholder "Enter username"})]] [:div (use-style input-container-style) [:input (use-style input-style {:type "password" :placeholder "Enter password"})]] [:div (use-style input-container-style) [:div (use-style input-style) "Get Started"]]]]) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; select topic component could go here ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn select-topics [] [:div "Hi PI:NAME:<NAME>END_PI, You will select topics here."]) ;;;;;;;;;;;;;;;;;;;;;;;;; ;; top level component ;; ;;;;;;;;;;;;;;;;;;;;;;;;; (defn page [route params] "based on the route load the correct child" [:div (stylefy/use-style loading-after) (case route :home [home-page] :select-topics [select-topics] :sources [:div "Sources"] [:div "Not Found"])]) ;; event handler to ensure navigation works (rf/reg-event-fx :navigate (fn [{:keys [db]} [_ page param]] (let [db (assoc db :page page :page-param param)] (case page {:db db})))) (defn on-navigate "Function called on route change. This loads the page component passing it the route the user currently is at." [route params query] (rf/dispatch-sync [:navigate {:route route :params params :perform? false}]) (r/render [page route params] (js/document.getElementById "root"))) (defn main [] "start stuff" ;; start communication with backend (comm/start!) ;; initialize stylefy (used for writing css in cljs) (stylefy/init) ;; start front end router (router/start! route-map on-navigate) ;; do intial animation (js/anime (clj->js {:targets ".app" :translateX [{:value 0 :duration 1200} {:value "-60%" :duration 800}] :duration 2000})) ;; print as always (println "Well.. Hello there!!!!")) (main)
[ { "context": "(ns\n ^{:author \"Brian Craft\"\n :doc \"Xena H2 database backend\"}\n cavm.h2\n ", "end": 28, "score": 0.9998717308044434, "start": 17, "tag": "NAME", "value": "Brian Craft" }, { "context": "can reference it.\n(def ^:private KEY-ID (keyword \"scope_identity()\"))\n\n(def ^:private float-size 4)\n(def ^:private b", "end": 1791, "score": 0.8487544059753418, "start": 1775, "tag": "KEY", "value": "scope_identity()" } ]
src/cavm/h2.clj
ucscXena/ucsc-xena-server
8
(ns ^{:author "Brian Craft" :doc "Xena H2 database backend"} cavm.h2 (:require [clojure.java.jdbc.deprecated :as jdbcd]) (:require [clojure.java.jdbc :as jdbc]) (:require [cavm.jdbc]) (:require [org.clojars.smee.binary.core :as binary]) (:require [clojure.java.io :as io]) (:require [honeysql.core :as hsql]) (:require [honeysql.format :as hsqlfmt]) (:require [honeysql.types :as hsqltypes]) (:require [cavm.json :as json]) (:require [cavm.binner :refer [calc-bin overlapping-bins]]) (:use [clj-time.format :only (formatter unparse)]) (:use [cavm.hashable :only (ahashable)]) (:require [cavm.db :refer [XenaDb]]) (:require [clojure.tools.logging :refer [spy trace info warn]]) (:require [taoensso.timbre.profiling :refer [profile p]]) (:require [clojure.core.cache :as cache]) (:require [cavm.statement :refer [sql-stmt sql-stmt-result cached-statement]]) (:require [cavm.conn-pool :refer [pool]]) (:require [cavm.lazy-utils :refer [consume-vec lazy-mapcat]]) (:require [clojure.core.match :refer [match]]) (:require [cavm.sqleval :refer [evaluate]]) (:require [clojure.data.int-map :as i]) (:import [org.h2.jdbc JdbcBatchUpdateException]) (:import [com.mchange.v2.c3p0 ComboPooledDataSource])) (def h2-log-level (into {} (map vector [:off :error :info :debug :slf4j] (range)))) ; ; Note that "bin" in this file is like a "segement" in the column store ; literature: a column is split into a series of segments (bins) before ; writing to disk (saving as blob in h2). ; (def ^:dynamic ^:private *tmp-dir* (System/getProperty "java.io.tmpdir")) (defn set-tmp-dir! [dir] (alter-var-root #'*tmp-dir* (constantly dir))) ; Coerce this sql fn name to a keyword so we can reference it. (def ^:private KEY-ID (keyword "scope_identity()")) (def ^:private float-size 4) (def ^:private bin-size 1000) (def ^:private score-size (* float-size bin-size)) ; Add 30 for gzip header ;( def score-size (+ 30 (* float-size bin-size))) ; row count for batch operations (e.g. insert/delete) (def ^:private batch-size 1000) ; ; Utility functions ; (defn- chunked-pmap [f coll] (->> coll (partition-all 250) (pmap (fn [chunk] (doall (map f chunk)))) (apply concat))) (defn- memoize-key "Memoize with the given function of the arguments" [kf f] (let [mem (atom {})] (fn [& args] (let [k (kf args)] (if-let [e (find @mem k)] (val e) (let [ret (apply f args)] (swap! mem assoc k ret) ret)))))) ; ; Table models ; (declare score-decode) (defn- cvt-scores [{scores :scores :as v}] (if scores (assoc v :scores (float-array (score-decode scores))) v)) ; ; Table definitions. ; (def ^:private max-probe-length 250) (def ^:private probe-version-length 5) ; to disambiguate probes by appending " (dd)" ; Note H2 has one int type: signed, 4 byte. Max is approximately 2 billion. (def ^:private field-table ["CREATE SEQUENCE IF NOT EXISTS FIELD_IDS CACHE 2000" (format "CREATE TABLE IF NOT EXISTS `field` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FIELD_IDS PRIMARY KEY, `dataset_id` INT NOT NULL, `name` VARCHAR(%d), UNIQUE(`dataset_id`, `name`), FOREIGN KEY (`dataset_id`) REFERENCES `dataset` (`id`) ON DELETE CASCADE)" (+ max-probe-length probe-version-length))]) (def ^:private field-score-table [(format "CREATE TABLE IF NOT EXISTS `field_score` ( `field_id` INT NOT NULL, `i` INT NOT NULL, `scores` VARBINARY(%d) NOT NULL, UNIQUE (`field_id`, `i`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" score-size)]) (def ^:private cohorts-table ["CREATE TABLE IF NOT EXISTS `cohorts` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL UNIQUE)"]) ; XXX What should max file name length be? ; XXX Unique columns? Indexes? (def ^:private source-table ["CREATE TABLE IF NOT EXISTS `source` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL, `time` TIMESTAMP NOT NULL, `hash` VARCHAR(40) NOT NULL)"]) (def ^:private dataset-table ["CREATE TABLE IF NOT EXISTS `dataset` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(1000) NOT NULL UNIQUE, `probeMap` VARCHAR(255), `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `groupTitle` VARCHAR(255), `platform` VARCHAR(255), `cohort` VARCHAR(1000), `security` VARCHAR(255), `rows` INT, `status` VARCHAR(20), `text` VARCHAR (65535), `type` VARCHAR (255), `dataSubType` VARCHAR (255))"]) (def ^:private dataset-columns #{:name :probeMap :shortTitle :longTitle :groupTitle :platform :cohort :security :dataSubType :type :text}) (def ^:private dataset-defaults (into {} (map #(vector % nil) dataset-columns))) (def ^:private dataset-source-table ["CREATE TABLE IF NOT EXISTS `dataset_source` ( `dataset_id` INT NOT NULL, `source_id` INT NOT NULL, FOREIGN KEY (dataset_id) REFERENCES `dataset` (`id`) ON DELETE CASCADE, FOREIGN KEY (source_id) REFERENCES `source` (`id`) ON DELETE CASCADE)"]) (def ^:private dataset-meta {:defaults dataset-defaults :columns dataset-columns}) ; XXX CASCADE might perform badly. Might need to do this incrementally in application code. (def ^:private field-position-table ["CREATE TABLE IF NOT EXISTS `field_position` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `bin` INT, `chrom` VARCHAR(255) NOT NULL, `chromStart` INT NOT NULL, `chromEnd` INT NOT NULL, `strand` CHAR(1), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS chrom_bin ON field_position (`field_id`, `chrom`, `bin`)" "CREATE INDEX IF NOT EXISTS position_row ON field_position (`field_id`, `row`)"]) (def ^:private field-gene-table ["CREATE TABLE IF NOT EXISTS `field_gene` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `gene` VARCHAR_IGNORECASE(255) NOT NULL, FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS field_gene ON `field_gene` (`field_id`, `gene`)" "CREATE INDEX IF NOT EXISTS gene_row ON `field_gene` (`field_id`, `row`)"]) ; ; feature tables ; (def ^:private feature-table ["CREATE SEQUENCE IF NOT EXISTS FEATURE_IDS CACHE 2000" "CREATE TABLE IF NOT EXISTS `feature` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FEATURE_IDS PRIMARY KEY, `field_id` INT(11) NOT NULL, `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `priority` DOUBLE DEFAULT NULL, `valueType` VARCHAR(255) NOT NULL, `visibility` VARCHAR(255), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (def ^:private feature-columns #{:shortTitle :longTitle :priority :valueType :visibility}) (def ^:private feature-defaults (into {} (map #(vector % nil) feature-columns))) (def ^:private feature-meta {:defaults feature-defaults :columns feature-columns}) ; Order is important to avoid creating duplicate indexes. A foreign ; key constraint creates an index if one doesn't exist, so create our ; index before adding the constraint. ; XXX varchar size is pushing it. Do we need another type for clob-valued ; fields? (def ^:private code-table ["CREATE TABLE IF NOT EXISTS `code` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `field_id` INT(11) NOT NULL, `ordering` INT(10) unsigned NOT NULL, `value` VARCHAR(16384) NOT NULL, UNIQUE (`field_id`, `ordering`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (defn- normalize-meta [m-ent metadata] (-> metadata (clojure.walk/keywordize-keys) (#(merge (:defaults m-ent) %)) (select-keys (:columns m-ent)))) (defn- json-text [md] (assoc md :text (json/write-str md :escape-slash false))) (defn- load-probe-meta [feature-seq field-id {:keys [order] :as feat}] (let [feature-id (feature-seq) fmeta (merge (normalize-meta feature-meta feat) {:field_id field-id :id feature-id})] (cons [:insert-feature (assoc fmeta :id feature-id)] (for [[value ordering] order] [:insert-code {:field_id field-id :ordering ordering :value value}])))) ; ; ; (defn do-command-while-updates [cmd] (while (> (first (jdbcd/do-commands cmd)) 0))) (defn delete-rows-by-field-cmd [table field] (format "DELETE FROM `%s` WHERE `field_id` = %d LIMIT %d" table field batch-size)) (defn- clear-fields [exp] (jdbcd/with-query-results field ["SELECT `id` FROM `field` WHERE `dataset_id` = ?" exp] (doseq [{id :id} field] (doseq [table ["code" "feature" "field_gene" "field_position" "field_score"]] (do-command-while-updates (delete-rows-by-field-cmd table id))))) (do-command-while-updates (format "DELETE FROM `field` WHERE `dataset_id` = %d LIMIT %d" exp batch-size))) ; Deletes an experiment. We break this up into a series ; of commits so other threads are not blocked, and we ; don't time-out the db thread pool. ; XXX Might want to add a "deleting" status to the dataset table? (defn- clear-by-exp [exp] (clear-fields exp) (jdbcd/delete-rows :field ["`dataset_id` = ?" exp])) ; Update meta entity record. (defn- merge-m-ent [ename metadata] (let [normmeta (normalize-meta dataset-meta (json-text (assoc metadata "name" ename))) {id :id} (jdbcd/with-query-results row [(str "SELECT `id` FROM `dataset` WHERE `name` = ?") ename] (first row))] (if id (do (jdbcd/update-values :dataset ["`id` = ?" id] normmeta) id) (-> (jdbcd/insert-record :dataset normmeta) KEY-ID)))) ; ; Hex ; (def ^:private hex-chars (char-array "0123456789ABCDEF")) (defn- bytes->hex [^bytes ba] (let [c (count ba) out ^chars (char-array (* 2 c))] (loop [i 0] (when (< i c) (aset out (* 2 i) (aget ^chars hex-chars (bit-shift-right (bit-and 0xF0 (aget ba i)) 4))) (aset out (+ 1 (* 2 i)) (aget ^chars hex-chars (bit-and 0x0F (aget ba i)))) (recur (inc i)))) (String. out))) ; ; Binary buffer manipulation. ; (defn- sort-float-bytes "Sorts a byte array by float byte order. This makes the bytes very slightly more compressable." [^bytes in] (let [c (count in) fc (/ c 4) out (byte-array c)] (loop [i 0 b1 0 b2 fc b3 (* fc 2) b4 (* fc 3)] (when (< i c) (aset out b1 (aget in i)) (aset out b2 (aget in (+ i 1))) (aset out b3 (aget in (+ i 2))) (aset out b4 (aget in (+ i 3))) (recur (+ i 4) (inc b1) (inc b2) (inc b3) (inc b4)))) out)) ; Pick elements of float array, by index. (defn- apick-float [^floats a idxs] (let [ia (float-array idxs)] (amap ia i ret (aget a i)))) (defn- ashuffle-float [mappings ^floats out ^floats in] (doseq [[i-in i-out] mappings] (aset out i-out (aget in i-in))) out) (defn- bytes-to-floats [^bytes barr] (let [bb (java.nio.ByteBuffer/allocate (alength barr)) fb (.asFloatBuffer bb) out (float-array (quot (alength barr) 4))] (.put bb barr) (.get fb out) out)) (defn- floats-to-bytes [^floats farr] (let [bb (java.nio.ByteBuffer/allocate (* (alength farr) 4)) fb (.asFloatBuffer bb)] (.put fb farr) (.array bb))) ; ; Score encoders ; (def ^:private codec-length (memoize (fn [len] (binary/repeated :float-le :length len)))) (defn- codec [blob] (codec-length (/ (count blob) float-size))) (defn score-decode [blob] (bytes-to-floats blob)) (defn score-encode-orig [slist] (floats-to-bytes (float-array slist))) (defn- score-encodez "Experimental compressing score encoder." [slist] (let [baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (binary/encode (codec-length (count slist)) gzos slist) (.finish gzos) (.toByteArray baos))) (defn- score-sort-encodez "Experimental compressing score encoder that sorts by byte order before compressing." [slist] (let [fbytes (score-encode-orig slist) ^bytes sorted (sort-float-bytes fbytes) baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (.write gzos sorted) (.finish gzos) (.toByteArray baos))) (defn- score-decodez [blob] (let [bais (java.io.ByteArrayInputStream. blob) gzis (java.util.zip.GZIPInputStream. bais)] (binary/decode (binary/repeated :float-le :length 10) gzis))) (def score-encode score-encode-orig) (defn- encode-row [encode row] (mapv encode (partition-all bin-size row))) (defn- encode-fields [encoder matrix-fn] (chunked-pmap #(assoc % :data (encode-row encoder (:scores %))) (:fields (matrix-fn)))) ; ; sequence utilities ; This is a stateful iterator. It may not be idiomatic in clojure, but it's a ; quick way to get sequential ids deep in a call stack. Maybe we should instead ; return a thunk that generates a seq, then zip with the data? (defn- seq-iterator "Create iterator for a seq" [s] (let [a (atom s)] (fn [] (let [s @a] (reset! a (next s)) (first s))))) ; Generates primary keys using range, w/o accessing the db for each next value. ; This works in h2 when doing a csvread when the sequence has been created ; automatically by h2 with the column: h2 will update the sequence while reading ; the rows. It doesn't work if the sequence is create separately from the column. ; In that case h2 will not update the sequence after a csvread. We have to ; create the sequence separately in order to set the cache parameter. (comment (defn- sequence-seq [seqname] (let [[{val :i}] (exec-raw (format "SELECT CURRVAL('%s') AS I" seqname) :results)] (range (+ val 1) Double/POSITIVE_INFINITY 1)))) (comment (defn- sequence-seq "Retrieve primary keys in batches by querying the db" [seqname] (let [cmd (format "SELECT NEXT VALUE FOR %s AS i FROM SYSTEM_RANGE(1, 100)" seqname)] (apply concat (repeatedly (fn [] (-> cmd str (exec-raw :results) (#(map :i %))))))))) ; ; Main loader routines. Here we build a sequence of vectors describing rows to be ; inserted, e.g. ; [:insert-score {:id 1 :scores #<byte[] [B@12345>}] ; (defmulti ^:private load-field (fn [dataset-id field-id column] (-> column :valueType))) (defmethod load-field :default [dataset-id field-id {:keys [field rows]}] (let [data (encode-row score-encode (force rows))] (conj (mapcat (fn [[block i]] [[:insert-field-score {:field_id field-id :i i :scores block}]]) (map vector (consume-vec data) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}]))) ; This should be lazy to avoid simultaneously instantiating all the rows as ; individual objects. (defmethod load-field "position" [dataset-id field-id {:keys [field rows]}] (conj (for [[position row] (map vector (force rows) (range))] [:insert-position (assoc position :field_id field-id :row row :bin (calc-bin (:chromStart position) (:chromEnd position)))]) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defmethod load-field "genes" [dataset-id field-id {:keys [field rows row-val]}] (conj (mapcat (fn [[genes row]] (for [gene (row-val genes)] [:insert-gene {:field_id field-id :row row :gene gene}])) (map vector (consume-vec (force rows)) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defn- inferred-type "Replace the given type with the inferred type" [fmeta row] (assoc fmeta "valueType" (:valueType row))) (defn- load-field-feature [feature-seq field-seq dataset-id field] (let [field-id (field-seq)] (concat (load-field dataset-id field-id field) (when-let [feature (force (:feature field))] (load-probe-meta feature-seq field-id (inferred-type feature field)))))) ; ; ; ; Table writer that updates tables as rows are read. ; ; (defn- quote-ent [x] (str \` (name x) \`)) (defn- insert-stmt ^cavm.statement.PStatement [table fields] (let [field-str (clojure.string/join ", " (map quote-ent fields)) val-str (clojure.string/join ", " (repeat (count fields), "?")) stmt-str (format "INSERT INTO %s(%s) VALUES (%s)" (quote-ent table) field-str val-str)] (sql-stmt (jdbcd/find-connection) stmt-str fields))) (defn- sequence-stmt ^cavm.statement.PStatement [db-seq] (sql-stmt-result (jdbcd/find-connection) (format "SELECT NEXT VALUE FOR %s AS i" db-seq))) (defn- run-delays [m] (into {} (for [[k v] m] [k (force v)]))) (def ^:private max-insert-retry 20) (defn trunc [^String s n] (subs s 0 (min (.length s) n))) (defn- numbered-suffix [n] (if (== 1 n) "" (str " (" n ")"))) (defn- table-writer-default [dir dataset-id matrix-fn] (with-open [code-stmt (insert-stmt :code [:value :id :ordering :field_id]) position-stmt (insert-stmt :field_position [:field_id :row :bin :chrom :chromStart :chromEnd :strand]) gene-stmt (insert-stmt :field_gene [:field_id :row :gene]) feature-stmt (insert-stmt :feature [:id :field_id :shortTitle :longTitle :priority :valueType :visibility]) field-stmt (insert-stmt :field [:id :dataset_id :name]) field-score-stmt (insert-stmt :field_score [:field_id :scores :i]) field-seq-stmt (sequence-stmt "FIELD_IDS") feature-seq-stmt (sequence-stmt "FEATURE_IDS")] ; XXX change these -seq functions to do queries returning vectors & ; simplify the destructuring. Or better, stop asking the db for ids and ; generate them ourselves. Getting ids is the slowest bit, even with a large ; cache. (let [feature-seq #(delay (-> (feature-seq-stmt []) first :i)) field-seq #(delay (-> (field-seq-stmt []) first :i)) ; XXX try memoization again? ; score-id-fn (memoize-key (comp ahashable first) scores-seq) writer {:insert-field field-stmt :insert-field-score field-score-stmt :insert-position position-stmt :insert-feature feature-stmt :insert-code code-stmt :insert-gene gene-stmt} row-count (atom 0) data (matrix-fn) warnings (atom (meta data)) last-log (atom 0) inserts (lazy-mapcat #(do (swap! row-count max (count (force (:rows %)))) (load-field-feature feature-seq field-seq dataset-id %)) data)] (doseq [insert-batch (partition-all batch-size inserts)] (jdbcd/transaction (doseq [[insert-type values] insert-batch] (when (= :insert-field insert-type) (let [t (System/currentTimeMillis)] (when (> (- t @last-log) 10000) (trace "writing" (:name values)) (reset! last-log t)))) (let [values (run-delays values) values (if (and (= :insert-field insert-type) (> (.length ^String (:name values)) max-probe-length)) (do (swap! warnings update-in ["too-long-probes"] conj (:name values)) (warn "Too-long probe" (:name values)) (update-in values [:name] trunc max-probe-length)) values) write (fn write [i] ; on field inserts we retry on certain failures, with sanitized probe ids. (let [values (if (= :insert-field insert-type) (update-in values [:name] str (numbered-suffix i)) values)] ; On primary key violations, try to rename probes. If we can't find a usable ; name after max-insert-retry attempts, let the dataset error out. It's probably ; a severe error, like wrong column being used as probe id. (try ((writer insert-type) values) (catch JdbcBatchUpdateException ex (cond (and (= :insert-field insert-type) ; h2 concats the english message after ; the localized message, so using ; .contains. (.contains (.getMessage ex) "Unique index") (< i max-insert-retry)) (do (swap! warnings update-in ["duplicate-probes"] conj (:name values)) (warn "Duplicate probe" (:name values)) (write (inc i))) :else (throw ex))))))] (write 1))))) {:rows @row-count :warnings @warnings}))) ; ; ; Table writer that updates one table at a time by writing to temporary files. ; ; Currently not functioning. Needs update for new schema. (defn- insert-field-out [^java.io.BufferedWriter out seqfn dataset-id name] (let [field-id (seqfn)] (.write out (str field-id "\t" dataset-id "\t" name "\n")) field-id)) (defn- insert-scores-out [^java.io.BufferedWriter out seqfn slist] (let [score-id (seqfn)] (.write out (str score-id "\t" (:hex slist) "\n")) score-id)) (defn- insert-field-score-out [^java.io.BufferedWriter out field-id i score-id] (.write out (str field-id "\t" i "\t" score-id "\n"))) (def ^:private table-writer #'table-writer-default) (let [fmtr (formatter "yyyy-MM-dd hh:mm:ss")] (defn- format-timestamp ^String [timestamp] (unparse fmtr timestamp))) (defn- fmt-time [file-meta] (assoc file-meta :time (. java.sql.Timestamp valueOf (format-timestamp (:time file-meta))))) ; XXX test this ; XXX and call it somewhere. (defn- clean-sources [] (jdbcd/delete-rows :source ["`id` NOT IN (SELECT DISTINCT `source_id` FROM `dataset_source)"])) (defn- load-related-sources [table id-key id files] (jdbcd/delete-rows table [(str (name id-key) " = ?") id]) (let [sources (map #(-> (jdbcd/insert-record :source %) KEY-ID) files)] (doseq [source-id sources] (jdbcd/insert-record table {id-key id :source_id source-id})))) (defn- related-sources [id] (jdbcd/with-query-results rows ["SELECT `source`.`name`, `hash`, `time` FROM `dataset` JOIN `dataset_source` ON `dataset_id` = `dataset`.`id` JOIN `source` on `source_id` = `source`.`id` WHERE `dataset`.`id` = ?" id] (vec rows))) (defn- record-exception [dataset-id ex] (jdbcd/with-query-results rows ["SELECT `text` FROM `dataset` WHERE `dataset`.`id` = ?" dataset-id] (let [[{text :text :or {text "{}"}}] rows metadata (json/read-str text)] (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:text (json/write-str (assoc metadata "error" (str ex)) :escape-slash false)})))) (defn- with-load-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loading"}) (func) (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loaded"}) (catch Exception ex (warn ex "Error loading dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-load-status [dataset-id & body] `(with-load-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (defn- with-delete-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "deleting"}) (func) (catch Exception ex (warn ex "Error deleting dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-delete-status [dataset-id & body] `(with-delete-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (def max-warnings 10) (defn- truncate-warnings [warnings] (-> warnings (update-in ["duplicate-keys" "sampleID"] #(take max-warnings %)) (update-in ["duplicate-probes"] #(take max-warnings %)))) ; jdbcd/transaction will create a closure of our parameters, ; so we can't pass in the matrix seq w/o blowing the heap. We ; pass in a function to return the seq, instead. ; files: the files this matrix was loaded from, e.g. clinical & genomic matrix, plus their timestamps & file hashes ; metadata: the metadata for the matrix (should cgdata mix in the clinical metadata?) ; matrix-fn: function to return seq of data rows ; features: field metadata. Need a better name for this. (defn- load-dataset "Load matrix file and metadata. Skips the data load if file hashes are unchanged, and 'force' is false. Metadata is always updated." ([mname files metadata matrix-fn features] (load-dataset mname files metadata matrix-fn features false)) ([mname files metadata matrix-fn features force] (profile :trace :dataset-load (let [dataset-id (jdbcd/transaction (merge-m-ent mname metadata)) files (map fmt-time files)] (with-load-status dataset-id (when (or force (not (= (set files) (set (related-sources dataset-id))))) (p :dataset-clear (clear-by-exp dataset-id)) (p :dataset-sources (load-related-sources :dataset_source :dataset_id dataset-id files)) (p :dataset-table (let [{:keys [rows warnings]} (table-writer *tmp-dir* dataset-id matrix-fn)] (jdbcd/transaction (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:rows rows}) (when warnings (merge-m-ent mname (assoc metadata :loader (truncate-warnings warnings))))))))))))) (defn- dataset-by-name [dname & kprops] (let [props (clojure.string/join "," (map name kprops))] (jdbcd/with-query-results rows [(format "SELECT %s FROM `dataset` WHERE `name` = ?" props) (str dname)] (-> rows first)))) (def dataset-id-by-name (comp :id #(dataset-by-name % :id))) (defn delete-dataset [dataset] (let [dataset-id (dataset-id-by-name dataset)] (if dataset-id (with-delete-status dataset-id (clear-by-exp dataset-id) (jdbcd/do-commands (format "DELETE FROM `dataset` WHERE `id` = %d" dataset-id))) (info "Did not delete unknown dataset" dataset)))) (defn create-db [file & [{:keys [classname subprotocol make-pool?] :or {classname "org.h2.Driver" subprotocol "h2" make-pool? true}}]] (let [spec {:classname classname :subprotocol subprotocol :subname file :conn-customizer "conn_customizer" :make-pool? make-pool?}] (if make-pool? (delay (pool spec)) (delay (-> spec))))) ; XXX should sanitize the query (defn- run-query [q] (jdbcd/with-query-results rows (spy :trace (hsql/format q)) (vec rows))) ; ; Code queries ; (def ^:private codes-for-field-query (cached-statement "SELECT `ordering`, `value` FROM `field` JOIN `code` ON `field_id` = `field`.`id` WHERE `name` = ? AND `dataset_id` = ?" true)) (defn- codes-for-field [dataset-id field] (->> (codes-for-field-query field dataset-id) (map #(mapv % [:value :ordering])) (into {}))) ; ; All rows queries. ; ; All bins for the given fields. ; XXX inner join here? really? not just a where? (def ^:private all-rows-query (cached-statement "SELECT `name`, `i`, `scores` FROM (SELECT `name`, `id` FROM `field` INNER JOIN (TABLE(`name2` VARCHAR = ?) T) ON `name2` = `field`.`name` WHERE `dataset_id` = ?) AS P LEFT JOIN `field_score` ON `P`.`id` = `field_score`.`field_id`" true)) ; bins will all be the same size, except the last one. bin size is thus ; max of count of first two bins. ; Loop over bins, copying into pre-allocated output array. ; {"foxm1" [{:name "foxm1" :scores <bytes>} ... ] (defn concat-field-bins [bins] (let [float-bins (mapv #(update-in % [:scores] score-decode) bins) sizes (mapv #(count (:scores %)) float-bins) bin-size (apply max (take 2 sizes)) row-count (apply + sizes) out (float-array row-count)] (doseq [{:keys [scores i]} float-bins] (System/arraycopy scores 0 out (* i bin-size) (count scores))) ; XXX mutate "out" in place out)) ; return float arrays of all rows for the given fields (defn- all-rows [dataset-id fields] (let [field-bins (->> (all-rows-query (to-array fields) dataset-id) (group-by :name))] (into {} (for [[k v] field-bins] [k (concat-field-bins v)])))) ; ; ; (defn bin-offset [i] [(quot i bin-size) (rem i bin-size)]) ; merge bin number and bin offset for a row (defn- merge-bin-off [{i :i :as row}] (merge row {:bin (quot i bin-size) :off (rem i bin-size)})) ; Returns mapping from input bin offset to output buffer for a ; given row. (defn- bin-mapping [{off :off row :order}] [off row]) ; Gets called once for each bin in the request. ; order is row -> order in output buffer. ; bin is the bin for the given set of rows ; rows is ({:i 12 :bin 1 :off 1}, ... ), where all :bin are the same (defn- pick-rows-fn [[bin rows]] [bin (partial ashuffle-float (map bin-mapping rows))]) ; Take an ordered list of requested rows, and generate fns to copy ; values from a score bin to an output array. Returns one function ; for each score bin in the request. ; ; rows ({:i 12 :bin 1 :off 1}, ... ) (defn- pick-rows-fns [rows] (let [by-bin (group-by :bin rows)] (apply hash-map (mapcat pick-rows-fn by-bin)))) ; Take map of bin copy fns, list of scores rows, and a map of output arrays, ; copying the scores to the output arrays via the bin copy fns. (defn- build-score-arrays [rows bfns out] (doseq [{i :i scores :scores field :name} rows] ((bfns i) (out field) scores)) out) (defn- col-arrays [columns n] (zipmap columns (repeatedly (partial float-array n Double/NaN)))) ; Doing an inner join on a table literal, instead of a big IN clause, so it will hit ; the index. ; XXX performance of the :in clause? ; XXX make a prepared statement ; Instead of building a custom query each time, this can be ; rewritten as a join against a TABLE literal, or as ; IN (SELECT * FROM TABLE(x INT = (?))). Should check performance ; of both & drop the (format) call. (def ^:private dataset-fields-query "SELECT name, i, scores FROM (SELECT `field`.`name`, `field`.`id` FROM `field` INNER JOIN TABLE(name varchar=?) T ON T.`name`=`field`.`name` WHERE (`field`.`dataset_id` = ?)) P LEFT JOIN `field_score` ON P.id = `field_score`.`field_id` WHERE `field_score`.`i` IN (%s)") (defn- select-scores-full [dataset-id columns bins] (let [q (format dataset-fields-query (clojure.string/join "," (repeat (count bins) "?"))) c (to-array (map str columns)) i bins] (jdbcd/with-query-results rows (vec (concat [q c dataset-id] i)) (vec rows)))) ; Returns rows from (dataset-id column-name) matching ; values. Returns a hashmap for each matching row. ; { :i The implicit index in the column as stored on disk. ; ;order The order of the row the result set. ; :value The value of the row. ; } (defn- rows-matching [dataset-id column-name values] (let [val-set (set values)] (->> column-name (vector) (all-rows dataset-id) ; Retrieve the full column (vals) (first) ; calculate row index in the column (map #(-> {:i %1 :value %2}) (range)) ; [{:i 0 :value 1.2} ...] (filter (comp val-set :value)) ; filter rows not matching the request. (group-by :value) (#(map (fn [g] (get % g [nil])) values)) ; arrange by output order. (apply concat) ; flatten groups. (mapv #(assoc %2 :order %1) (range))))) ; assoc row output order. (defn- float-nil [x] (when x (float x))) ; Get codes for samples in request ; Get the entire sample column ; Find the rows matching the samples, ordered by sample list ; Have to scan the sample column, group by sample, and map over the ordering ; Build shuffle functions, per bin, to copy bins to output buffer ; Run scores query ; Copy to output buffer (defn- genomic-read-req [req] (let [{:keys [samples table columns]} req dataset-id (dataset-id-by-name table) samp->code (codes-for-field dataset-id "sampleID") order (mapv (comp float-nil samp->code) samples) ; codes in request order rows (rows-matching dataset-id "sampleID" order) rows-to-copy (->> rows (filter :value) (mapv merge-bin-off)) bins (mapv :bin rows-to-copy) ; list of bins to pull. bfns (pick-rows-fns rows-to-copy)] ; make fns that map from input bin to ; output buffer, one fn per input bin. (-> (select-scores-full dataset-id columns (distinct bins)) (#(mapv cvt-scores %)) (build-score-arrays bfns (col-arrays columns (count rows)))))) ; ; ; Methods for providing a sql abstraction over the column store. ; ; (def ^:private field-ids-query (cached-statement "SELECT `id`, `name` FROM `field` WHERE `dataset_id` = ? AND `name` IN (SELECT * FROM TABLE(x VARCHAR = (?)))" true)) (defn- fetch-field-ids [dataset-id names] (when-let [ids (field-ids-query dataset-id names)] (map (juxt :name :id) ids))) ; (def ^:private codes-for-values-query (cached-statement "SELECT `ordering`, `value` FROM `code` JOIN TABLE(x INT = (?)) V on `x` = `ordering` WHERE `field_id` = ?" true)) (defn- codes-for-values [field-id values] (when-let [codes (codes-for-values-query values field-id)] (map (juxt :ordering :value) codes))) ; (def ^:private field-bins-query (cached-statement "SELECT `scores`, `i` FROM `field_score` WHERE `field_id` = ? AND `i` IN (SELECT * FROM TABLE(x INT = (?)))" true)) (defn- fetch-bins [field-id bins] (when-let [scores (field-bins-query field-id bins)] (map #(update-in % [:scores] bytes-to-floats) scores))) ; (def ^:private has-codes-query (cached-statement "SELECT EXISTS(SELECT `ordering` FROM `code` WHERE `field_id` = ?) hascodes" true)) (defn has-codes? [field-id] (-> (has-codes-query field-id) first :hascodes)) ; (def ^:private has-genes-query (cached-statement "SELECT EXISTS(SELECT `gene` FROM `field_gene` WHERE `field_id` = ?) hasgenes" true)) (defn has-genes? [field-id] (-> (has-genes-query field-id) first :hasgenes)) ; (def ^:private has-position-query (cached-statement "SELECT EXISTS(SELECT `bin` FROM `field_position` WHERE `field_id` = ?) hasposition" true)) (defn has-position? [field-id] (-> (has-position-query field-id) first :hasposition)) ; (defn update-codes-cache [codes field-id new-bins cache] (match [codes] [nil] (update-codes-cache (if (has-codes? field-id) [:yes {}] [:no]) field-id new-bins cache) [[:no]] codes [[:yes code-cache]] [:yes (let [values (distinct (mapcat cache new-bins)) missing (filterv #(not (contains? code-cache %)) values)] (into code-cache (codes-for-values field-id missing)))])) (defn update-cache [cache field-id rows] (let [bins (distinct (map #(quot % bin-size) rows)) missing (filterv #(not (contains? cache %)) bins)] (if (seq missing) (let [new-cache (->> missing (fetch-bins field-id) (map (juxt :i :scores)) (into (or cache {})))] (update-in new-cache [:codes] update-codes-cache field-id missing new-cache)) cache))) ; ; ; return fn of rows->vals ; (defmulti fetch-rows (fn [cache rows field-id] (cond (has-genes? field-id) :gene (has-position? field-id) :position :else :binned))) ; binned fields (defmethod fetch-rows :binned [cache rows field-id] (swap! cache update-in [field-id] update-cache field-id rows) (let [f (@cache field-id) getter (match [(:codes f)] ; XXX cast to int here is pretty horrible. ; Really calls for an int array bin in h2. [[:yes vals->codes]] (fn [bin off] (let [v (aget ^floats (f bin) off)] (if (. Float isNaN v) nil (vals->codes (int v))))) [[:no]] (fn [bin off] (get (f bin) off)))] (fn [row] (apply getter (bin-offset row))))) (def ^:private field-genes-by-row-query (cached-statement "SELECT `row`, `gene` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) (defn field-genes-by-row [field-id rows] (->> (field-genes-by-row-query rows field-id) (group-by :row) (map (fn [[k rows]] [k (mapv :gene rows)])))) ; gene fields (defmethod fetch-rows :gene [cache rows field-id] (into {} (field-genes-by-row field-id rows))) (def ^:private field-position-by-row-query (cached-statement "SELECT `row`, `chrom`, `chromStart`, `chromEnd`, `strand` FROM `field_position` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) ; position fields (defn field-position-by-row [field-id rows] (->> (field-position-by-row-query rows field-id) (map (fn [{:keys [row] :as values}] [row (dissoc values :row)])))) (defmethod fetch-rows :position [cache rows field-id] (into {} (field-position-by-row field-id rows))) ; ; Indexed field lookups (gene & position) ; (defn has-index? [fields field] (let [field-id (fields field)] (or (has-genes? field-id) (has-position? field-id)))) ; gene ; Selecting `gene` as well adds a lot to the query time. Might ; need it if we need to cache gene names. (def ^:private field-genes-query (cached-statement "SELECT `row` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `gene` WHERE `field_id` = ?" true)) (defn field-genes [field-id genes] (->> (field-genes-query genes field-id) (map :row))) (defn fetch-genes [field-id values] (into (i/int-set) (field-genes field-id values))) ; position (def ^:private field-position-one-query (cached-statement "SELECT `row` FROM `field_position` WHERE `field_id` = ? AND `chrom` = ? AND (`bin` >= ? AND `bin` <= ?) AND `chromStart` <= ? AND `chromEnd` >= ?" true)) ; [:in "position" [["chr17" 100 20000]]] (defn field-position [field-id values] (->> (mapcat (fn [[chr start end]] (let [istart (int start) iend (int end) bins (overlapping-bins istart iend)] (mapcat (fn [[s e]] (field-position-one-query field-id chr s e iend istart)) bins))) values) (map :row))) (defn fetch-position [field-id values] (into (i/int-set) (field-position field-id values))) ; fetch-indexed doesn't cache, and it's unclear ; if we should cache the indexed fields during 'restrict'. ; h2 also has caches, so it might be better to rely on them, ; simply doing the query again if we need it. ; Otherwise, we might want to inform the cache of what columns are ; required later during 'restrict', or in 'project', so ; we know if they should be cached. (defn fetch-indexed [fields field values] (let [field-id (fields field)] (cond (has-position? field-id) (fetch-position field-id values) (has-genes? field-id) (fetch-genes field-id values)))) ; ; sql eval methods ; ; might want to use a reader literal for field names, so we ; find them w/o knowing syntax. (defn collect-fields [exp] (match [exp] [[:in field _]] [field] [[:in arrmod field _]] [field] [[:and & subexps]] (mapcat collect-fields subexps) [[:or & subexps]] (mapcat collect-fields subexps) [nil] [])) ; ; Computing the "set of all rows" to begin a query was taking much too long ; (minutes, for tens of millions of rows). Switching from sorted-set to int-set ; brought this down to tens of seconds, which was still too slow. Here we ; generate the int-set in parallel & merge with i/union, which is fast. This ; brings the time down to a couple seconds for tens of millions of rows. We ; then, additionally, cache the set, and re-use it if possible. We can ; quickly create smaller sets with i/range, so we memoize such that we ; compute a new base set only if the current memoized size is too small. ; ; Note that this means that if we load a very large dataset, then delete it, ; the memory required to represent all the rows of that dataset is not released ; until the server is restarted. ; ; Alternative fixes might be 1) use an agent to always maintain the largest ; "set of all rows" required for the loaded datasets, updating on dataset add/remove; ; 2) using a different representation of contiguous rows, e.g. [start, end]. We ; would need to review the down-stream performance implications of this (i.e. computing ; union and intersection, generating db queries, etc.) (def block-size 1e6) (defn int-set-bins [n] (let [blocks (+ (quot n block-size) (if (= 0 (rem n block-size)) 0 1))] (map (fn [i] [(* i block-size) (min (* (+ i 1) block-size) n)]) (range blocks)))) (defn set-of-all [n] (let [blocks (/ n block-size)] (reduce #(i/union % %2) (pmap (fn [[start end]] (into (i/int-set) (range start end))) (int-set-bins n))))) (defn mem-min [f] (let [mem (atom nil)] (fn [n] (if (> n (count @mem)) (let [ret (f n)] (reset! mem ret) ret) (i/range @mem 0 (- n 1)))))) (def set-of-all-cache (mem-min set-of-all)) ; XXX Look at memory use of pulling :gene field. If it's not ; interned, it could be expensive. ; XXX Map keywords to strings, for dataset & field names? ; XXX Add some param guards, esp. unknown field. (defn eval-sql [{[from] :from where :where select :select :as exp}] (let [{dataset-id :id N :rows} (dataset-by-name from :id :rows) fields (into {} (fetch-field-ids dataset-id (into (collect-fields where) select))) cache (atom {}) fetch (fn [rows field] (if (not-empty rows) (fetch-rows cache rows (fields field)) {}))] (evaluate (set-of-all-cache N) {:fetch fetch :fetch-indexed (partial fetch-indexed fields) :indexed? (partial has-index? fields)} exp))) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["sampleID"] :from ["BRCA1"] :where [:in "sampleID" ; ["HG00122" "NA07056" "HG01870" "NA18949" "HG02375" ; "HG00150" "NA18528" "HG02724"]]})) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["alt"] :from ["BRCA1"] :where [:in "position" [["chr17" 10000 100000000]]]})) ; ; ; ; ; ; ; Each req is a map of ; :table "tablename" ; :columns '("column1" "column2") ; :samples '("sample1" "sample2") ; We merge into 'data the columns that we can resolve, like ; :data { 'column1 [1.1 1.2] 'column2 [2.1 2.2] } (defn- genomic-source [reqs] (map #(update-in % [:data] merge (genomic-read-req %)) reqs)) ; ; hand-spun migrations. ; (def column-len-query "SELECT character_maximum_length as len FROM information_schema.columns as c WHERE c.table_name = ? AND c.column_name = ?") (def bad-probemap-query "SELECT `dataset`.`name` FROM `dataset` LEFT JOIN `dataset` as d ON d.`name` = `dataset`.`probemap` WHERE `dataset`.`probeMap` IS NOT NULL AND d.`name` IS NULL") (defn delete-if-probemap-invalid [] (jdbcd/with-query-results bad-datasets [bad-probemap-query] (doseq [{dataset :name} bad-datasets] (delete-dataset dataset)))) ; dataset.probemap refers to a dataset.name, but previously ; had different data size, and was not enforced as a foreign ; key. Check for old data size, and run migration if it's old ; ; The migration will delete datasets that have invalid probemap, ; and update the field. (defn migrate-probemap [] (jdbcd/with-query-results pm-key [column-len-query "DATASET" "PROBEMAP"] (when (and (seq pm-key) (= (:len (first pm-key)) 255)) (info "Migrating probeMap field") (delete-if-probemap-invalid) (jdbcd/do-commands "AlTER TABLE `dataset` ALTER COLUMN `probeMap` VARCHAR(1000)" "ALTER TABLE `dataset` ADD FOREIGN KEY (`probeMap`) REFERENCES `dataset` (`name`)")))) (defn- migrate [] (migrate-probemap) ; ...add more here ) (defn- create[] (jdbcd/transaction (apply jdbcd/do-commands cohorts-table) (apply jdbcd/do-commands source-table) (apply jdbcd/do-commands dataset-table) (apply jdbcd/do-commands dataset-source-table) (apply jdbcd/do-commands field-table) (apply jdbcd/do-commands field-score-table) (apply jdbcd/do-commands feature-table) (apply jdbcd/do-commands code-table) (apply jdbcd/do-commands field-position-table) (apply jdbcd/do-commands field-gene-table)) (migrate)) ; ; add TABLE handling for honeysql ; (defmethod hsqlfmt/format-clause :table [[_ [fields alias]] _] (str "TABLE(" (clojure.string/join ", " (map (fn [[name type values]] (str (hsqlfmt/to-sql name) " " (hsqlfmt/to-sql type) "=" (hsqlfmt/paren-wrap (clojure.string/join ", " (map hsqlfmt/to-sql values))))) fields)) ") " (hsqlfmt/to-sql alias))) ; Fix GROUP_CONCAT in honeysql (defn- format-concat ([value {:keys [order separator]}] (let [oclause (if (nil? order) "" (str " order by " (hsqlfmt/to-sql order))) sclause (if (nil? separator) "" (str " separator " (hsqlfmt/to-sql separator)))] (str "GROUP_CONCAT(" (hsqlfmt/to-sql value) oclause sclause ")")))) (defmethod hsqlfmt/fn-handler "group_concat" [_ value & args] (format-concat value args)) (defrecord H2Db [db]) (extend-protocol XenaDb H2Db (write-matrix [this mname files metadata data-fn features always] (jdbcd/with-connection @(:db this) (load-dataset mname files metadata data-fn features always))) (delete-matrix [this mname] (jdbcd/with-connection @(:db this) (delete-dataset mname))) (run-query [this query] (jdbcd/with-connection @(:db this) (run-query query))) (column-query [this query] (jdbcd/with-connection @(:db this) (eval-sql query))) (fetch [this reqs] (jdbcd/with-connection @(:db this) (doall (genomic-source reqs)))) (close [this] ; XXX test for pool, or datasource before running? (.close ^ComboPooledDataSource (:datasource @(:db this)) false))) (defn create-xenadb [& args] (let [db (apply create-db args)] (jdbcd/with-connection @db (create)) (H2Db. db)))
70744
(ns ^{:author "<NAME>" :doc "Xena H2 database backend"} cavm.h2 (:require [clojure.java.jdbc.deprecated :as jdbcd]) (:require [clojure.java.jdbc :as jdbc]) (:require [cavm.jdbc]) (:require [org.clojars.smee.binary.core :as binary]) (:require [clojure.java.io :as io]) (:require [honeysql.core :as hsql]) (:require [honeysql.format :as hsqlfmt]) (:require [honeysql.types :as hsqltypes]) (:require [cavm.json :as json]) (:require [cavm.binner :refer [calc-bin overlapping-bins]]) (:use [clj-time.format :only (formatter unparse)]) (:use [cavm.hashable :only (ahashable)]) (:require [cavm.db :refer [XenaDb]]) (:require [clojure.tools.logging :refer [spy trace info warn]]) (:require [taoensso.timbre.profiling :refer [profile p]]) (:require [clojure.core.cache :as cache]) (:require [cavm.statement :refer [sql-stmt sql-stmt-result cached-statement]]) (:require [cavm.conn-pool :refer [pool]]) (:require [cavm.lazy-utils :refer [consume-vec lazy-mapcat]]) (:require [clojure.core.match :refer [match]]) (:require [cavm.sqleval :refer [evaluate]]) (:require [clojure.data.int-map :as i]) (:import [org.h2.jdbc JdbcBatchUpdateException]) (:import [com.mchange.v2.c3p0 ComboPooledDataSource])) (def h2-log-level (into {} (map vector [:off :error :info :debug :slf4j] (range)))) ; ; Note that "bin" in this file is like a "segement" in the column store ; literature: a column is split into a series of segments (bins) before ; writing to disk (saving as blob in h2). ; (def ^:dynamic ^:private *tmp-dir* (System/getProperty "java.io.tmpdir")) (defn set-tmp-dir! [dir] (alter-var-root #'*tmp-dir* (constantly dir))) ; Coerce this sql fn name to a keyword so we can reference it. (def ^:private KEY-ID (keyword "<KEY>")) (def ^:private float-size 4) (def ^:private bin-size 1000) (def ^:private score-size (* float-size bin-size)) ; Add 30 for gzip header ;( def score-size (+ 30 (* float-size bin-size))) ; row count for batch operations (e.g. insert/delete) (def ^:private batch-size 1000) ; ; Utility functions ; (defn- chunked-pmap [f coll] (->> coll (partition-all 250) (pmap (fn [chunk] (doall (map f chunk)))) (apply concat))) (defn- memoize-key "Memoize with the given function of the arguments" [kf f] (let [mem (atom {})] (fn [& args] (let [k (kf args)] (if-let [e (find @mem k)] (val e) (let [ret (apply f args)] (swap! mem assoc k ret) ret)))))) ; ; Table models ; (declare score-decode) (defn- cvt-scores [{scores :scores :as v}] (if scores (assoc v :scores (float-array (score-decode scores))) v)) ; ; Table definitions. ; (def ^:private max-probe-length 250) (def ^:private probe-version-length 5) ; to disambiguate probes by appending " (dd)" ; Note H2 has one int type: signed, 4 byte. Max is approximately 2 billion. (def ^:private field-table ["CREATE SEQUENCE IF NOT EXISTS FIELD_IDS CACHE 2000" (format "CREATE TABLE IF NOT EXISTS `field` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FIELD_IDS PRIMARY KEY, `dataset_id` INT NOT NULL, `name` VARCHAR(%d), UNIQUE(`dataset_id`, `name`), FOREIGN KEY (`dataset_id`) REFERENCES `dataset` (`id`) ON DELETE CASCADE)" (+ max-probe-length probe-version-length))]) (def ^:private field-score-table [(format "CREATE TABLE IF NOT EXISTS `field_score` ( `field_id` INT NOT NULL, `i` INT NOT NULL, `scores` VARBINARY(%d) NOT NULL, UNIQUE (`field_id`, `i`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" score-size)]) (def ^:private cohorts-table ["CREATE TABLE IF NOT EXISTS `cohorts` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL UNIQUE)"]) ; XXX What should max file name length be? ; XXX Unique columns? Indexes? (def ^:private source-table ["CREATE TABLE IF NOT EXISTS `source` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL, `time` TIMESTAMP NOT NULL, `hash` VARCHAR(40) NOT NULL)"]) (def ^:private dataset-table ["CREATE TABLE IF NOT EXISTS `dataset` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(1000) NOT NULL UNIQUE, `probeMap` VARCHAR(255), `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `groupTitle` VARCHAR(255), `platform` VARCHAR(255), `cohort` VARCHAR(1000), `security` VARCHAR(255), `rows` INT, `status` VARCHAR(20), `text` VARCHAR (65535), `type` VARCHAR (255), `dataSubType` VARCHAR (255))"]) (def ^:private dataset-columns #{:name :probeMap :shortTitle :longTitle :groupTitle :platform :cohort :security :dataSubType :type :text}) (def ^:private dataset-defaults (into {} (map #(vector % nil) dataset-columns))) (def ^:private dataset-source-table ["CREATE TABLE IF NOT EXISTS `dataset_source` ( `dataset_id` INT NOT NULL, `source_id` INT NOT NULL, FOREIGN KEY (dataset_id) REFERENCES `dataset` (`id`) ON DELETE CASCADE, FOREIGN KEY (source_id) REFERENCES `source` (`id`) ON DELETE CASCADE)"]) (def ^:private dataset-meta {:defaults dataset-defaults :columns dataset-columns}) ; XXX CASCADE might perform badly. Might need to do this incrementally in application code. (def ^:private field-position-table ["CREATE TABLE IF NOT EXISTS `field_position` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `bin` INT, `chrom` VARCHAR(255) NOT NULL, `chromStart` INT NOT NULL, `chromEnd` INT NOT NULL, `strand` CHAR(1), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS chrom_bin ON field_position (`field_id`, `chrom`, `bin`)" "CREATE INDEX IF NOT EXISTS position_row ON field_position (`field_id`, `row`)"]) (def ^:private field-gene-table ["CREATE TABLE IF NOT EXISTS `field_gene` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `gene` VARCHAR_IGNORECASE(255) NOT NULL, FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS field_gene ON `field_gene` (`field_id`, `gene`)" "CREATE INDEX IF NOT EXISTS gene_row ON `field_gene` (`field_id`, `row`)"]) ; ; feature tables ; (def ^:private feature-table ["CREATE SEQUENCE IF NOT EXISTS FEATURE_IDS CACHE 2000" "CREATE TABLE IF NOT EXISTS `feature` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FEATURE_IDS PRIMARY KEY, `field_id` INT(11) NOT NULL, `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `priority` DOUBLE DEFAULT NULL, `valueType` VARCHAR(255) NOT NULL, `visibility` VARCHAR(255), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (def ^:private feature-columns #{:shortTitle :longTitle :priority :valueType :visibility}) (def ^:private feature-defaults (into {} (map #(vector % nil) feature-columns))) (def ^:private feature-meta {:defaults feature-defaults :columns feature-columns}) ; Order is important to avoid creating duplicate indexes. A foreign ; key constraint creates an index if one doesn't exist, so create our ; index before adding the constraint. ; XXX varchar size is pushing it. Do we need another type for clob-valued ; fields? (def ^:private code-table ["CREATE TABLE IF NOT EXISTS `code` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `field_id` INT(11) NOT NULL, `ordering` INT(10) unsigned NOT NULL, `value` VARCHAR(16384) NOT NULL, UNIQUE (`field_id`, `ordering`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (defn- normalize-meta [m-ent metadata] (-> metadata (clojure.walk/keywordize-keys) (#(merge (:defaults m-ent) %)) (select-keys (:columns m-ent)))) (defn- json-text [md] (assoc md :text (json/write-str md :escape-slash false))) (defn- load-probe-meta [feature-seq field-id {:keys [order] :as feat}] (let [feature-id (feature-seq) fmeta (merge (normalize-meta feature-meta feat) {:field_id field-id :id feature-id})] (cons [:insert-feature (assoc fmeta :id feature-id)] (for [[value ordering] order] [:insert-code {:field_id field-id :ordering ordering :value value}])))) ; ; ; (defn do-command-while-updates [cmd] (while (> (first (jdbcd/do-commands cmd)) 0))) (defn delete-rows-by-field-cmd [table field] (format "DELETE FROM `%s` WHERE `field_id` = %d LIMIT %d" table field batch-size)) (defn- clear-fields [exp] (jdbcd/with-query-results field ["SELECT `id` FROM `field` WHERE `dataset_id` = ?" exp] (doseq [{id :id} field] (doseq [table ["code" "feature" "field_gene" "field_position" "field_score"]] (do-command-while-updates (delete-rows-by-field-cmd table id))))) (do-command-while-updates (format "DELETE FROM `field` WHERE `dataset_id` = %d LIMIT %d" exp batch-size))) ; Deletes an experiment. We break this up into a series ; of commits so other threads are not blocked, and we ; don't time-out the db thread pool. ; XXX Might want to add a "deleting" status to the dataset table? (defn- clear-by-exp [exp] (clear-fields exp) (jdbcd/delete-rows :field ["`dataset_id` = ?" exp])) ; Update meta entity record. (defn- merge-m-ent [ename metadata] (let [normmeta (normalize-meta dataset-meta (json-text (assoc metadata "name" ename))) {id :id} (jdbcd/with-query-results row [(str "SELECT `id` FROM `dataset` WHERE `name` = ?") ename] (first row))] (if id (do (jdbcd/update-values :dataset ["`id` = ?" id] normmeta) id) (-> (jdbcd/insert-record :dataset normmeta) KEY-ID)))) ; ; Hex ; (def ^:private hex-chars (char-array "0123456789ABCDEF")) (defn- bytes->hex [^bytes ba] (let [c (count ba) out ^chars (char-array (* 2 c))] (loop [i 0] (when (< i c) (aset out (* 2 i) (aget ^chars hex-chars (bit-shift-right (bit-and 0xF0 (aget ba i)) 4))) (aset out (+ 1 (* 2 i)) (aget ^chars hex-chars (bit-and 0x0F (aget ba i)))) (recur (inc i)))) (String. out))) ; ; Binary buffer manipulation. ; (defn- sort-float-bytes "Sorts a byte array by float byte order. This makes the bytes very slightly more compressable." [^bytes in] (let [c (count in) fc (/ c 4) out (byte-array c)] (loop [i 0 b1 0 b2 fc b3 (* fc 2) b4 (* fc 3)] (when (< i c) (aset out b1 (aget in i)) (aset out b2 (aget in (+ i 1))) (aset out b3 (aget in (+ i 2))) (aset out b4 (aget in (+ i 3))) (recur (+ i 4) (inc b1) (inc b2) (inc b3) (inc b4)))) out)) ; Pick elements of float array, by index. (defn- apick-float [^floats a idxs] (let [ia (float-array idxs)] (amap ia i ret (aget a i)))) (defn- ashuffle-float [mappings ^floats out ^floats in] (doseq [[i-in i-out] mappings] (aset out i-out (aget in i-in))) out) (defn- bytes-to-floats [^bytes barr] (let [bb (java.nio.ByteBuffer/allocate (alength barr)) fb (.asFloatBuffer bb) out (float-array (quot (alength barr) 4))] (.put bb barr) (.get fb out) out)) (defn- floats-to-bytes [^floats farr] (let [bb (java.nio.ByteBuffer/allocate (* (alength farr) 4)) fb (.asFloatBuffer bb)] (.put fb farr) (.array bb))) ; ; Score encoders ; (def ^:private codec-length (memoize (fn [len] (binary/repeated :float-le :length len)))) (defn- codec [blob] (codec-length (/ (count blob) float-size))) (defn score-decode [blob] (bytes-to-floats blob)) (defn score-encode-orig [slist] (floats-to-bytes (float-array slist))) (defn- score-encodez "Experimental compressing score encoder." [slist] (let [baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (binary/encode (codec-length (count slist)) gzos slist) (.finish gzos) (.toByteArray baos))) (defn- score-sort-encodez "Experimental compressing score encoder that sorts by byte order before compressing." [slist] (let [fbytes (score-encode-orig slist) ^bytes sorted (sort-float-bytes fbytes) baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (.write gzos sorted) (.finish gzos) (.toByteArray baos))) (defn- score-decodez [blob] (let [bais (java.io.ByteArrayInputStream. blob) gzis (java.util.zip.GZIPInputStream. bais)] (binary/decode (binary/repeated :float-le :length 10) gzis))) (def score-encode score-encode-orig) (defn- encode-row [encode row] (mapv encode (partition-all bin-size row))) (defn- encode-fields [encoder matrix-fn] (chunked-pmap #(assoc % :data (encode-row encoder (:scores %))) (:fields (matrix-fn)))) ; ; sequence utilities ; This is a stateful iterator. It may not be idiomatic in clojure, but it's a ; quick way to get sequential ids deep in a call stack. Maybe we should instead ; return a thunk that generates a seq, then zip with the data? (defn- seq-iterator "Create iterator for a seq" [s] (let [a (atom s)] (fn [] (let [s @a] (reset! a (next s)) (first s))))) ; Generates primary keys using range, w/o accessing the db for each next value. ; This works in h2 when doing a csvread when the sequence has been created ; automatically by h2 with the column: h2 will update the sequence while reading ; the rows. It doesn't work if the sequence is create separately from the column. ; In that case h2 will not update the sequence after a csvread. We have to ; create the sequence separately in order to set the cache parameter. (comment (defn- sequence-seq [seqname] (let [[{val :i}] (exec-raw (format "SELECT CURRVAL('%s') AS I" seqname) :results)] (range (+ val 1) Double/POSITIVE_INFINITY 1)))) (comment (defn- sequence-seq "Retrieve primary keys in batches by querying the db" [seqname] (let [cmd (format "SELECT NEXT VALUE FOR %s AS i FROM SYSTEM_RANGE(1, 100)" seqname)] (apply concat (repeatedly (fn [] (-> cmd str (exec-raw :results) (#(map :i %))))))))) ; ; Main loader routines. Here we build a sequence of vectors describing rows to be ; inserted, e.g. ; [:insert-score {:id 1 :scores #<byte[] [B@12345>}] ; (defmulti ^:private load-field (fn [dataset-id field-id column] (-> column :valueType))) (defmethod load-field :default [dataset-id field-id {:keys [field rows]}] (let [data (encode-row score-encode (force rows))] (conj (mapcat (fn [[block i]] [[:insert-field-score {:field_id field-id :i i :scores block}]]) (map vector (consume-vec data) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}]))) ; This should be lazy to avoid simultaneously instantiating all the rows as ; individual objects. (defmethod load-field "position" [dataset-id field-id {:keys [field rows]}] (conj (for [[position row] (map vector (force rows) (range))] [:insert-position (assoc position :field_id field-id :row row :bin (calc-bin (:chromStart position) (:chromEnd position)))]) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defmethod load-field "genes" [dataset-id field-id {:keys [field rows row-val]}] (conj (mapcat (fn [[genes row]] (for [gene (row-val genes)] [:insert-gene {:field_id field-id :row row :gene gene}])) (map vector (consume-vec (force rows)) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defn- inferred-type "Replace the given type with the inferred type" [fmeta row] (assoc fmeta "valueType" (:valueType row))) (defn- load-field-feature [feature-seq field-seq dataset-id field] (let [field-id (field-seq)] (concat (load-field dataset-id field-id field) (when-let [feature (force (:feature field))] (load-probe-meta feature-seq field-id (inferred-type feature field)))))) ; ; ; ; Table writer that updates tables as rows are read. ; ; (defn- quote-ent [x] (str \` (name x) \`)) (defn- insert-stmt ^cavm.statement.PStatement [table fields] (let [field-str (clojure.string/join ", " (map quote-ent fields)) val-str (clojure.string/join ", " (repeat (count fields), "?")) stmt-str (format "INSERT INTO %s(%s) VALUES (%s)" (quote-ent table) field-str val-str)] (sql-stmt (jdbcd/find-connection) stmt-str fields))) (defn- sequence-stmt ^cavm.statement.PStatement [db-seq] (sql-stmt-result (jdbcd/find-connection) (format "SELECT NEXT VALUE FOR %s AS i" db-seq))) (defn- run-delays [m] (into {} (for [[k v] m] [k (force v)]))) (def ^:private max-insert-retry 20) (defn trunc [^String s n] (subs s 0 (min (.length s) n))) (defn- numbered-suffix [n] (if (== 1 n) "" (str " (" n ")"))) (defn- table-writer-default [dir dataset-id matrix-fn] (with-open [code-stmt (insert-stmt :code [:value :id :ordering :field_id]) position-stmt (insert-stmt :field_position [:field_id :row :bin :chrom :chromStart :chromEnd :strand]) gene-stmt (insert-stmt :field_gene [:field_id :row :gene]) feature-stmt (insert-stmt :feature [:id :field_id :shortTitle :longTitle :priority :valueType :visibility]) field-stmt (insert-stmt :field [:id :dataset_id :name]) field-score-stmt (insert-stmt :field_score [:field_id :scores :i]) field-seq-stmt (sequence-stmt "FIELD_IDS") feature-seq-stmt (sequence-stmt "FEATURE_IDS")] ; XXX change these -seq functions to do queries returning vectors & ; simplify the destructuring. Or better, stop asking the db for ids and ; generate them ourselves. Getting ids is the slowest bit, even with a large ; cache. (let [feature-seq #(delay (-> (feature-seq-stmt []) first :i)) field-seq #(delay (-> (field-seq-stmt []) first :i)) ; XXX try memoization again? ; score-id-fn (memoize-key (comp ahashable first) scores-seq) writer {:insert-field field-stmt :insert-field-score field-score-stmt :insert-position position-stmt :insert-feature feature-stmt :insert-code code-stmt :insert-gene gene-stmt} row-count (atom 0) data (matrix-fn) warnings (atom (meta data)) last-log (atom 0) inserts (lazy-mapcat #(do (swap! row-count max (count (force (:rows %)))) (load-field-feature feature-seq field-seq dataset-id %)) data)] (doseq [insert-batch (partition-all batch-size inserts)] (jdbcd/transaction (doseq [[insert-type values] insert-batch] (when (= :insert-field insert-type) (let [t (System/currentTimeMillis)] (when (> (- t @last-log) 10000) (trace "writing" (:name values)) (reset! last-log t)))) (let [values (run-delays values) values (if (and (= :insert-field insert-type) (> (.length ^String (:name values)) max-probe-length)) (do (swap! warnings update-in ["too-long-probes"] conj (:name values)) (warn "Too-long probe" (:name values)) (update-in values [:name] trunc max-probe-length)) values) write (fn write [i] ; on field inserts we retry on certain failures, with sanitized probe ids. (let [values (if (= :insert-field insert-type) (update-in values [:name] str (numbered-suffix i)) values)] ; On primary key violations, try to rename probes. If we can't find a usable ; name after max-insert-retry attempts, let the dataset error out. It's probably ; a severe error, like wrong column being used as probe id. (try ((writer insert-type) values) (catch JdbcBatchUpdateException ex (cond (and (= :insert-field insert-type) ; h2 concats the english message after ; the localized message, so using ; .contains. (.contains (.getMessage ex) "Unique index") (< i max-insert-retry)) (do (swap! warnings update-in ["duplicate-probes"] conj (:name values)) (warn "Duplicate probe" (:name values)) (write (inc i))) :else (throw ex))))))] (write 1))))) {:rows @row-count :warnings @warnings}))) ; ; ; Table writer that updates one table at a time by writing to temporary files. ; ; Currently not functioning. Needs update for new schema. (defn- insert-field-out [^java.io.BufferedWriter out seqfn dataset-id name] (let [field-id (seqfn)] (.write out (str field-id "\t" dataset-id "\t" name "\n")) field-id)) (defn- insert-scores-out [^java.io.BufferedWriter out seqfn slist] (let [score-id (seqfn)] (.write out (str score-id "\t" (:hex slist) "\n")) score-id)) (defn- insert-field-score-out [^java.io.BufferedWriter out field-id i score-id] (.write out (str field-id "\t" i "\t" score-id "\n"))) (def ^:private table-writer #'table-writer-default) (let [fmtr (formatter "yyyy-MM-dd hh:mm:ss")] (defn- format-timestamp ^String [timestamp] (unparse fmtr timestamp))) (defn- fmt-time [file-meta] (assoc file-meta :time (. java.sql.Timestamp valueOf (format-timestamp (:time file-meta))))) ; XXX test this ; XXX and call it somewhere. (defn- clean-sources [] (jdbcd/delete-rows :source ["`id` NOT IN (SELECT DISTINCT `source_id` FROM `dataset_source)"])) (defn- load-related-sources [table id-key id files] (jdbcd/delete-rows table [(str (name id-key) " = ?") id]) (let [sources (map #(-> (jdbcd/insert-record :source %) KEY-ID) files)] (doseq [source-id sources] (jdbcd/insert-record table {id-key id :source_id source-id})))) (defn- related-sources [id] (jdbcd/with-query-results rows ["SELECT `source`.`name`, `hash`, `time` FROM `dataset` JOIN `dataset_source` ON `dataset_id` = `dataset`.`id` JOIN `source` on `source_id` = `source`.`id` WHERE `dataset`.`id` = ?" id] (vec rows))) (defn- record-exception [dataset-id ex] (jdbcd/with-query-results rows ["SELECT `text` FROM `dataset` WHERE `dataset`.`id` = ?" dataset-id] (let [[{text :text :or {text "{}"}}] rows metadata (json/read-str text)] (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:text (json/write-str (assoc metadata "error" (str ex)) :escape-slash false)})))) (defn- with-load-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loading"}) (func) (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loaded"}) (catch Exception ex (warn ex "Error loading dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-load-status [dataset-id & body] `(with-load-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (defn- with-delete-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "deleting"}) (func) (catch Exception ex (warn ex "Error deleting dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-delete-status [dataset-id & body] `(with-delete-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (def max-warnings 10) (defn- truncate-warnings [warnings] (-> warnings (update-in ["duplicate-keys" "sampleID"] #(take max-warnings %)) (update-in ["duplicate-probes"] #(take max-warnings %)))) ; jdbcd/transaction will create a closure of our parameters, ; so we can't pass in the matrix seq w/o blowing the heap. We ; pass in a function to return the seq, instead. ; files: the files this matrix was loaded from, e.g. clinical & genomic matrix, plus their timestamps & file hashes ; metadata: the metadata for the matrix (should cgdata mix in the clinical metadata?) ; matrix-fn: function to return seq of data rows ; features: field metadata. Need a better name for this. (defn- load-dataset "Load matrix file and metadata. Skips the data load if file hashes are unchanged, and 'force' is false. Metadata is always updated." ([mname files metadata matrix-fn features] (load-dataset mname files metadata matrix-fn features false)) ([mname files metadata matrix-fn features force] (profile :trace :dataset-load (let [dataset-id (jdbcd/transaction (merge-m-ent mname metadata)) files (map fmt-time files)] (with-load-status dataset-id (when (or force (not (= (set files) (set (related-sources dataset-id))))) (p :dataset-clear (clear-by-exp dataset-id)) (p :dataset-sources (load-related-sources :dataset_source :dataset_id dataset-id files)) (p :dataset-table (let [{:keys [rows warnings]} (table-writer *tmp-dir* dataset-id matrix-fn)] (jdbcd/transaction (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:rows rows}) (when warnings (merge-m-ent mname (assoc metadata :loader (truncate-warnings warnings))))))))))))) (defn- dataset-by-name [dname & kprops] (let [props (clojure.string/join "," (map name kprops))] (jdbcd/with-query-results rows [(format "SELECT %s FROM `dataset` WHERE `name` = ?" props) (str dname)] (-> rows first)))) (def dataset-id-by-name (comp :id #(dataset-by-name % :id))) (defn delete-dataset [dataset] (let [dataset-id (dataset-id-by-name dataset)] (if dataset-id (with-delete-status dataset-id (clear-by-exp dataset-id) (jdbcd/do-commands (format "DELETE FROM `dataset` WHERE `id` = %d" dataset-id))) (info "Did not delete unknown dataset" dataset)))) (defn create-db [file & [{:keys [classname subprotocol make-pool?] :or {classname "org.h2.Driver" subprotocol "h2" make-pool? true}}]] (let [spec {:classname classname :subprotocol subprotocol :subname file :conn-customizer "conn_customizer" :make-pool? make-pool?}] (if make-pool? (delay (pool spec)) (delay (-> spec))))) ; XXX should sanitize the query (defn- run-query [q] (jdbcd/with-query-results rows (spy :trace (hsql/format q)) (vec rows))) ; ; Code queries ; (def ^:private codes-for-field-query (cached-statement "SELECT `ordering`, `value` FROM `field` JOIN `code` ON `field_id` = `field`.`id` WHERE `name` = ? AND `dataset_id` = ?" true)) (defn- codes-for-field [dataset-id field] (->> (codes-for-field-query field dataset-id) (map #(mapv % [:value :ordering])) (into {}))) ; ; All rows queries. ; ; All bins for the given fields. ; XXX inner join here? really? not just a where? (def ^:private all-rows-query (cached-statement "SELECT `name`, `i`, `scores` FROM (SELECT `name`, `id` FROM `field` INNER JOIN (TABLE(`name2` VARCHAR = ?) T) ON `name2` = `field`.`name` WHERE `dataset_id` = ?) AS P LEFT JOIN `field_score` ON `P`.`id` = `field_score`.`field_id`" true)) ; bins will all be the same size, except the last one. bin size is thus ; max of count of first two bins. ; Loop over bins, copying into pre-allocated output array. ; {"foxm1" [{:name "foxm1" :scores <bytes>} ... ] (defn concat-field-bins [bins] (let [float-bins (mapv #(update-in % [:scores] score-decode) bins) sizes (mapv #(count (:scores %)) float-bins) bin-size (apply max (take 2 sizes)) row-count (apply + sizes) out (float-array row-count)] (doseq [{:keys [scores i]} float-bins] (System/arraycopy scores 0 out (* i bin-size) (count scores))) ; XXX mutate "out" in place out)) ; return float arrays of all rows for the given fields (defn- all-rows [dataset-id fields] (let [field-bins (->> (all-rows-query (to-array fields) dataset-id) (group-by :name))] (into {} (for [[k v] field-bins] [k (concat-field-bins v)])))) ; ; ; (defn bin-offset [i] [(quot i bin-size) (rem i bin-size)]) ; merge bin number and bin offset for a row (defn- merge-bin-off [{i :i :as row}] (merge row {:bin (quot i bin-size) :off (rem i bin-size)})) ; Returns mapping from input bin offset to output buffer for a ; given row. (defn- bin-mapping [{off :off row :order}] [off row]) ; Gets called once for each bin in the request. ; order is row -> order in output buffer. ; bin is the bin for the given set of rows ; rows is ({:i 12 :bin 1 :off 1}, ... ), where all :bin are the same (defn- pick-rows-fn [[bin rows]] [bin (partial ashuffle-float (map bin-mapping rows))]) ; Take an ordered list of requested rows, and generate fns to copy ; values from a score bin to an output array. Returns one function ; for each score bin in the request. ; ; rows ({:i 12 :bin 1 :off 1}, ... ) (defn- pick-rows-fns [rows] (let [by-bin (group-by :bin rows)] (apply hash-map (mapcat pick-rows-fn by-bin)))) ; Take map of bin copy fns, list of scores rows, and a map of output arrays, ; copying the scores to the output arrays via the bin copy fns. (defn- build-score-arrays [rows bfns out] (doseq [{i :i scores :scores field :name} rows] ((bfns i) (out field) scores)) out) (defn- col-arrays [columns n] (zipmap columns (repeatedly (partial float-array n Double/NaN)))) ; Doing an inner join on a table literal, instead of a big IN clause, so it will hit ; the index. ; XXX performance of the :in clause? ; XXX make a prepared statement ; Instead of building a custom query each time, this can be ; rewritten as a join against a TABLE literal, or as ; IN (SELECT * FROM TABLE(x INT = (?))). Should check performance ; of both & drop the (format) call. (def ^:private dataset-fields-query "SELECT name, i, scores FROM (SELECT `field`.`name`, `field`.`id` FROM `field` INNER JOIN TABLE(name varchar=?) T ON T.`name`=`field`.`name` WHERE (`field`.`dataset_id` = ?)) P LEFT JOIN `field_score` ON P.id = `field_score`.`field_id` WHERE `field_score`.`i` IN (%s)") (defn- select-scores-full [dataset-id columns bins] (let [q (format dataset-fields-query (clojure.string/join "," (repeat (count bins) "?"))) c (to-array (map str columns)) i bins] (jdbcd/with-query-results rows (vec (concat [q c dataset-id] i)) (vec rows)))) ; Returns rows from (dataset-id column-name) matching ; values. Returns a hashmap for each matching row. ; { :i The implicit index in the column as stored on disk. ; ;order The order of the row the result set. ; :value The value of the row. ; } (defn- rows-matching [dataset-id column-name values] (let [val-set (set values)] (->> column-name (vector) (all-rows dataset-id) ; Retrieve the full column (vals) (first) ; calculate row index in the column (map #(-> {:i %1 :value %2}) (range)) ; [{:i 0 :value 1.2} ...] (filter (comp val-set :value)) ; filter rows not matching the request. (group-by :value) (#(map (fn [g] (get % g [nil])) values)) ; arrange by output order. (apply concat) ; flatten groups. (mapv #(assoc %2 :order %1) (range))))) ; assoc row output order. (defn- float-nil [x] (when x (float x))) ; Get codes for samples in request ; Get the entire sample column ; Find the rows matching the samples, ordered by sample list ; Have to scan the sample column, group by sample, and map over the ordering ; Build shuffle functions, per bin, to copy bins to output buffer ; Run scores query ; Copy to output buffer (defn- genomic-read-req [req] (let [{:keys [samples table columns]} req dataset-id (dataset-id-by-name table) samp->code (codes-for-field dataset-id "sampleID") order (mapv (comp float-nil samp->code) samples) ; codes in request order rows (rows-matching dataset-id "sampleID" order) rows-to-copy (->> rows (filter :value) (mapv merge-bin-off)) bins (mapv :bin rows-to-copy) ; list of bins to pull. bfns (pick-rows-fns rows-to-copy)] ; make fns that map from input bin to ; output buffer, one fn per input bin. (-> (select-scores-full dataset-id columns (distinct bins)) (#(mapv cvt-scores %)) (build-score-arrays bfns (col-arrays columns (count rows)))))) ; ; ; Methods for providing a sql abstraction over the column store. ; ; (def ^:private field-ids-query (cached-statement "SELECT `id`, `name` FROM `field` WHERE `dataset_id` = ? AND `name` IN (SELECT * FROM TABLE(x VARCHAR = (?)))" true)) (defn- fetch-field-ids [dataset-id names] (when-let [ids (field-ids-query dataset-id names)] (map (juxt :name :id) ids))) ; (def ^:private codes-for-values-query (cached-statement "SELECT `ordering`, `value` FROM `code` JOIN TABLE(x INT = (?)) V on `x` = `ordering` WHERE `field_id` = ?" true)) (defn- codes-for-values [field-id values] (when-let [codes (codes-for-values-query values field-id)] (map (juxt :ordering :value) codes))) ; (def ^:private field-bins-query (cached-statement "SELECT `scores`, `i` FROM `field_score` WHERE `field_id` = ? AND `i` IN (SELECT * FROM TABLE(x INT = (?)))" true)) (defn- fetch-bins [field-id bins] (when-let [scores (field-bins-query field-id bins)] (map #(update-in % [:scores] bytes-to-floats) scores))) ; (def ^:private has-codes-query (cached-statement "SELECT EXISTS(SELECT `ordering` FROM `code` WHERE `field_id` = ?) hascodes" true)) (defn has-codes? [field-id] (-> (has-codes-query field-id) first :hascodes)) ; (def ^:private has-genes-query (cached-statement "SELECT EXISTS(SELECT `gene` FROM `field_gene` WHERE `field_id` = ?) hasgenes" true)) (defn has-genes? [field-id] (-> (has-genes-query field-id) first :hasgenes)) ; (def ^:private has-position-query (cached-statement "SELECT EXISTS(SELECT `bin` FROM `field_position` WHERE `field_id` = ?) hasposition" true)) (defn has-position? [field-id] (-> (has-position-query field-id) first :hasposition)) ; (defn update-codes-cache [codes field-id new-bins cache] (match [codes] [nil] (update-codes-cache (if (has-codes? field-id) [:yes {}] [:no]) field-id new-bins cache) [[:no]] codes [[:yes code-cache]] [:yes (let [values (distinct (mapcat cache new-bins)) missing (filterv #(not (contains? code-cache %)) values)] (into code-cache (codes-for-values field-id missing)))])) (defn update-cache [cache field-id rows] (let [bins (distinct (map #(quot % bin-size) rows)) missing (filterv #(not (contains? cache %)) bins)] (if (seq missing) (let [new-cache (->> missing (fetch-bins field-id) (map (juxt :i :scores)) (into (or cache {})))] (update-in new-cache [:codes] update-codes-cache field-id missing new-cache)) cache))) ; ; ; return fn of rows->vals ; (defmulti fetch-rows (fn [cache rows field-id] (cond (has-genes? field-id) :gene (has-position? field-id) :position :else :binned))) ; binned fields (defmethod fetch-rows :binned [cache rows field-id] (swap! cache update-in [field-id] update-cache field-id rows) (let [f (@cache field-id) getter (match [(:codes f)] ; XXX cast to int here is pretty horrible. ; Really calls for an int array bin in h2. [[:yes vals->codes]] (fn [bin off] (let [v (aget ^floats (f bin) off)] (if (. Float isNaN v) nil (vals->codes (int v))))) [[:no]] (fn [bin off] (get (f bin) off)))] (fn [row] (apply getter (bin-offset row))))) (def ^:private field-genes-by-row-query (cached-statement "SELECT `row`, `gene` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) (defn field-genes-by-row [field-id rows] (->> (field-genes-by-row-query rows field-id) (group-by :row) (map (fn [[k rows]] [k (mapv :gene rows)])))) ; gene fields (defmethod fetch-rows :gene [cache rows field-id] (into {} (field-genes-by-row field-id rows))) (def ^:private field-position-by-row-query (cached-statement "SELECT `row`, `chrom`, `chromStart`, `chromEnd`, `strand` FROM `field_position` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) ; position fields (defn field-position-by-row [field-id rows] (->> (field-position-by-row-query rows field-id) (map (fn [{:keys [row] :as values}] [row (dissoc values :row)])))) (defmethod fetch-rows :position [cache rows field-id] (into {} (field-position-by-row field-id rows))) ; ; Indexed field lookups (gene & position) ; (defn has-index? [fields field] (let [field-id (fields field)] (or (has-genes? field-id) (has-position? field-id)))) ; gene ; Selecting `gene` as well adds a lot to the query time. Might ; need it if we need to cache gene names. (def ^:private field-genes-query (cached-statement "SELECT `row` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `gene` WHERE `field_id` = ?" true)) (defn field-genes [field-id genes] (->> (field-genes-query genes field-id) (map :row))) (defn fetch-genes [field-id values] (into (i/int-set) (field-genes field-id values))) ; position (def ^:private field-position-one-query (cached-statement "SELECT `row` FROM `field_position` WHERE `field_id` = ? AND `chrom` = ? AND (`bin` >= ? AND `bin` <= ?) AND `chromStart` <= ? AND `chromEnd` >= ?" true)) ; [:in "position" [["chr17" 100 20000]]] (defn field-position [field-id values] (->> (mapcat (fn [[chr start end]] (let [istart (int start) iend (int end) bins (overlapping-bins istart iend)] (mapcat (fn [[s e]] (field-position-one-query field-id chr s e iend istart)) bins))) values) (map :row))) (defn fetch-position [field-id values] (into (i/int-set) (field-position field-id values))) ; fetch-indexed doesn't cache, and it's unclear ; if we should cache the indexed fields during 'restrict'. ; h2 also has caches, so it might be better to rely on them, ; simply doing the query again if we need it. ; Otherwise, we might want to inform the cache of what columns are ; required later during 'restrict', or in 'project', so ; we know if they should be cached. (defn fetch-indexed [fields field values] (let [field-id (fields field)] (cond (has-position? field-id) (fetch-position field-id values) (has-genes? field-id) (fetch-genes field-id values)))) ; ; sql eval methods ; ; might want to use a reader literal for field names, so we ; find them w/o knowing syntax. (defn collect-fields [exp] (match [exp] [[:in field _]] [field] [[:in arrmod field _]] [field] [[:and & subexps]] (mapcat collect-fields subexps) [[:or & subexps]] (mapcat collect-fields subexps) [nil] [])) ; ; Computing the "set of all rows" to begin a query was taking much too long ; (minutes, for tens of millions of rows). Switching from sorted-set to int-set ; brought this down to tens of seconds, which was still too slow. Here we ; generate the int-set in parallel & merge with i/union, which is fast. This ; brings the time down to a couple seconds for tens of millions of rows. We ; then, additionally, cache the set, and re-use it if possible. We can ; quickly create smaller sets with i/range, so we memoize such that we ; compute a new base set only if the current memoized size is too small. ; ; Note that this means that if we load a very large dataset, then delete it, ; the memory required to represent all the rows of that dataset is not released ; until the server is restarted. ; ; Alternative fixes might be 1) use an agent to always maintain the largest ; "set of all rows" required for the loaded datasets, updating on dataset add/remove; ; 2) using a different representation of contiguous rows, e.g. [start, end]. We ; would need to review the down-stream performance implications of this (i.e. computing ; union and intersection, generating db queries, etc.) (def block-size 1e6) (defn int-set-bins [n] (let [blocks (+ (quot n block-size) (if (= 0 (rem n block-size)) 0 1))] (map (fn [i] [(* i block-size) (min (* (+ i 1) block-size) n)]) (range blocks)))) (defn set-of-all [n] (let [blocks (/ n block-size)] (reduce #(i/union % %2) (pmap (fn [[start end]] (into (i/int-set) (range start end))) (int-set-bins n))))) (defn mem-min [f] (let [mem (atom nil)] (fn [n] (if (> n (count @mem)) (let [ret (f n)] (reset! mem ret) ret) (i/range @mem 0 (- n 1)))))) (def set-of-all-cache (mem-min set-of-all)) ; XXX Look at memory use of pulling :gene field. If it's not ; interned, it could be expensive. ; XXX Map keywords to strings, for dataset & field names? ; XXX Add some param guards, esp. unknown field. (defn eval-sql [{[from] :from where :where select :select :as exp}] (let [{dataset-id :id N :rows} (dataset-by-name from :id :rows) fields (into {} (fetch-field-ids dataset-id (into (collect-fields where) select))) cache (atom {}) fetch (fn [rows field] (if (not-empty rows) (fetch-rows cache rows (fields field)) {}))] (evaluate (set-of-all-cache N) {:fetch fetch :fetch-indexed (partial fetch-indexed fields) :indexed? (partial has-index? fields)} exp))) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["sampleID"] :from ["BRCA1"] :where [:in "sampleID" ; ["HG00122" "NA07056" "HG01870" "NA18949" "HG02375" ; "HG00150" "NA18528" "HG02724"]]})) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["alt"] :from ["BRCA1"] :where [:in "position" [["chr17" 10000 100000000]]]})) ; ; ; ; ; ; ; Each req is a map of ; :table "tablename" ; :columns '("column1" "column2") ; :samples '("sample1" "sample2") ; We merge into 'data the columns that we can resolve, like ; :data { 'column1 [1.1 1.2] 'column2 [2.1 2.2] } (defn- genomic-source [reqs] (map #(update-in % [:data] merge (genomic-read-req %)) reqs)) ; ; hand-spun migrations. ; (def column-len-query "SELECT character_maximum_length as len FROM information_schema.columns as c WHERE c.table_name = ? AND c.column_name = ?") (def bad-probemap-query "SELECT `dataset`.`name` FROM `dataset` LEFT JOIN `dataset` as d ON d.`name` = `dataset`.`probemap` WHERE `dataset`.`probeMap` IS NOT NULL AND d.`name` IS NULL") (defn delete-if-probemap-invalid [] (jdbcd/with-query-results bad-datasets [bad-probemap-query] (doseq [{dataset :name} bad-datasets] (delete-dataset dataset)))) ; dataset.probemap refers to a dataset.name, but previously ; had different data size, and was not enforced as a foreign ; key. Check for old data size, and run migration if it's old ; ; The migration will delete datasets that have invalid probemap, ; and update the field. (defn migrate-probemap [] (jdbcd/with-query-results pm-key [column-len-query "DATASET" "PROBEMAP"] (when (and (seq pm-key) (= (:len (first pm-key)) 255)) (info "Migrating probeMap field") (delete-if-probemap-invalid) (jdbcd/do-commands "AlTER TABLE `dataset` ALTER COLUMN `probeMap` VARCHAR(1000)" "ALTER TABLE `dataset` ADD FOREIGN KEY (`probeMap`) REFERENCES `dataset` (`name`)")))) (defn- migrate [] (migrate-probemap) ; ...add more here ) (defn- create[] (jdbcd/transaction (apply jdbcd/do-commands cohorts-table) (apply jdbcd/do-commands source-table) (apply jdbcd/do-commands dataset-table) (apply jdbcd/do-commands dataset-source-table) (apply jdbcd/do-commands field-table) (apply jdbcd/do-commands field-score-table) (apply jdbcd/do-commands feature-table) (apply jdbcd/do-commands code-table) (apply jdbcd/do-commands field-position-table) (apply jdbcd/do-commands field-gene-table)) (migrate)) ; ; add TABLE handling for honeysql ; (defmethod hsqlfmt/format-clause :table [[_ [fields alias]] _] (str "TABLE(" (clojure.string/join ", " (map (fn [[name type values]] (str (hsqlfmt/to-sql name) " " (hsqlfmt/to-sql type) "=" (hsqlfmt/paren-wrap (clojure.string/join ", " (map hsqlfmt/to-sql values))))) fields)) ") " (hsqlfmt/to-sql alias))) ; Fix GROUP_CONCAT in honeysql (defn- format-concat ([value {:keys [order separator]}] (let [oclause (if (nil? order) "" (str " order by " (hsqlfmt/to-sql order))) sclause (if (nil? separator) "" (str " separator " (hsqlfmt/to-sql separator)))] (str "GROUP_CONCAT(" (hsqlfmt/to-sql value) oclause sclause ")")))) (defmethod hsqlfmt/fn-handler "group_concat" [_ value & args] (format-concat value args)) (defrecord H2Db [db]) (extend-protocol XenaDb H2Db (write-matrix [this mname files metadata data-fn features always] (jdbcd/with-connection @(:db this) (load-dataset mname files metadata data-fn features always))) (delete-matrix [this mname] (jdbcd/with-connection @(:db this) (delete-dataset mname))) (run-query [this query] (jdbcd/with-connection @(:db this) (run-query query))) (column-query [this query] (jdbcd/with-connection @(:db this) (eval-sql query))) (fetch [this reqs] (jdbcd/with-connection @(:db this) (doall (genomic-source reqs)))) (close [this] ; XXX test for pool, or datasource before running? (.close ^ComboPooledDataSource (:datasource @(:db this)) false))) (defn create-xenadb [& args] (let [db (apply create-db args)] (jdbcd/with-connection @db (create)) (H2Db. db)))
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "Xena H2 database backend"} cavm.h2 (:require [clojure.java.jdbc.deprecated :as jdbcd]) (:require [clojure.java.jdbc :as jdbc]) (:require [cavm.jdbc]) (:require [org.clojars.smee.binary.core :as binary]) (:require [clojure.java.io :as io]) (:require [honeysql.core :as hsql]) (:require [honeysql.format :as hsqlfmt]) (:require [honeysql.types :as hsqltypes]) (:require [cavm.json :as json]) (:require [cavm.binner :refer [calc-bin overlapping-bins]]) (:use [clj-time.format :only (formatter unparse)]) (:use [cavm.hashable :only (ahashable)]) (:require [cavm.db :refer [XenaDb]]) (:require [clojure.tools.logging :refer [spy trace info warn]]) (:require [taoensso.timbre.profiling :refer [profile p]]) (:require [clojure.core.cache :as cache]) (:require [cavm.statement :refer [sql-stmt sql-stmt-result cached-statement]]) (:require [cavm.conn-pool :refer [pool]]) (:require [cavm.lazy-utils :refer [consume-vec lazy-mapcat]]) (:require [clojure.core.match :refer [match]]) (:require [cavm.sqleval :refer [evaluate]]) (:require [clojure.data.int-map :as i]) (:import [org.h2.jdbc JdbcBatchUpdateException]) (:import [com.mchange.v2.c3p0 ComboPooledDataSource])) (def h2-log-level (into {} (map vector [:off :error :info :debug :slf4j] (range)))) ; ; Note that "bin" in this file is like a "segement" in the column store ; literature: a column is split into a series of segments (bins) before ; writing to disk (saving as blob in h2). ; (def ^:dynamic ^:private *tmp-dir* (System/getProperty "java.io.tmpdir")) (defn set-tmp-dir! [dir] (alter-var-root #'*tmp-dir* (constantly dir))) ; Coerce this sql fn name to a keyword so we can reference it. (def ^:private KEY-ID (keyword "PI:KEY:<KEY>END_PI")) (def ^:private float-size 4) (def ^:private bin-size 1000) (def ^:private score-size (* float-size bin-size)) ; Add 30 for gzip header ;( def score-size (+ 30 (* float-size bin-size))) ; row count for batch operations (e.g. insert/delete) (def ^:private batch-size 1000) ; ; Utility functions ; (defn- chunked-pmap [f coll] (->> coll (partition-all 250) (pmap (fn [chunk] (doall (map f chunk)))) (apply concat))) (defn- memoize-key "Memoize with the given function of the arguments" [kf f] (let [mem (atom {})] (fn [& args] (let [k (kf args)] (if-let [e (find @mem k)] (val e) (let [ret (apply f args)] (swap! mem assoc k ret) ret)))))) ; ; Table models ; (declare score-decode) (defn- cvt-scores [{scores :scores :as v}] (if scores (assoc v :scores (float-array (score-decode scores))) v)) ; ; Table definitions. ; (def ^:private max-probe-length 250) (def ^:private probe-version-length 5) ; to disambiguate probes by appending " (dd)" ; Note H2 has one int type: signed, 4 byte. Max is approximately 2 billion. (def ^:private field-table ["CREATE SEQUENCE IF NOT EXISTS FIELD_IDS CACHE 2000" (format "CREATE TABLE IF NOT EXISTS `field` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FIELD_IDS PRIMARY KEY, `dataset_id` INT NOT NULL, `name` VARCHAR(%d), UNIQUE(`dataset_id`, `name`), FOREIGN KEY (`dataset_id`) REFERENCES `dataset` (`id`) ON DELETE CASCADE)" (+ max-probe-length probe-version-length))]) (def ^:private field-score-table [(format "CREATE TABLE IF NOT EXISTS `field_score` ( `field_id` INT NOT NULL, `i` INT NOT NULL, `scores` VARBINARY(%d) NOT NULL, UNIQUE (`field_id`, `i`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" score-size)]) (def ^:private cohorts-table ["CREATE TABLE IF NOT EXISTS `cohorts` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL UNIQUE)"]) ; XXX What should max file name length be? ; XXX Unique columns? Indexes? (def ^:private source-table ["CREATE TABLE IF NOT EXISTS `source` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(2000) NOT NULL, `time` TIMESTAMP NOT NULL, `hash` VARCHAR(40) NOT NULL)"]) (def ^:private dataset-table ["CREATE TABLE IF NOT EXISTS `dataset` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, `name` VARCHAR(1000) NOT NULL UNIQUE, `probeMap` VARCHAR(255), `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `groupTitle` VARCHAR(255), `platform` VARCHAR(255), `cohort` VARCHAR(1000), `security` VARCHAR(255), `rows` INT, `status` VARCHAR(20), `text` VARCHAR (65535), `type` VARCHAR (255), `dataSubType` VARCHAR (255))"]) (def ^:private dataset-columns #{:name :probeMap :shortTitle :longTitle :groupTitle :platform :cohort :security :dataSubType :type :text}) (def ^:private dataset-defaults (into {} (map #(vector % nil) dataset-columns))) (def ^:private dataset-source-table ["CREATE TABLE IF NOT EXISTS `dataset_source` ( `dataset_id` INT NOT NULL, `source_id` INT NOT NULL, FOREIGN KEY (dataset_id) REFERENCES `dataset` (`id`) ON DELETE CASCADE, FOREIGN KEY (source_id) REFERENCES `source` (`id`) ON DELETE CASCADE)"]) (def ^:private dataset-meta {:defaults dataset-defaults :columns dataset-columns}) ; XXX CASCADE might perform badly. Might need to do this incrementally in application code. (def ^:private field-position-table ["CREATE TABLE IF NOT EXISTS `field_position` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `bin` INT, `chrom` VARCHAR(255) NOT NULL, `chromStart` INT NOT NULL, `chromEnd` INT NOT NULL, `strand` CHAR(1), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS chrom_bin ON field_position (`field_id`, `chrom`, `bin`)" "CREATE INDEX IF NOT EXISTS position_row ON field_position (`field_id`, `row`)"]) (def ^:private field-gene-table ["CREATE TABLE IF NOT EXISTS `field_gene` ( `field_id` INT NOT NULL, `row` INT NOT NULL, `gene` VARCHAR_IGNORECASE(255) NOT NULL, FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)" "CREATE INDEX IF NOT EXISTS field_gene ON `field_gene` (`field_id`, `gene`)" "CREATE INDEX IF NOT EXISTS gene_row ON `field_gene` (`field_id`, `row`)"]) ; ; feature tables ; (def ^:private feature-table ["CREATE SEQUENCE IF NOT EXISTS FEATURE_IDS CACHE 2000" "CREATE TABLE IF NOT EXISTS `feature` ( `id` INT NOT NULL DEFAULT NEXT VALUE FOR FEATURE_IDS PRIMARY KEY, `field_id` INT(11) NOT NULL, `shortTitle` VARCHAR(255), `longTitle` VARCHAR(255), `priority` DOUBLE DEFAULT NULL, `valueType` VARCHAR(255) NOT NULL, `visibility` VARCHAR(255), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (def ^:private feature-columns #{:shortTitle :longTitle :priority :valueType :visibility}) (def ^:private feature-defaults (into {} (map #(vector % nil) feature-columns))) (def ^:private feature-meta {:defaults feature-defaults :columns feature-columns}) ; Order is important to avoid creating duplicate indexes. A foreign ; key constraint creates an index if one doesn't exist, so create our ; index before adding the constraint. ; XXX varchar size is pushing it. Do we need another type for clob-valued ; fields? (def ^:private code-table ["CREATE TABLE IF NOT EXISTS `code` ( `id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, `field_id` INT(11) NOT NULL, `ordering` INT(10) unsigned NOT NULL, `value` VARCHAR(16384) NOT NULL, UNIQUE (`field_id`, `ordering`), FOREIGN KEY (`field_id`) REFERENCES `field` (`id`) ON DELETE CASCADE)"]) (defn- normalize-meta [m-ent metadata] (-> metadata (clojure.walk/keywordize-keys) (#(merge (:defaults m-ent) %)) (select-keys (:columns m-ent)))) (defn- json-text [md] (assoc md :text (json/write-str md :escape-slash false))) (defn- load-probe-meta [feature-seq field-id {:keys [order] :as feat}] (let [feature-id (feature-seq) fmeta (merge (normalize-meta feature-meta feat) {:field_id field-id :id feature-id})] (cons [:insert-feature (assoc fmeta :id feature-id)] (for [[value ordering] order] [:insert-code {:field_id field-id :ordering ordering :value value}])))) ; ; ; (defn do-command-while-updates [cmd] (while (> (first (jdbcd/do-commands cmd)) 0))) (defn delete-rows-by-field-cmd [table field] (format "DELETE FROM `%s` WHERE `field_id` = %d LIMIT %d" table field batch-size)) (defn- clear-fields [exp] (jdbcd/with-query-results field ["SELECT `id` FROM `field` WHERE `dataset_id` = ?" exp] (doseq [{id :id} field] (doseq [table ["code" "feature" "field_gene" "field_position" "field_score"]] (do-command-while-updates (delete-rows-by-field-cmd table id))))) (do-command-while-updates (format "DELETE FROM `field` WHERE `dataset_id` = %d LIMIT %d" exp batch-size))) ; Deletes an experiment. We break this up into a series ; of commits so other threads are not blocked, and we ; don't time-out the db thread pool. ; XXX Might want to add a "deleting" status to the dataset table? (defn- clear-by-exp [exp] (clear-fields exp) (jdbcd/delete-rows :field ["`dataset_id` = ?" exp])) ; Update meta entity record. (defn- merge-m-ent [ename metadata] (let [normmeta (normalize-meta dataset-meta (json-text (assoc metadata "name" ename))) {id :id} (jdbcd/with-query-results row [(str "SELECT `id` FROM `dataset` WHERE `name` = ?") ename] (first row))] (if id (do (jdbcd/update-values :dataset ["`id` = ?" id] normmeta) id) (-> (jdbcd/insert-record :dataset normmeta) KEY-ID)))) ; ; Hex ; (def ^:private hex-chars (char-array "0123456789ABCDEF")) (defn- bytes->hex [^bytes ba] (let [c (count ba) out ^chars (char-array (* 2 c))] (loop [i 0] (when (< i c) (aset out (* 2 i) (aget ^chars hex-chars (bit-shift-right (bit-and 0xF0 (aget ba i)) 4))) (aset out (+ 1 (* 2 i)) (aget ^chars hex-chars (bit-and 0x0F (aget ba i)))) (recur (inc i)))) (String. out))) ; ; Binary buffer manipulation. ; (defn- sort-float-bytes "Sorts a byte array by float byte order. This makes the bytes very slightly more compressable." [^bytes in] (let [c (count in) fc (/ c 4) out (byte-array c)] (loop [i 0 b1 0 b2 fc b3 (* fc 2) b4 (* fc 3)] (when (< i c) (aset out b1 (aget in i)) (aset out b2 (aget in (+ i 1))) (aset out b3 (aget in (+ i 2))) (aset out b4 (aget in (+ i 3))) (recur (+ i 4) (inc b1) (inc b2) (inc b3) (inc b4)))) out)) ; Pick elements of float array, by index. (defn- apick-float [^floats a idxs] (let [ia (float-array idxs)] (amap ia i ret (aget a i)))) (defn- ashuffle-float [mappings ^floats out ^floats in] (doseq [[i-in i-out] mappings] (aset out i-out (aget in i-in))) out) (defn- bytes-to-floats [^bytes barr] (let [bb (java.nio.ByteBuffer/allocate (alength barr)) fb (.asFloatBuffer bb) out (float-array (quot (alength barr) 4))] (.put bb barr) (.get fb out) out)) (defn- floats-to-bytes [^floats farr] (let [bb (java.nio.ByteBuffer/allocate (* (alength farr) 4)) fb (.asFloatBuffer bb)] (.put fb farr) (.array bb))) ; ; Score encoders ; (def ^:private codec-length (memoize (fn [len] (binary/repeated :float-le :length len)))) (defn- codec [blob] (codec-length (/ (count blob) float-size))) (defn score-decode [blob] (bytes-to-floats blob)) (defn score-encode-orig [slist] (floats-to-bytes (float-array slist))) (defn- score-encodez "Experimental compressing score encoder." [slist] (let [baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (binary/encode (codec-length (count slist)) gzos slist) (.finish gzos) (.toByteArray baos))) (defn- score-sort-encodez "Experimental compressing score encoder that sorts by byte order before compressing." [slist] (let [fbytes (score-encode-orig slist) ^bytes sorted (sort-float-bytes fbytes) baos (java.io.ByteArrayOutputStream.) gzos (java.util.zip.GZIPOutputStream. baos)] (.write gzos sorted) (.finish gzos) (.toByteArray baos))) (defn- score-decodez [blob] (let [bais (java.io.ByteArrayInputStream. blob) gzis (java.util.zip.GZIPInputStream. bais)] (binary/decode (binary/repeated :float-le :length 10) gzis))) (def score-encode score-encode-orig) (defn- encode-row [encode row] (mapv encode (partition-all bin-size row))) (defn- encode-fields [encoder matrix-fn] (chunked-pmap #(assoc % :data (encode-row encoder (:scores %))) (:fields (matrix-fn)))) ; ; sequence utilities ; This is a stateful iterator. It may not be idiomatic in clojure, but it's a ; quick way to get sequential ids deep in a call stack. Maybe we should instead ; return a thunk that generates a seq, then zip with the data? (defn- seq-iterator "Create iterator for a seq" [s] (let [a (atom s)] (fn [] (let [s @a] (reset! a (next s)) (first s))))) ; Generates primary keys using range, w/o accessing the db for each next value. ; This works in h2 when doing a csvread when the sequence has been created ; automatically by h2 with the column: h2 will update the sequence while reading ; the rows. It doesn't work if the sequence is create separately from the column. ; In that case h2 will not update the sequence after a csvread. We have to ; create the sequence separately in order to set the cache parameter. (comment (defn- sequence-seq [seqname] (let [[{val :i}] (exec-raw (format "SELECT CURRVAL('%s') AS I" seqname) :results)] (range (+ val 1) Double/POSITIVE_INFINITY 1)))) (comment (defn- sequence-seq "Retrieve primary keys in batches by querying the db" [seqname] (let [cmd (format "SELECT NEXT VALUE FOR %s AS i FROM SYSTEM_RANGE(1, 100)" seqname)] (apply concat (repeatedly (fn [] (-> cmd str (exec-raw :results) (#(map :i %))))))))) ; ; Main loader routines. Here we build a sequence of vectors describing rows to be ; inserted, e.g. ; [:insert-score {:id 1 :scores #<byte[] [B@12345>}] ; (defmulti ^:private load-field (fn [dataset-id field-id column] (-> column :valueType))) (defmethod load-field :default [dataset-id field-id {:keys [field rows]}] (let [data (encode-row score-encode (force rows))] (conj (mapcat (fn [[block i]] [[:insert-field-score {:field_id field-id :i i :scores block}]]) (map vector (consume-vec data) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}]))) ; This should be lazy to avoid simultaneously instantiating all the rows as ; individual objects. (defmethod load-field "position" [dataset-id field-id {:keys [field rows]}] (conj (for [[position row] (map vector (force rows) (range))] [:insert-position (assoc position :field_id field-id :row row :bin (calc-bin (:chromStart position) (:chromEnd position)))]) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defmethod load-field "genes" [dataset-id field-id {:keys [field rows row-val]}] (conj (mapcat (fn [[genes row]] (for [gene (row-val genes)] [:insert-gene {:field_id field-id :row row :gene gene}])) (map vector (consume-vec (force rows)) (range))) [:insert-field {:id field-id :dataset_id dataset-id :name field}])) (defn- inferred-type "Replace the given type with the inferred type" [fmeta row] (assoc fmeta "valueType" (:valueType row))) (defn- load-field-feature [feature-seq field-seq dataset-id field] (let [field-id (field-seq)] (concat (load-field dataset-id field-id field) (when-let [feature (force (:feature field))] (load-probe-meta feature-seq field-id (inferred-type feature field)))))) ; ; ; ; Table writer that updates tables as rows are read. ; ; (defn- quote-ent [x] (str \` (name x) \`)) (defn- insert-stmt ^cavm.statement.PStatement [table fields] (let [field-str (clojure.string/join ", " (map quote-ent fields)) val-str (clojure.string/join ", " (repeat (count fields), "?")) stmt-str (format "INSERT INTO %s(%s) VALUES (%s)" (quote-ent table) field-str val-str)] (sql-stmt (jdbcd/find-connection) stmt-str fields))) (defn- sequence-stmt ^cavm.statement.PStatement [db-seq] (sql-stmt-result (jdbcd/find-connection) (format "SELECT NEXT VALUE FOR %s AS i" db-seq))) (defn- run-delays [m] (into {} (for [[k v] m] [k (force v)]))) (def ^:private max-insert-retry 20) (defn trunc [^String s n] (subs s 0 (min (.length s) n))) (defn- numbered-suffix [n] (if (== 1 n) "" (str " (" n ")"))) (defn- table-writer-default [dir dataset-id matrix-fn] (with-open [code-stmt (insert-stmt :code [:value :id :ordering :field_id]) position-stmt (insert-stmt :field_position [:field_id :row :bin :chrom :chromStart :chromEnd :strand]) gene-stmt (insert-stmt :field_gene [:field_id :row :gene]) feature-stmt (insert-stmt :feature [:id :field_id :shortTitle :longTitle :priority :valueType :visibility]) field-stmt (insert-stmt :field [:id :dataset_id :name]) field-score-stmt (insert-stmt :field_score [:field_id :scores :i]) field-seq-stmt (sequence-stmt "FIELD_IDS") feature-seq-stmt (sequence-stmt "FEATURE_IDS")] ; XXX change these -seq functions to do queries returning vectors & ; simplify the destructuring. Or better, stop asking the db for ids and ; generate them ourselves. Getting ids is the slowest bit, even with a large ; cache. (let [feature-seq #(delay (-> (feature-seq-stmt []) first :i)) field-seq #(delay (-> (field-seq-stmt []) first :i)) ; XXX try memoization again? ; score-id-fn (memoize-key (comp ahashable first) scores-seq) writer {:insert-field field-stmt :insert-field-score field-score-stmt :insert-position position-stmt :insert-feature feature-stmt :insert-code code-stmt :insert-gene gene-stmt} row-count (atom 0) data (matrix-fn) warnings (atom (meta data)) last-log (atom 0) inserts (lazy-mapcat #(do (swap! row-count max (count (force (:rows %)))) (load-field-feature feature-seq field-seq dataset-id %)) data)] (doseq [insert-batch (partition-all batch-size inserts)] (jdbcd/transaction (doseq [[insert-type values] insert-batch] (when (= :insert-field insert-type) (let [t (System/currentTimeMillis)] (when (> (- t @last-log) 10000) (trace "writing" (:name values)) (reset! last-log t)))) (let [values (run-delays values) values (if (and (= :insert-field insert-type) (> (.length ^String (:name values)) max-probe-length)) (do (swap! warnings update-in ["too-long-probes"] conj (:name values)) (warn "Too-long probe" (:name values)) (update-in values [:name] trunc max-probe-length)) values) write (fn write [i] ; on field inserts we retry on certain failures, with sanitized probe ids. (let [values (if (= :insert-field insert-type) (update-in values [:name] str (numbered-suffix i)) values)] ; On primary key violations, try to rename probes. If we can't find a usable ; name after max-insert-retry attempts, let the dataset error out. It's probably ; a severe error, like wrong column being used as probe id. (try ((writer insert-type) values) (catch JdbcBatchUpdateException ex (cond (and (= :insert-field insert-type) ; h2 concats the english message after ; the localized message, so using ; .contains. (.contains (.getMessage ex) "Unique index") (< i max-insert-retry)) (do (swap! warnings update-in ["duplicate-probes"] conj (:name values)) (warn "Duplicate probe" (:name values)) (write (inc i))) :else (throw ex))))))] (write 1))))) {:rows @row-count :warnings @warnings}))) ; ; ; Table writer that updates one table at a time by writing to temporary files. ; ; Currently not functioning. Needs update for new schema. (defn- insert-field-out [^java.io.BufferedWriter out seqfn dataset-id name] (let [field-id (seqfn)] (.write out (str field-id "\t" dataset-id "\t" name "\n")) field-id)) (defn- insert-scores-out [^java.io.BufferedWriter out seqfn slist] (let [score-id (seqfn)] (.write out (str score-id "\t" (:hex slist) "\n")) score-id)) (defn- insert-field-score-out [^java.io.BufferedWriter out field-id i score-id] (.write out (str field-id "\t" i "\t" score-id "\n"))) (def ^:private table-writer #'table-writer-default) (let [fmtr (formatter "yyyy-MM-dd hh:mm:ss")] (defn- format-timestamp ^String [timestamp] (unparse fmtr timestamp))) (defn- fmt-time [file-meta] (assoc file-meta :time (. java.sql.Timestamp valueOf (format-timestamp (:time file-meta))))) ; XXX test this ; XXX and call it somewhere. (defn- clean-sources [] (jdbcd/delete-rows :source ["`id` NOT IN (SELECT DISTINCT `source_id` FROM `dataset_source)"])) (defn- load-related-sources [table id-key id files] (jdbcd/delete-rows table [(str (name id-key) " = ?") id]) (let [sources (map #(-> (jdbcd/insert-record :source %) KEY-ID) files)] (doseq [source-id sources] (jdbcd/insert-record table {id-key id :source_id source-id})))) (defn- related-sources [id] (jdbcd/with-query-results rows ["SELECT `source`.`name`, `hash`, `time` FROM `dataset` JOIN `dataset_source` ON `dataset_id` = `dataset`.`id` JOIN `source` on `source_id` = `source`.`id` WHERE `dataset`.`id` = ?" id] (vec rows))) (defn- record-exception [dataset-id ex] (jdbcd/with-query-results rows ["SELECT `text` FROM `dataset` WHERE `dataset`.`id` = ?" dataset-id] (let [[{text :text :or {text "{}"}}] rows metadata (json/read-str text)] (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:text (json/write-str (assoc metadata "error" (str ex)) :escape-slash false)})))) (defn- with-load-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loading"}) (func) (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "loaded"}) (catch Exception ex (warn ex "Error loading dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-load-status [dataset-id & body] `(with-load-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (defn- with-delete-status* [dataset-id func] (try (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "deleting"}) (func) (catch Exception ex (warn ex "Error deleting dataset") (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:status "error"}) (record-exception dataset-id ex)))) (defmacro with-delete-status [dataset-id & body] `(with-delete-status* ~dataset-id (fn [] ~@body))) ; XXX need :^once? (def max-warnings 10) (defn- truncate-warnings [warnings] (-> warnings (update-in ["duplicate-keys" "sampleID"] #(take max-warnings %)) (update-in ["duplicate-probes"] #(take max-warnings %)))) ; jdbcd/transaction will create a closure of our parameters, ; so we can't pass in the matrix seq w/o blowing the heap. We ; pass in a function to return the seq, instead. ; files: the files this matrix was loaded from, e.g. clinical & genomic matrix, plus their timestamps & file hashes ; metadata: the metadata for the matrix (should cgdata mix in the clinical metadata?) ; matrix-fn: function to return seq of data rows ; features: field metadata. Need a better name for this. (defn- load-dataset "Load matrix file and metadata. Skips the data load if file hashes are unchanged, and 'force' is false. Metadata is always updated." ([mname files metadata matrix-fn features] (load-dataset mname files metadata matrix-fn features false)) ([mname files metadata matrix-fn features force] (profile :trace :dataset-load (let [dataset-id (jdbcd/transaction (merge-m-ent mname metadata)) files (map fmt-time files)] (with-load-status dataset-id (when (or force (not (= (set files) (set (related-sources dataset-id))))) (p :dataset-clear (clear-by-exp dataset-id)) (p :dataset-sources (load-related-sources :dataset_source :dataset_id dataset-id files)) (p :dataset-table (let [{:keys [rows warnings]} (table-writer *tmp-dir* dataset-id matrix-fn)] (jdbcd/transaction (jdbcd/update-values :dataset ["`id` = ?" dataset-id] {:rows rows}) (when warnings (merge-m-ent mname (assoc metadata :loader (truncate-warnings warnings))))))))))))) (defn- dataset-by-name [dname & kprops] (let [props (clojure.string/join "," (map name kprops))] (jdbcd/with-query-results rows [(format "SELECT %s FROM `dataset` WHERE `name` = ?" props) (str dname)] (-> rows first)))) (def dataset-id-by-name (comp :id #(dataset-by-name % :id))) (defn delete-dataset [dataset] (let [dataset-id (dataset-id-by-name dataset)] (if dataset-id (with-delete-status dataset-id (clear-by-exp dataset-id) (jdbcd/do-commands (format "DELETE FROM `dataset` WHERE `id` = %d" dataset-id))) (info "Did not delete unknown dataset" dataset)))) (defn create-db [file & [{:keys [classname subprotocol make-pool?] :or {classname "org.h2.Driver" subprotocol "h2" make-pool? true}}]] (let [spec {:classname classname :subprotocol subprotocol :subname file :conn-customizer "conn_customizer" :make-pool? make-pool?}] (if make-pool? (delay (pool spec)) (delay (-> spec))))) ; XXX should sanitize the query (defn- run-query [q] (jdbcd/with-query-results rows (spy :trace (hsql/format q)) (vec rows))) ; ; Code queries ; (def ^:private codes-for-field-query (cached-statement "SELECT `ordering`, `value` FROM `field` JOIN `code` ON `field_id` = `field`.`id` WHERE `name` = ? AND `dataset_id` = ?" true)) (defn- codes-for-field [dataset-id field] (->> (codes-for-field-query field dataset-id) (map #(mapv % [:value :ordering])) (into {}))) ; ; All rows queries. ; ; All bins for the given fields. ; XXX inner join here? really? not just a where? (def ^:private all-rows-query (cached-statement "SELECT `name`, `i`, `scores` FROM (SELECT `name`, `id` FROM `field` INNER JOIN (TABLE(`name2` VARCHAR = ?) T) ON `name2` = `field`.`name` WHERE `dataset_id` = ?) AS P LEFT JOIN `field_score` ON `P`.`id` = `field_score`.`field_id`" true)) ; bins will all be the same size, except the last one. bin size is thus ; max of count of first two bins. ; Loop over bins, copying into pre-allocated output array. ; {"foxm1" [{:name "foxm1" :scores <bytes>} ... ] (defn concat-field-bins [bins] (let [float-bins (mapv #(update-in % [:scores] score-decode) bins) sizes (mapv #(count (:scores %)) float-bins) bin-size (apply max (take 2 sizes)) row-count (apply + sizes) out (float-array row-count)] (doseq [{:keys [scores i]} float-bins] (System/arraycopy scores 0 out (* i bin-size) (count scores))) ; XXX mutate "out" in place out)) ; return float arrays of all rows for the given fields (defn- all-rows [dataset-id fields] (let [field-bins (->> (all-rows-query (to-array fields) dataset-id) (group-by :name))] (into {} (for [[k v] field-bins] [k (concat-field-bins v)])))) ; ; ; (defn bin-offset [i] [(quot i bin-size) (rem i bin-size)]) ; merge bin number and bin offset for a row (defn- merge-bin-off [{i :i :as row}] (merge row {:bin (quot i bin-size) :off (rem i bin-size)})) ; Returns mapping from input bin offset to output buffer for a ; given row. (defn- bin-mapping [{off :off row :order}] [off row]) ; Gets called once for each bin in the request. ; order is row -> order in output buffer. ; bin is the bin for the given set of rows ; rows is ({:i 12 :bin 1 :off 1}, ... ), where all :bin are the same (defn- pick-rows-fn [[bin rows]] [bin (partial ashuffle-float (map bin-mapping rows))]) ; Take an ordered list of requested rows, and generate fns to copy ; values from a score bin to an output array. Returns one function ; for each score bin in the request. ; ; rows ({:i 12 :bin 1 :off 1}, ... ) (defn- pick-rows-fns [rows] (let [by-bin (group-by :bin rows)] (apply hash-map (mapcat pick-rows-fn by-bin)))) ; Take map of bin copy fns, list of scores rows, and a map of output arrays, ; copying the scores to the output arrays via the bin copy fns. (defn- build-score-arrays [rows bfns out] (doseq [{i :i scores :scores field :name} rows] ((bfns i) (out field) scores)) out) (defn- col-arrays [columns n] (zipmap columns (repeatedly (partial float-array n Double/NaN)))) ; Doing an inner join on a table literal, instead of a big IN clause, so it will hit ; the index. ; XXX performance of the :in clause? ; XXX make a prepared statement ; Instead of building a custom query each time, this can be ; rewritten as a join against a TABLE literal, or as ; IN (SELECT * FROM TABLE(x INT = (?))). Should check performance ; of both & drop the (format) call. (def ^:private dataset-fields-query "SELECT name, i, scores FROM (SELECT `field`.`name`, `field`.`id` FROM `field` INNER JOIN TABLE(name varchar=?) T ON T.`name`=`field`.`name` WHERE (`field`.`dataset_id` = ?)) P LEFT JOIN `field_score` ON P.id = `field_score`.`field_id` WHERE `field_score`.`i` IN (%s)") (defn- select-scores-full [dataset-id columns bins] (let [q (format dataset-fields-query (clojure.string/join "," (repeat (count bins) "?"))) c (to-array (map str columns)) i bins] (jdbcd/with-query-results rows (vec (concat [q c dataset-id] i)) (vec rows)))) ; Returns rows from (dataset-id column-name) matching ; values. Returns a hashmap for each matching row. ; { :i The implicit index in the column as stored on disk. ; ;order The order of the row the result set. ; :value The value of the row. ; } (defn- rows-matching [dataset-id column-name values] (let [val-set (set values)] (->> column-name (vector) (all-rows dataset-id) ; Retrieve the full column (vals) (first) ; calculate row index in the column (map #(-> {:i %1 :value %2}) (range)) ; [{:i 0 :value 1.2} ...] (filter (comp val-set :value)) ; filter rows not matching the request. (group-by :value) (#(map (fn [g] (get % g [nil])) values)) ; arrange by output order. (apply concat) ; flatten groups. (mapv #(assoc %2 :order %1) (range))))) ; assoc row output order. (defn- float-nil [x] (when x (float x))) ; Get codes for samples in request ; Get the entire sample column ; Find the rows matching the samples, ordered by sample list ; Have to scan the sample column, group by sample, and map over the ordering ; Build shuffle functions, per bin, to copy bins to output buffer ; Run scores query ; Copy to output buffer (defn- genomic-read-req [req] (let [{:keys [samples table columns]} req dataset-id (dataset-id-by-name table) samp->code (codes-for-field dataset-id "sampleID") order (mapv (comp float-nil samp->code) samples) ; codes in request order rows (rows-matching dataset-id "sampleID" order) rows-to-copy (->> rows (filter :value) (mapv merge-bin-off)) bins (mapv :bin rows-to-copy) ; list of bins to pull. bfns (pick-rows-fns rows-to-copy)] ; make fns that map from input bin to ; output buffer, one fn per input bin. (-> (select-scores-full dataset-id columns (distinct bins)) (#(mapv cvt-scores %)) (build-score-arrays bfns (col-arrays columns (count rows)))))) ; ; ; Methods for providing a sql abstraction over the column store. ; ; (def ^:private field-ids-query (cached-statement "SELECT `id`, `name` FROM `field` WHERE `dataset_id` = ? AND `name` IN (SELECT * FROM TABLE(x VARCHAR = (?)))" true)) (defn- fetch-field-ids [dataset-id names] (when-let [ids (field-ids-query dataset-id names)] (map (juxt :name :id) ids))) ; (def ^:private codes-for-values-query (cached-statement "SELECT `ordering`, `value` FROM `code` JOIN TABLE(x INT = (?)) V on `x` = `ordering` WHERE `field_id` = ?" true)) (defn- codes-for-values [field-id values] (when-let [codes (codes-for-values-query values field-id)] (map (juxt :ordering :value) codes))) ; (def ^:private field-bins-query (cached-statement "SELECT `scores`, `i` FROM `field_score` WHERE `field_id` = ? AND `i` IN (SELECT * FROM TABLE(x INT = (?)))" true)) (defn- fetch-bins [field-id bins] (when-let [scores (field-bins-query field-id bins)] (map #(update-in % [:scores] bytes-to-floats) scores))) ; (def ^:private has-codes-query (cached-statement "SELECT EXISTS(SELECT `ordering` FROM `code` WHERE `field_id` = ?) hascodes" true)) (defn has-codes? [field-id] (-> (has-codes-query field-id) first :hascodes)) ; (def ^:private has-genes-query (cached-statement "SELECT EXISTS(SELECT `gene` FROM `field_gene` WHERE `field_id` = ?) hasgenes" true)) (defn has-genes? [field-id] (-> (has-genes-query field-id) first :hasgenes)) ; (def ^:private has-position-query (cached-statement "SELECT EXISTS(SELECT `bin` FROM `field_position` WHERE `field_id` = ?) hasposition" true)) (defn has-position? [field-id] (-> (has-position-query field-id) first :hasposition)) ; (defn update-codes-cache [codes field-id new-bins cache] (match [codes] [nil] (update-codes-cache (if (has-codes? field-id) [:yes {}] [:no]) field-id new-bins cache) [[:no]] codes [[:yes code-cache]] [:yes (let [values (distinct (mapcat cache new-bins)) missing (filterv #(not (contains? code-cache %)) values)] (into code-cache (codes-for-values field-id missing)))])) (defn update-cache [cache field-id rows] (let [bins (distinct (map #(quot % bin-size) rows)) missing (filterv #(not (contains? cache %)) bins)] (if (seq missing) (let [new-cache (->> missing (fetch-bins field-id) (map (juxt :i :scores)) (into (or cache {})))] (update-in new-cache [:codes] update-codes-cache field-id missing new-cache)) cache))) ; ; ; return fn of rows->vals ; (defmulti fetch-rows (fn [cache rows field-id] (cond (has-genes? field-id) :gene (has-position? field-id) :position :else :binned))) ; binned fields (defmethod fetch-rows :binned [cache rows field-id] (swap! cache update-in [field-id] update-cache field-id rows) (let [f (@cache field-id) getter (match [(:codes f)] ; XXX cast to int here is pretty horrible. ; Really calls for an int array bin in h2. [[:yes vals->codes]] (fn [bin off] (let [v (aget ^floats (f bin) off)] (if (. Float isNaN v) nil (vals->codes (int v))))) [[:no]] (fn [bin off] (get (f bin) off)))] (fn [row] (apply getter (bin-offset row))))) (def ^:private field-genes-by-row-query (cached-statement "SELECT `row`, `gene` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) (defn field-genes-by-row [field-id rows] (->> (field-genes-by-row-query rows field-id) (group-by :row) (map (fn [[k rows]] [k (mapv :gene rows)])))) ; gene fields (defmethod fetch-rows :gene [cache rows field-id] (into {} (field-genes-by-row field-id rows))) (def ^:private field-position-by-row-query (cached-statement "SELECT `row`, `chrom`, `chromStart`, `chromEnd`, `strand` FROM `field_position` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `row` WHERE `field_id` = ?" true)) ; position fields (defn field-position-by-row [field-id rows] (->> (field-position-by-row-query rows field-id) (map (fn [{:keys [row] :as values}] [row (dissoc values :row)])))) (defmethod fetch-rows :position [cache rows field-id] (into {} (field-position-by-row field-id rows))) ; ; Indexed field lookups (gene & position) ; (defn has-index? [fields field] (let [field-id (fields field)] (or (has-genes? field-id) (has-position? field-id)))) ; gene ; Selecting `gene` as well adds a lot to the query time. Might ; need it if we need to cache gene names. (def ^:private field-genes-query (cached-statement "SELECT `row` FROM `field_gene` INNER JOIN TABLE(x VARCHAR = (?)) X ON X.x = `gene` WHERE `field_id` = ?" true)) (defn field-genes [field-id genes] (->> (field-genes-query genes field-id) (map :row))) (defn fetch-genes [field-id values] (into (i/int-set) (field-genes field-id values))) ; position (def ^:private field-position-one-query (cached-statement "SELECT `row` FROM `field_position` WHERE `field_id` = ? AND `chrom` = ? AND (`bin` >= ? AND `bin` <= ?) AND `chromStart` <= ? AND `chromEnd` >= ?" true)) ; [:in "position" [["chr17" 100 20000]]] (defn field-position [field-id values] (->> (mapcat (fn [[chr start end]] (let [istart (int start) iend (int end) bins (overlapping-bins istart iend)] (mapcat (fn [[s e]] (field-position-one-query field-id chr s e iend istart)) bins))) values) (map :row))) (defn fetch-position [field-id values] (into (i/int-set) (field-position field-id values))) ; fetch-indexed doesn't cache, and it's unclear ; if we should cache the indexed fields during 'restrict'. ; h2 also has caches, so it might be better to rely on them, ; simply doing the query again if we need it. ; Otherwise, we might want to inform the cache of what columns are ; required later during 'restrict', or in 'project', so ; we know if they should be cached. (defn fetch-indexed [fields field values] (let [field-id (fields field)] (cond (has-position? field-id) (fetch-position field-id values) (has-genes? field-id) (fetch-genes field-id values)))) ; ; sql eval methods ; ; might want to use a reader literal for field names, so we ; find them w/o knowing syntax. (defn collect-fields [exp] (match [exp] [[:in field _]] [field] [[:in arrmod field _]] [field] [[:and & subexps]] (mapcat collect-fields subexps) [[:or & subexps]] (mapcat collect-fields subexps) [nil] [])) ; ; Computing the "set of all rows" to begin a query was taking much too long ; (minutes, for tens of millions of rows). Switching from sorted-set to int-set ; brought this down to tens of seconds, which was still too slow. Here we ; generate the int-set in parallel & merge with i/union, which is fast. This ; brings the time down to a couple seconds for tens of millions of rows. We ; then, additionally, cache the set, and re-use it if possible. We can ; quickly create smaller sets with i/range, so we memoize such that we ; compute a new base set only if the current memoized size is too small. ; ; Note that this means that if we load a very large dataset, then delete it, ; the memory required to represent all the rows of that dataset is not released ; until the server is restarted. ; ; Alternative fixes might be 1) use an agent to always maintain the largest ; "set of all rows" required for the loaded datasets, updating on dataset add/remove; ; 2) using a different representation of contiguous rows, e.g. [start, end]. We ; would need to review the down-stream performance implications of this (i.e. computing ; union and intersection, generating db queries, etc.) (def block-size 1e6) (defn int-set-bins [n] (let [blocks (+ (quot n block-size) (if (= 0 (rem n block-size)) 0 1))] (map (fn [i] [(* i block-size) (min (* (+ i 1) block-size) n)]) (range blocks)))) (defn set-of-all [n] (let [blocks (/ n block-size)] (reduce #(i/union % %2) (pmap (fn [[start end]] (into (i/int-set) (range start end))) (int-set-bins n))))) (defn mem-min [f] (let [mem (atom nil)] (fn [n] (if (> n (count @mem)) (let [ret (f n)] (reset! mem ret) ret) (i/range @mem 0 (- n 1)))))) (def set-of-all-cache (mem-min set-of-all)) ; XXX Look at memory use of pulling :gene field. If it's not ; interned, it could be expensive. ; XXX Map keywords to strings, for dataset & field names? ; XXX Add some param guards, esp. unknown field. (defn eval-sql [{[from] :from where :where select :select :as exp}] (let [{dataset-id :id N :rows} (dataset-by-name from :id :rows) fields (into {} (fetch-field-ids dataset-id (into (collect-fields where) select))) cache (atom {}) fetch (fn [rows field] (if (not-empty rows) (fetch-rows cache rows (fields field)) {}))] (evaluate (set-of-all-cache N) {:fetch fetch :fetch-indexed (partial fetch-indexed fields) :indexed? (partial has-index? fields)} exp))) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["sampleID"] :from ["BRCA1"] :where [:in "sampleID" ; ["HG00122" "NA07056" "HG01870" "NA18949" "HG02375" ; "HG00150" "NA18528" "HG02724"]]})) ;(jdbcd/with-connection @(:db cavm.core/testdb) ; (eval-sql {:select ["alt"] :from ["BRCA1"] :where [:in "position" [["chr17" 10000 100000000]]]})) ; ; ; ; ; ; ; Each req is a map of ; :table "tablename" ; :columns '("column1" "column2") ; :samples '("sample1" "sample2") ; We merge into 'data the columns that we can resolve, like ; :data { 'column1 [1.1 1.2] 'column2 [2.1 2.2] } (defn- genomic-source [reqs] (map #(update-in % [:data] merge (genomic-read-req %)) reqs)) ; ; hand-spun migrations. ; (def column-len-query "SELECT character_maximum_length as len FROM information_schema.columns as c WHERE c.table_name = ? AND c.column_name = ?") (def bad-probemap-query "SELECT `dataset`.`name` FROM `dataset` LEFT JOIN `dataset` as d ON d.`name` = `dataset`.`probemap` WHERE `dataset`.`probeMap` IS NOT NULL AND d.`name` IS NULL") (defn delete-if-probemap-invalid [] (jdbcd/with-query-results bad-datasets [bad-probemap-query] (doseq [{dataset :name} bad-datasets] (delete-dataset dataset)))) ; dataset.probemap refers to a dataset.name, but previously ; had different data size, and was not enforced as a foreign ; key. Check for old data size, and run migration if it's old ; ; The migration will delete datasets that have invalid probemap, ; and update the field. (defn migrate-probemap [] (jdbcd/with-query-results pm-key [column-len-query "DATASET" "PROBEMAP"] (when (and (seq pm-key) (= (:len (first pm-key)) 255)) (info "Migrating probeMap field") (delete-if-probemap-invalid) (jdbcd/do-commands "AlTER TABLE `dataset` ALTER COLUMN `probeMap` VARCHAR(1000)" "ALTER TABLE `dataset` ADD FOREIGN KEY (`probeMap`) REFERENCES `dataset` (`name`)")))) (defn- migrate [] (migrate-probemap) ; ...add more here ) (defn- create[] (jdbcd/transaction (apply jdbcd/do-commands cohorts-table) (apply jdbcd/do-commands source-table) (apply jdbcd/do-commands dataset-table) (apply jdbcd/do-commands dataset-source-table) (apply jdbcd/do-commands field-table) (apply jdbcd/do-commands field-score-table) (apply jdbcd/do-commands feature-table) (apply jdbcd/do-commands code-table) (apply jdbcd/do-commands field-position-table) (apply jdbcd/do-commands field-gene-table)) (migrate)) ; ; add TABLE handling for honeysql ; (defmethod hsqlfmt/format-clause :table [[_ [fields alias]] _] (str "TABLE(" (clojure.string/join ", " (map (fn [[name type values]] (str (hsqlfmt/to-sql name) " " (hsqlfmt/to-sql type) "=" (hsqlfmt/paren-wrap (clojure.string/join ", " (map hsqlfmt/to-sql values))))) fields)) ") " (hsqlfmt/to-sql alias))) ; Fix GROUP_CONCAT in honeysql (defn- format-concat ([value {:keys [order separator]}] (let [oclause (if (nil? order) "" (str " order by " (hsqlfmt/to-sql order))) sclause (if (nil? separator) "" (str " separator " (hsqlfmt/to-sql separator)))] (str "GROUP_CONCAT(" (hsqlfmt/to-sql value) oclause sclause ")")))) (defmethod hsqlfmt/fn-handler "group_concat" [_ value & args] (format-concat value args)) (defrecord H2Db [db]) (extend-protocol XenaDb H2Db (write-matrix [this mname files metadata data-fn features always] (jdbcd/with-connection @(:db this) (load-dataset mname files metadata data-fn features always))) (delete-matrix [this mname] (jdbcd/with-connection @(:db this) (delete-dataset mname))) (run-query [this query] (jdbcd/with-connection @(:db this) (run-query query))) (column-query [this query] (jdbcd/with-connection @(:db this) (eval-sql query))) (fetch [this reqs] (jdbcd/with-connection @(:db this) (doall (genomic-source reqs)))) (close [this] ; XXX test for pool, or datasource before running? (.close ^ComboPooledDataSource (:datasource @(:db this)) false))) (defn create-xenadb [& args] (let [db (apply create-db args)] (jdbcd/with-connection @db (create)) (H2Db. db)))
[ { "context": "equire\n [reagent.core :as r]))\n\n\n(def names [\n\"Guillermo Wynn  \"\n\"Darlena Paulin  \"\n\"Mara Edelstein  \"\n\"Hillary", "end": 85, "score": 0.9998883605003357, "start": 71, "tag": "NAME", "value": "Guillermo Wynn" }, { "context": ".core :as r]))\n\n\n(def names [\n\"Guillermo Wynn  \"\n\"Darlena Paulin  \"\n\"Mara Edelstein  \"\n\"Hillary Minogue  \"\n\"Eleono", "end": 104, "score": 0.9998885989189148, "start": 90, "tag": "NAME", "value": "Darlena Paulin" }, { "context": "ef names [\n\"Guillermo Wynn  \"\n\"Darlena Paulin  \"\n\"Mara Edelstein  \"\n\"Hillary Minogue  \"\n\"Eleonor Shear  \"\n\"Wynona ", "end": 123, "score": 0.9998834729194641, "start": 109, "tag": "NAME", "value": "Mara Edelstein" }, { "context": "mo Wynn  \"\n\"Darlena Paulin  \"\n\"Mara Edelstein  \"\n\"Hillary Minogue  \"\n\"Eleonor Shear  \"\n\"Wynona Harling  \"\n\"Beth Pir", "end": 143, "score": 0.999894917011261, "start": 128, "tag": "NAME", "value": "Hillary Minogue" }, { "context": "Paulin  \"\n\"Mara Edelstein  \"\n\"Hillary Minogue  \"\n\"Eleonor Shear  \"\n\"Wynona Harling  \"\n\"Beth Pires  \"\n\"Nida Lapeyr", "end": 161, "score": 0.99989253282547, "start": 148, "tag": "NAME", "value": "Eleonor Shear" }, { "context": "elstein  \"\n\"Hillary Minogue  \"\n\"Eleonor Shear  \"\n\"Wynona Harling  \"\n\"Beth Pires  \"\n\"Nida Lapeyrouse  \"\n\"Ricarda Li", "end": 180, "score": 0.9998931884765625, "start": 166, "tag": "NAME", "value": "Wynona Harling" }, { "context": " Minogue  \"\n\"Eleonor Shear  \"\n\"Wynona Harling  \"\n\"Beth Pires  \"\n\"Nida Lapeyrouse  \"\n\"Ricarda Liska  \"\n\"Synthia", "end": 195, "score": 0.9998898506164551, "start": 185, "tag": "NAME", "value": "Beth Pires" }, { "context": "eonor Shear  \"\n\"Wynona Harling  \"\n\"Beth Pires  \"\n\"Nida Lapeyrouse  \"\n\"Ricarda Liska  \"\n\"Synthia Dvorak  \"\n\"Royce Mu", "end": 215, "score": 0.9998970627784729, "start": 200, "tag": "NAME", "value": "Nida Lapeyrouse" }, { "context": "na Harling  \"\n\"Beth Pires  \"\n\"Nida Lapeyrouse  \"\n\"Ricarda Liska  \"\n\"Synthia Dvorak  \"\n\"Royce Murawski  \"\n\"Nerissa", "end": 233, "score": 0.9998928904533386, "start": 220, "tag": "NAME", "value": "Ricarda Liska" }, { "context": "h Pires  \"\n\"Nida Lapeyrouse  \"\n\"Ricarda Liska  \"\n\"Synthia Dvorak  \"\n\"Royce Murawski  \"\n\"Nerissa Yocom  \"\n\"Tonisha ", "end": 252, "score": 0.9998956322669983, "start": 238, "tag": "NAME", "value": "Synthia Dvorak" }, { "context": "peyrouse  \"\n\"Ricarda Liska  \"\n\"Synthia Dvorak  \"\n\"Royce Murawski  \"\n\"Nerissa Yocom  \"\n\"Tonisha Cardon  \"\n\"Rosalind", "end": 271, "score": 0.9998949766159058, "start": 257, "tag": "NAME", "value": "Royce Murawski" }, { "context": "a Liska  \"\n\"Synthia Dvorak  \"\n\"Royce Murawski  \"\n\"Nerissa Yocom  \"\n\"Tonisha Cardon  \"\n\"Rosalind Wigington  \"\n\"Sha", "end": 289, "score": 0.9998893737792969, "start": 276, "tag": "NAME", "value": "Nerissa Yocom" }, { "context": "a Dvorak  \"\n\"Royce Murawski  \"\n\"Nerissa Yocom  \"\n\"Tonisha Cardon  \"\n\"Rosalind Wigington  \"\n\"Shaunta Stenson  \"\n\"An", "end": 308, "score": 0.9998891353607178, "start": 294, "tag": "NAME", "value": "Tonisha Cardon" }, { "context": "Murawski  \"\n\"Nerissa Yocom  \"\n\"Tonisha Cardon  \"\n\"Rosalind Wigington  \"\n\"Shaunta Stenson  \"\n\"Anette Emanuel  \"\n\"Oma Pu", "end": 331, "score": 0.9998909831047058, "start": 313, "tag": "NAME", "value": "Rosalind Wigington" }, { "context": "com  \"\n\"Tonisha Cardon  \"\n\"Rosalind Wigington  \"\n\"Shaunta Stenson  \"\n\"Anette Emanuel  \"\n\"Oma Pullum  \"\n\"Moses Hornb", "end": 351, "score": 0.9998844861984253, "start": 336, "tag": "NAME", "value": "Shaunta Stenson" }, { "context": "on  \"\n\"Rosalind Wigington  \"\n\"Shaunta Stenson  \"\n\"Anette Emanuel  \"\n\"Oma Pullum  \"\n\"Moses Hornberger  \"\n\"Yvette Fe", "end": 370, "score": 0.9998858571052551, "start": 356, "tag": "NAME", "value": "Anette Emanuel" }, { "context": "ington  \"\n\"Shaunta Stenson  \"\n\"Anette Emanuel  \"\n\"Oma Pullum  \"\n\"Moses Hornberger  \"\n\"Yvette Fenstermaker  \"\n\"", "end": 385, "score": 0.9998904466629028, "start": 375, "tag": "NAME", "value": "Oma Pullum" }, { "context": "nta Stenson  \"\n\"Anette Emanuel  \"\n\"Oma Pullum  \"\n\"Moses Hornberger  \"\n\"Yvette Fenstermaker  \"\n\"Sung Summa  \"\n\"Kately", "end": 406, "score": 0.999885082244873, "start": 390, "tag": "NAME", "value": "Moses Hornberger" }, { "context": "e Emanuel  \"\n\"Oma Pullum  \"\n\"Moses Hornberger  \"\n\"Yvette Fenstermaker  \"\n\"Sung Summa  \"\n\"Katelynn Bradshaw  \"\n\"Robena M", "end": 430, "score": 0.9998894333839417, "start": 411, "tag": "NAME", "value": "Yvette Fenstermaker" }, { "context": "  \"\n\"Moses Hornberger  \"\n\"Yvette Fenstermaker  \"\n\"Sung Summa  \"\n\"Katelynn Bradshaw  \"\n\"Robena Manigo  \"\n\"Dong ", "end": 445, "score": 0.9998874068260193, "start": 435, "tag": "NAME", "value": "Sung Summa" }, { "context": "berger  \"\n\"Yvette Fenstermaker  \"\n\"Sung Summa  \"\n\"Katelynn Bradshaw  \"\n\"Robena Manigo  \"\n\"Dong Olivarria  \"\n\"Margaret", "end": 467, "score": 0.9998864531517029, "start": 450, "tag": "NAME", "value": "Katelynn Bradshaw" }, { "context": "termaker  \"\n\"Sung Summa  \"\n\"Katelynn Bradshaw  \"\n\"Robena Manigo  \"\n\"Dong Olivarria  \"\n\"Margarett Oakman  \"\n\"Roman", "end": 485, "score": 0.9998864531517029, "start": 472, "tag": "NAME", "value": "Robena Manigo" }, { "context": "Summa  \"\n\"Katelynn Bradshaw  \"\n\"Robena Manigo  \"\n\"Dong Olivarria  \"\n\"Margarett Oakman  \"\n\"Roman Sabourin  \"\n\"Ayann", "end": 504, "score": 0.9998900890350342, "start": 490, "tag": "NAME", "value": "Dong Olivarria" }, { "context": "Bradshaw  \"\n\"Robena Manigo  \"\n\"Dong Olivarria  \"\n\"Margarett Oakman  \"\n\"Roman Sabourin  \"\n\"Ayanna Vito  \"\n\"Shellie Ce", "end": 525, "score": 0.9998816251754761, "start": 509, "tag": "NAME", "value": "Margarett Oakman" }, { "context": "anigo  \"\n\"Dong Olivarria  \"\n\"Margarett Oakman  \"\n\"Roman Sabourin  \"\n\"Ayanna Vito  \"\n\"Shellie Cerrato  \"\n\"Reuben La", "end": 544, "score": 0.9998877644538879, "start": 530, "tag": "NAME", "value": "Roman Sabourin" }, { "context": "arria  \"\n\"Margarett Oakman  \"\n\"Roman Sabourin  \"\n\"Ayanna Vito  \"\n\"Shellie Cerrato  \"\n\"Reuben Lash  \"\n\"Amee Hora", "end": 560, "score": 0.9998833537101746, "start": 549, "tag": "NAME", "value": "Ayanna Vito" }, { "context": "ett Oakman  \"\n\"Roman Sabourin  \"\n\"Ayanna Vito  \"\n\"Shellie Cerrato  \"\n\"Reuben Lash  \"\n\"Amee Horak  \"\n\"Jerold Sisemor", "end": 580, "score": 0.9998807311058044, "start": 565, "tag": "NAME", "value": "Shellie Cerrato" }, { "context": " Sabourin  \"\n\"Ayanna Vito  \"\n\"Shellie Cerrato  \"\n\"Reuben Lash  \"\n\"Amee Horak  \"\n\"Jerold Sisemore  \"\n\"Mellissa L", "end": 596, "score": 0.9998865127563477, "start": 585, "tag": "NAME", "value": "Reuben Lash" }, { "context": "anna Vito  \"\n\"Shellie Cerrato  \"\n\"Reuben Lash  \"\n\"Amee Horak  \"\n\"Jerold Sisemore  \"\n\"Mellissa Lobel  \"\n\"Kristi", "end": 611, "score": 0.9998908042907715, "start": 601, "tag": "NAME", "value": "Amee Horak" }, { "context": "hellie Cerrato  \"\n\"Reuben Lash  \"\n\"Amee Horak  \"\n\"Jerold Sisemore  \"\n\"Mellissa Lobel  \"\n\"Kristina Gower  \"\n\"Collen ", "end": 631, "score": 0.9998882412910461, "start": 616, "tag": "NAME", "value": "Jerold Sisemore" }, { "context": "euben Lash  \"\n\"Amee Horak  \"\n\"Jerold Sisemore  \"\n\"Mellissa Lobel  \"\n\"Kristina Gower  \"\n\"Collen Mccreary  \"\n\"Jamie ", "end": 650, "score": 0.9998888969421387, "start": 636, "tag": "NAME", "value": "Mellissa Lobel" }, { "context": " Horak  \"\n\"Jerold Sisemore  \"\n\"Mellissa Lobel  \"\n\"Kristina Gower  \"\n\"Collen Mccreary  \"\n\"Jamie Drinnon  \"\n\"Wanetta", "end": 669, "score": 0.999886155128479, "start": 655, "tag": "NAME", "value": "Kristina Gower" }, { "context": "isemore  \"\n\"Mellissa Lobel  \"\n\"Kristina Gower  \"\n\"Collen Mccreary  \"\n\"Jamie Drinnon  \"\n\"Wanetta Dismukes  \"\n\"Chu Ki", "end": 689, "score": 0.9998918175697327, "start": 674, "tag": "NAME", "value": "Collen Mccreary" }, { "context": " Lobel  \"\n\"Kristina Gower  \"\n\"Collen Mccreary  \"\n\"Jamie Drinnon  \"\n\"Wanetta Dismukes  \"\n\"Chu Kiel  \"\n\"Lionel Jaeg", "end": 707, "score": 0.9998962879180908, "start": 694, "tag": "NAME", "value": "Jamie Drinnon" }, { "context": "a Gower  \"\n\"Collen Mccreary  \"\n\"Jamie Drinnon  \"\n\"Wanetta Dismukes  \"\n\"Chu Kiel  \"\n\"Lionel Jaeger  \"\n\"Felica Rollo  ", "end": 728, "score": 0.9998950362205505, "start": 712, "tag": "NAME", "value": "Wanetta Dismukes" }, { "context": "creary  \"\n\"Jamie Drinnon  \"\n\"Wanetta Dismukes  \"\n\"Chu Kiel  \"\n\"Lionel Jaeger  \"\n\"Felica Rollo  \"\n\"Pablo Sege", "end": 741, "score": 0.9998952150344849, "start": 733, "tag": "NAME", "value": "Chu Kiel" }, { "context": "mie Drinnon  \"\n\"Wanetta Dismukes  \"\n\"Chu Kiel  \"\n\"Lionel Jaeger  \"\n\"Felica Rollo  \"\n\"Pablo Segers  \"\n\"Tawna Inabi", "end": 759, "score": 0.999890148639679, "start": 746, "tag": "NAME", "value": "Lionel Jaeger" }, { "context": "netta Dismukes  \"\n\"Chu Kiel  \"\n\"Lionel Jaeger  \"\n\"Felica Rollo  \"\n\"Pablo Segers  \"\n\"Tawna Inabinet  \"\n\"Jaleesa P", "end": 776, "score": 0.9998894929885864, "start": 764, "tag": "NAME", "value": "Felica Rollo" }, { "context": "\n\"Chu Kiel  \"\n\"Lionel Jaeger  \"\n\"Felica Rollo  \"\n\"Pablo Segers  \"\n\"Tawna Inabinet  \"\n\"Jaleesa Portner  \"\n\"Myrna ", "end": 793, "score": 0.9998939037322998, "start": 781, "tag": "NAME", "value": "Pablo Segers" }, { "context": "onel Jaeger  \"\n\"Felica Rollo  \"\n\"Pablo Segers  \"\n\"Tawna Inabinet  \"\n\"Jaleesa Portner  \"\n\"Myrna Ridinger  \"\n\"Annett", "end": 812, "score": 0.9998905062675476, "start": 798, "tag": "NAME", "value": "Tawna Inabinet" }, { "context": "ica Rollo  \"\n\"Pablo Segers  \"\n\"Tawna Inabinet  \"\n\"Jaleesa Portner  \"\n\"Myrna Ridinger  \"\n\"Annette Lawyer  \"\n\"Mike Sh", "end": 832, "score": 0.9998911023139954, "start": 817, "tag": "NAME", "value": "Jaleesa Portner" }, { "context": "Segers  \"\n\"Tawna Inabinet  \"\n\"Jaleesa Portner  \"\n\"Myrna Ridinger  \"\n\"Annette Lawyer  \"\n\"Mike Shue  \"\n\"Min Angus  \"", "end": 851, "score": 0.9998984336853027, "start": 837, "tag": "NAME", "value": "Myrna Ridinger" }, { "context": "abinet  \"\n\"Jaleesa Portner  \"\n\"Myrna Ridinger  \"\n\"Annette Lawyer  \"\n\"Mike Shue  \"\n\"Min Angus  \"\n\"Blondell Boise  \"", "end": 870, "score": 0.9998751878738403, "start": 856, "tag": "NAME", "value": "Annette Lawyer" }, { "context": "Portner  \"\n\"Myrna Ridinger  \"\n\"Annette Lawyer  \"\n\"Mike Shue  \"\n\"Min Angus  \"\n\"Blondell Boise  \"\n\"Laine Sheple", "end": 884, "score": 0.9998823404312134, "start": 875, "tag": "NAME", "value": "Mike Shue" }, { "context": "rna Ridinger  \"\n\"Annette Lawyer  \"\n\"Mike Shue  \"\n\"Min Angus  \"\n\"Blondell Boise  \"\n\"Laine Shepley  \"\n\"Eddie Ca", "end": 898, "score": 0.9998793005943298, "start": 889, "tag": "NAME", "value": "Min Angus" }, { "context": "\"\n\"Annette Lawyer  \"\n\"Mike Shue  \"\n\"Min Angus  \"\n\"Blondell Boise  \"\n\"Laine Shepley  \"\n\"Eddie Cadwallader  \"\n\"Parke", "end": 917, "score": 0.9998884201049805, "start": 903, "tag": "NAME", "value": "Blondell Boise" }, { "context": "\"\n\"Mike Shue  \"\n\"Min Angus  \"\n\"Blondell Boise  \"\n\"Laine Shepley  \"\n\"Eddie Cadwallader  \"\n\"Parker Band  \"\n\"Jana Br", "end": 935, "score": 0.9998682141304016, "start": 922, "tag": "NAME", "value": "Laine Shepley" }, { "context": "in Angus  \"\n\"Blondell Boise  \"\n\"Laine Shepley  \"\n\"Eddie Cadwallader  \"\n\"Parker Band  \"\n\"Jana Bryer  \"\n])\n\n\n(defn disp", "end": 957, "score": 0.9998890161514282, "start": 940, "tag": "NAME", "value": "Eddie Cadwallader" }, { "context": "Boise  \"\n\"Laine Shepley  \"\n\"Eddie Cadwallader  \"\n\"Parker Band  \"\n\"Jana Bryer  \"\n])\n\n\n(defn display-names\n \"Dis", "end": 973, "score": 0.9998664855957031, "start": 962, "tag": "NAME", "value": "Parker Band" }, { "context": "Shepley  \"\n\"Eddie Cadwallader  \"\n\"Parker Band  \"\n\"Jana Bryer  \"\n])\n\n\n(defn display-names\n \"Displays APIs that", "end": 988, "score": 0.9998782873153687, "start": 978, "tag": "NAME", "value": "Jana Bryer" } ]
testme/src/cljs/testme/home.cljs
vallard/Reagent-Example
0
(ns testme.home (:require [reagent.core :as r])) (def names [ "Guillermo Wynn  " "Darlena Paulin  " "Mara Edelstein  " "Hillary Minogue  " "Eleonor Shear  " "Wynona Harling  " "Beth Pires  " "Nida Lapeyrouse  " "Ricarda Liska  " "Synthia Dvorak  " "Royce Murawski  " "Nerissa Yocom  " "Tonisha Cardon  " "Rosalind Wigington  " "Shaunta Stenson  " "Anette Emanuel  " "Oma Pullum  " "Moses Hornberger  " "Yvette Fenstermaker  " "Sung Summa  " "Katelynn Bradshaw  " "Robena Manigo  " "Dong Olivarria  " "Margarett Oakman  " "Roman Sabourin  " "Ayanna Vito  " "Shellie Cerrato  " "Reuben Lash  " "Amee Horak  " "Jerold Sisemore  " "Mellissa Lobel  " "Kristina Gower  " "Collen Mccreary  " "Jamie Drinnon  " "Wanetta Dismukes  " "Chu Kiel  " "Lionel Jaeger  " "Felica Rollo  " "Pablo Segers  " "Tawna Inabinet  " "Jaleesa Portner  " "Myrna Ridinger  " "Annette Lawyer  " "Mike Shue  " "Min Angus  " "Blondell Boise  " "Laine Shepley  " "Eddie Cadwallader  " "Parker Band  " "Jana Bryer  " ]) (defn display-names "Displays APIs that match the search string" [search-string] [:div {:class "container-fluid"} [:center (for [person-name names] ;; tricky regular expression to see if the search string matches the name (if (or (re-find (re-pattern (str "(?i)" search-string)) person-name) (= "" search-string)) ^{ :key (.indexOf names person-name)} [:div {:class "col-sm-4"} [:div {:class "panel panel-default"} [:div {:class "panel-heading"} person-name]]]))]]) (defn show-home [] ;; First, display banner and search text box. (let [search-string (r/atom "")] (fn [] [:div {:class "jumbotron " } [:div {:class "container-fluid"} [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:h2 [:center "Fun names" ]] [:p {:class "center"} "Filter names" ] [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:input.form-control { :type "text" :placeholder "Filter names" :value @search-string :on-change #(reset! search-string (-> % .-target .-value)) }] ] ] ] [:div {:class "page-header"}] [display-names @search-string]])))
11394
(ns testme.home (:require [reagent.core :as r])) (def names [ "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " "<NAME>  " ]) (defn display-names "Displays APIs that match the search string" [search-string] [:div {:class "container-fluid"} [:center (for [person-name names] ;; tricky regular expression to see if the search string matches the name (if (or (re-find (re-pattern (str "(?i)" search-string)) person-name) (= "" search-string)) ^{ :key (.indexOf names person-name)} [:div {:class "col-sm-4"} [:div {:class "panel panel-default"} [:div {:class "panel-heading"} person-name]]]))]]) (defn show-home [] ;; First, display banner and search text box. (let [search-string (r/atom "")] (fn [] [:div {:class "jumbotron " } [:div {:class "container-fluid"} [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:h2 [:center "Fun names" ]] [:p {:class "center"} "Filter names" ] [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:input.form-control { :type "text" :placeholder "Filter names" :value @search-string :on-change #(reset! search-string (-> % .-target .-value)) }] ] ] ] [:div {:class "page-header"}] [display-names @search-string]])))
true
(ns testme.home (:require [reagent.core :as r])) (def names [ "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " "PI:NAME:<NAME>END_PI  " ]) (defn display-names "Displays APIs that match the search string" [search-string] [:div {:class "container-fluid"} [:center (for [person-name names] ;; tricky regular expression to see if the search string matches the name (if (or (re-find (re-pattern (str "(?i)" search-string)) person-name) (= "" search-string)) ^{ :key (.indexOf names person-name)} [:div {:class "col-sm-4"} [:div {:class "panel panel-default"} [:div {:class "panel-heading"} person-name]]]))]]) (defn show-home [] ;; First, display banner and search text box. (let [search-string (r/atom "")] (fn [] [:div {:class "jumbotron " } [:div {:class "container-fluid"} [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:h2 [:center "Fun names" ]] [:p {:class "center"} "Filter names" ] [:div {:class "row"}] [:div {:class "col-sm-2"}] [:div {:class "col-sm-8"} [:input.form-control { :type "text" :placeholder "Filter names" :value @search-string :on-change #(reset! search-string (-> % .-target .-value)) }] ] ] ] [:div {:class "page-header"}] [display-names @search-string]])))
[ { "context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde", "end": 31, "score": 0.9997715950012207, "start": 19, "tag": "NAME", "value": "Hirokuni Kim" }, { "context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses", "end": 64, "score": 0.9998798370361328, "start": 52, "tag": "NAME", "value": "Kevin Kredit" } ]
clojure/p10-case/src/p10_case/core.clj
kkredit/pl-study
0
;; Original author Hirokuni Kim ;; Modifications by Kevin Kredit ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#case (ns p10-case.core) (defn case-test-1 [n] (case n 1 "n is 1" 2 "n is 2" "n is other")) ;; Case options must be compile-time literals https://clojuredocs.org/clojure.core/case (defn -main "Main" [] (println (case-test-1 1)) (println (case-test-1 2)) (println (case-test-1 3)) )
124595
;; Original author <NAME> ;; Modifications by <NAME> ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#case (ns p10-case.core) (defn case-test-1 [n] (case n 1 "n is 1" 2 "n is 2" "n is other")) ;; Case options must be compile-time literals https://clojuredocs.org/clojure.core/case (defn -main "Main" [] (println (case-test-1 1)) (println (case-test-1 2)) (println (case-test-1 3)) )
true
;; Original author PI:NAME:<NAME>END_PI ;; Modifications by PI:NAME:<NAME>END_PI ;; Licensed under https://www.apache.org/licenses/LICENSE-2.0 ;; See https://kimh.github.io/clojure-by-example/#case (ns p10-case.core) (defn case-test-1 [n] (case n 1 "n is 1" 2 "n is 2" "n is other")) ;; Case options must be compile-time literals https://clojuredocs.org/clojure.core/case (defn -main "Main" [] (println (case-test-1 1)) (println (case-test-1 2)) (println (case-test-1 3)) )
[ { "context": "ror))\n\n(def default-config\n (merge\n {:server \"127.0.0.1\"\n :port 5000\n :protocol :http}\n #_{:pr", "end": 537, "score": 0.999277651309967, "start": 528, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ttp}\n #_{:protocol :https\n :private-key \"devcert/localhost.key\"\n :certificate \"devcert/localhost.crt\"}))\n\n", "end": 643, "score": 0.9644721150398254, "start": 622, "tag": "KEY", "value": "devcert/localhost.key" } ]
src/cljs-node/rx/node/devserver.cljs
zk/rx-lib
0
(ns ^:figwheel-no-load rx.node.devserver (:require [rx.kitchen-sink :as ks] [rx.anom :as anom] #_[macchiato.http :as http] #_[macchiato.server :as server] [clojure.string :as str] [cljs.nodejs :as nodejs] [clojure.core.async :refer [<! go]])) (nodejs/enable-util-print!) (defn on-global-error [e] (js/console.error e)) (defonce add-global-listener (.on js/process "uncaughtException" on-global-error)) (def default-config (merge {:server "127.0.0.1" :port 5000 :protocol :http} #_{:protocol :https :private-key "devcert/localhost.key" :certificate "devcert/localhost.crt"})) (defonce !server (atom nil)) (defn stop-server [] (when (:server-obj @!server) (.close (:server-obj @!server))) (reset! !server nil) (ks/pn "Stopped dev server")) (defn start [{:keys [handler <handler] :as config}] (stop-server) (let [config (merge default-config config)] (reset! !server {:config config :start-ts (ks/now) #_:server-obj #_(server/start (merge config {:handler (fn [req respond raise] (cond <handler (go (let [res (<! (<handler req))] (cond (ks/error? res) (raise res) (anom/? res) (raise res) :else (if-not (:status res) (raise "Missing :status in response map") (respond res))))) handler (handler req (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for response: " response)) (respond response)) (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for raise: " response)) (raise response))) :else (respond {:body (str "rx.node.devserver: handler not provided" "\n\n" (ks/pp-str @!server)) :status 500}))) :on-success (fn [& args] (ks/pn "Started dev server"))}))}))) (defn status [] @!server) (comment (status) (start {:port 8000}) )
36506
(ns ^:figwheel-no-load rx.node.devserver (:require [rx.kitchen-sink :as ks] [rx.anom :as anom] #_[macchiato.http :as http] #_[macchiato.server :as server] [clojure.string :as str] [cljs.nodejs :as nodejs] [clojure.core.async :refer [<! go]])) (nodejs/enable-util-print!) (defn on-global-error [e] (js/console.error e)) (defonce add-global-listener (.on js/process "uncaughtException" on-global-error)) (def default-config (merge {:server "127.0.0.1" :port 5000 :protocol :http} #_{:protocol :https :private-key "<KEY>" :certificate "devcert/localhost.crt"})) (defonce !server (atom nil)) (defn stop-server [] (when (:server-obj @!server) (.close (:server-obj @!server))) (reset! !server nil) (ks/pn "Stopped dev server")) (defn start [{:keys [handler <handler] :as config}] (stop-server) (let [config (merge default-config config)] (reset! !server {:config config :start-ts (ks/now) #_:server-obj #_(server/start (merge config {:handler (fn [req respond raise] (cond <handler (go (let [res (<! (<handler req))] (cond (ks/error? res) (raise res) (anom/? res) (raise res) :else (if-not (:status res) (raise "Missing :status in response map") (respond res))))) handler (handler req (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for response: " response)) (respond response)) (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for raise: " response)) (raise response))) :else (respond {:body (str "rx.node.devserver: handler not provided" "\n\n" (ks/pp-str @!server)) :status 500}))) :on-success (fn [& args] (ks/pn "Started dev server"))}))}))) (defn status [] @!server) (comment (status) (start {:port 8000}) )
true
(ns ^:figwheel-no-load rx.node.devserver (:require [rx.kitchen-sink :as ks] [rx.anom :as anom] #_[macchiato.http :as http] #_[macchiato.server :as server] [clojure.string :as str] [cljs.nodejs :as nodejs] [clojure.core.async :refer [<! go]])) (nodejs/enable-util-print!) (defn on-global-error [e] (js/console.error e)) (defonce add-global-listener (.on js/process "uncaughtException" on-global-error)) (def default-config (merge {:server "127.0.0.1" :port 5000 :protocol :http} #_{:protocol :https :private-key "PI:KEY:<KEY>END_PI" :certificate "devcert/localhost.crt"})) (defonce !server (atom nil)) (defn stop-server [] (when (:server-obj @!server) (.close (:server-obj @!server))) (reset! !server nil) (ks/pn "Stopped dev server")) (defn start [{:keys [handler <handler] :as config}] (stop-server) (let [config (merge default-config config)] (reset! !server {:config config :start-ts (ks/now) #_:server-obj #_(server/start (merge config {:handler (fn [req respond raise] (cond <handler (go (let [res (<! (<handler req))] (cond (ks/error? res) (raise res) (anom/? res) (raise res) :else (if-not (:status res) (raise "Missing :status in response map") (respond res))))) handler (handler req (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for response: " response)) (respond response)) (fn [response] (when (and (map? response) (not (:status response))) (ks/throw-str "Missing status for raise: " response)) (raise response))) :else (respond {:body (str "rx.node.devserver: handler not provided" "\n\n" (ks/pp-str @!server)) :status 500}))) :on-success (fn [& args] (ks/pn "Started dev server"))}))}))) (defn status [] @!server) (comment (status) (start {:port 8000}) )
[ { "context": "ented with \n <a href=\\\"https://github.com/palisades-lakes/faster-multimethods\\\">\n faster-multimetho", "end": 311, "score": 0.9974198937416077, "start": 296, "tag": "USERNAME", "value": "palisades-lakes" }, { "context": "\">\n faster-multimethods</a>.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-13\"}\n \n (:refer-clojure :", "end": 418, "score": 0.9720146059989929, "start": 382, "tag": "EMAIL", "value": "palisades dot lakes at gmail dot com" } ]
src/main/clojure/palisades/lakes/fm/map.clj
palisades-lakes/collection-experiments
0
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.fm.map {:doc "A generic, usually eager <code>map</code> function, implemented with <a href=\"https://github.com/palisades-lakes/faster-multimethods\"> faster-multimethods</a>." :author "palisades dot lakes at gmail dot com" :version "2017-12-13"} (:refer-clojure :exclude [map]) (:require [palisades.lakes.multimethods.core :as fm] [palisades.lakes.collex.arrays :as arrays] [palisades.lakes.fm.iterator :as iterator]) (:import [java.util ArrayList Collection Collections HashMap Iterator LinkedList Map Map$Entry] [clojure.lang IFn IFn$D IFn$L LazySeq IPersistentList IPersistentMap IPersistentVector Seqable] [com.google.common.collect ImmutableList])) ;;---------------------------------------------------------------- (fm/defmulti map "Create a new data structure with the same shape as <code>things0</code>, with each value <code>x0</code> replaced by <code>(f x0)</code> (or <code>(f x0 x1)</code>, etc., depending on the number of data structure arguments in the call to <code>map</code>." {:arglists '([^IFn f things0] [^IFn f things0 things1] [^IFn f things0 things1 things2] [^IFn f things0 things1 things2 things3])} ;; TODO: skip dispatching on (class f)? fm/signature) ;;---------------------------------------------------------------- (fm/defmethod map (fm/to-signature IFn Iterator) [^IFn f ^Iterator things] (let [a (ArrayList.)] (while (.hasNext things) (let [nxt (.next things)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Iterable) [^IFn f ^Iterable things] (map f (.iterator things))) (fm/defmethod map (fm/to-signature IFn Collection) [^IFn f ^Collection things] (let [a (ArrayList. (.size things)) it (.iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) ;; Note: requires f to be a function that takes 2 args. ;; Could use destructuring of Map$Entry ;; --- need to compare performance. (fm/defmethod map (fm/to-signature IFn Map) [^IFn f ^Map things] (let [m (HashMap. (.size things)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Object)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Iterable)) (fm/defmethod map (fm/to-signature IFn Seqable) [^IFn f ^Seqable things] (let [a (if (counted? things) (ArrayList. (count things)) (ArrayList.)) it (iterator/iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Seqable)) (fm/defmethod map (fm/to-signature IFn IPersistentMap) [^IFn f ^IPersistentMap things] (let [m (if (counted? things) (HashMap. (count things)) (HashMap.)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Map)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Seqable)) ;;---------------------------------------------------------------- ;; 3 args (fm/defmethod map (fm/to-signature IFn Iterator Iterator) [^IFn f ^Iterator things0 ^Iterator things1] (let [a (ArrayList.)] (while (and (.hasNext things0) (.hasNext things1)) (.add a (f (.next things0) (.next things1)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Object Object) [^IFn f ^Object things0 ^Object things1] (map f (iterator/iterator things0) (iterator/iterator things1))) (fm/defmethod map (fm/to-signature IFn Collection Collection) [^IFn f ^Collection things0 ^Collection things1] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1)] (while (and (.hasNext i0) (.hasNext i1)) (.add a (f (.next i0) (.next i1)))) (Collections/unmodifiableList a))) ;;---------------------------------------------------------------- ;; 4 args (fm/defmethod map (fm/to-signature IFn Object Object Object) [^IFn f ^Object things0 ^Object things1 ^Object things2] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Collection Collection Collection) [^IFn f ^Collection things0 ^Collection things1 ^Collection things2] (let [a (ArrayList. (min (.size things0) (.size things1) (.size things2))) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) ;;----------------------------------------------------------------
103594
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.fm.map {:doc "A generic, usually eager <code>map</code> function, implemented with <a href=\"https://github.com/palisades-lakes/faster-multimethods\"> faster-multimethods</a>." :author "<EMAIL>" :version "2017-12-13"} (:refer-clojure :exclude [map]) (:require [palisades.lakes.multimethods.core :as fm] [palisades.lakes.collex.arrays :as arrays] [palisades.lakes.fm.iterator :as iterator]) (:import [java.util ArrayList Collection Collections HashMap Iterator LinkedList Map Map$Entry] [clojure.lang IFn IFn$D IFn$L LazySeq IPersistentList IPersistentMap IPersistentVector Seqable] [com.google.common.collect ImmutableList])) ;;---------------------------------------------------------------- (fm/defmulti map "Create a new data structure with the same shape as <code>things0</code>, with each value <code>x0</code> replaced by <code>(f x0)</code> (or <code>(f x0 x1)</code>, etc., depending on the number of data structure arguments in the call to <code>map</code>." {:arglists '([^IFn f things0] [^IFn f things0 things1] [^IFn f things0 things1 things2] [^IFn f things0 things1 things2 things3])} ;; TODO: skip dispatching on (class f)? fm/signature) ;;---------------------------------------------------------------- (fm/defmethod map (fm/to-signature IFn Iterator) [^IFn f ^Iterator things] (let [a (ArrayList.)] (while (.hasNext things) (let [nxt (.next things)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Iterable) [^IFn f ^Iterable things] (map f (.iterator things))) (fm/defmethod map (fm/to-signature IFn Collection) [^IFn f ^Collection things] (let [a (ArrayList. (.size things)) it (.iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) ;; Note: requires f to be a function that takes 2 args. ;; Could use destructuring of Map$Entry ;; --- need to compare performance. (fm/defmethod map (fm/to-signature IFn Map) [^IFn f ^Map things] (let [m (HashMap. (.size things)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Object)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Iterable)) (fm/defmethod map (fm/to-signature IFn Seqable) [^IFn f ^Seqable things] (let [a (if (counted? things) (ArrayList. (count things)) (ArrayList.)) it (iterator/iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Seqable)) (fm/defmethod map (fm/to-signature IFn IPersistentMap) [^IFn f ^IPersistentMap things] (let [m (if (counted? things) (HashMap. (count things)) (HashMap.)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Map)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Seqable)) ;;---------------------------------------------------------------- ;; 3 args (fm/defmethod map (fm/to-signature IFn Iterator Iterator) [^IFn f ^Iterator things0 ^Iterator things1] (let [a (ArrayList.)] (while (and (.hasNext things0) (.hasNext things1)) (.add a (f (.next things0) (.next things1)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Object Object) [^IFn f ^Object things0 ^Object things1] (map f (iterator/iterator things0) (iterator/iterator things1))) (fm/defmethod map (fm/to-signature IFn Collection Collection) [^IFn f ^Collection things0 ^Collection things1] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1)] (while (and (.hasNext i0) (.hasNext i1)) (.add a (f (.next i0) (.next i1)))) (Collections/unmodifiableList a))) ;;---------------------------------------------------------------- ;; 4 args (fm/defmethod map (fm/to-signature IFn Object Object Object) [^IFn f ^Object things0 ^Object things1 ^Object things2] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Collection Collection Collection) [^IFn f ^Collection things0 ^Collection things1 ^Collection things2] (let [a (ArrayList. (min (.size things0) (.size things1) (.size things2))) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) ;;----------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) ;;---------------------------------------------------------------- (ns palisades.lakes.fm.map {:doc "A generic, usually eager <code>map</code> function, implemented with <a href=\"https://github.com/palisades-lakes/faster-multimethods\"> faster-multimethods</a>." :author "PI:EMAIL:<EMAIL>END_PI" :version "2017-12-13"} (:refer-clojure :exclude [map]) (:require [palisades.lakes.multimethods.core :as fm] [palisades.lakes.collex.arrays :as arrays] [palisades.lakes.fm.iterator :as iterator]) (:import [java.util ArrayList Collection Collections HashMap Iterator LinkedList Map Map$Entry] [clojure.lang IFn IFn$D IFn$L LazySeq IPersistentList IPersistentMap IPersistentVector Seqable] [com.google.common.collect ImmutableList])) ;;---------------------------------------------------------------- (fm/defmulti map "Create a new data structure with the same shape as <code>things0</code>, with each value <code>x0</code> replaced by <code>(f x0)</code> (or <code>(f x0 x1)</code>, etc., depending on the number of data structure arguments in the call to <code>map</code>." {:arglists '([^IFn f things0] [^IFn f things0 things1] [^IFn f things0 things1 things2] [^IFn f things0 things1 things2 things3])} ;; TODO: skip dispatching on (class f)? fm/signature) ;;---------------------------------------------------------------- (fm/defmethod map (fm/to-signature IFn Iterator) [^IFn f ^Iterator things] (let [a (ArrayList.)] (while (.hasNext things) (let [nxt (.next things)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Iterable) [^IFn f ^Iterable things] (map f (.iterator things))) (fm/defmethod map (fm/to-signature IFn Collection) [^IFn f ^Collection things] (let [a (ArrayList. (.size things)) it (.iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) ;; Note: requires f to be a function that takes 2 args. ;; Could use destructuring of Map$Entry ;; --- need to compare performance. (fm/defmethod map (fm/to-signature IFn Map) [^IFn f ^Map things] (let [m (HashMap. (.size things)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Object)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Iterable)) (fm/defmethod map (fm/to-signature IFn Seqable) [^IFn f ^Seqable things] (let [a (if (counted? things) (ArrayList. (count things)) (ArrayList.)) it (iterator/iterator things)] (while (.hasNext it) (let [nxt (.next it)] (.add a (f nxt)))) (Collections/unmodifiableList a))) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn Seqable) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn Map) (fm/to-signature IFn Seqable)) (fm/defmethod map (fm/to-signature IFn IPersistentMap) [^IFn f ^IPersistentMap things] (let [m (if (counted? things) (HashMap. (count things)) (HashMap.)) it (iterator/iterator things)] (while (.hasNext it) (let [^Map$Entry nxt (.next it) k (.getKey nxt) v0 (.getValue nxt) v1 (f k v0)] (.put m k v1))) (Collections/unmodifiableMap m))) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Collection)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Iterable)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Map)) (fm/prefer-method map (fm/to-signature IFn IPersistentMap) (fm/to-signature IFn Seqable)) ;;---------------------------------------------------------------- ;; 3 args (fm/defmethod map (fm/to-signature IFn Iterator Iterator) [^IFn f ^Iterator things0 ^Iterator things1] (let [a (ArrayList.)] (while (and (.hasNext things0) (.hasNext things1)) (.add a (f (.next things0) (.next things1)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Object Object) [^IFn f ^Object things0 ^Object things1] (map f (iterator/iterator things0) (iterator/iterator things1))) (fm/defmethod map (fm/to-signature IFn Collection Collection) [^IFn f ^Collection things0 ^Collection things1] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1)] (while (and (.hasNext i0) (.hasNext i1)) (.add a (f (.next i0) (.next i1)))) (Collections/unmodifiableList a))) ;;---------------------------------------------------------------- ;; 4 args (fm/defmethod map (fm/to-signature IFn Object Object Object) [^IFn f ^Object things0 ^Object things1 ^Object things2] (let [a (ArrayList.) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) (fm/defmethod map (fm/to-signature IFn Collection Collection Collection) [^IFn f ^Collection things0 ^Collection things1 ^Collection things2] (let [a (ArrayList. (min (.size things0) (.size things1) (.size things2))) i0 (iterator/iterator things0) i1 (iterator/iterator things1) i2 (iterator/iterator things2)] (while (and (.hasNext i0) (.hasNext i1) (.hasNext i2)) (.add a (f (.next i0) (.next i1) (.next i2)))) (Collections/unmodifiableList a))) ;;----------------------------------------------------------------
[ { "context": "st\"]\n [:table \"users\"]\n [:insert [{:name \"Anne\" :age 10 :pets [\"dog\" \"cat\"]}\n {:na", "end": 581, "score": 0.9996477365493774, "start": 577, "tag": "NAME", "value": "Anne" }, { "context": "ge 10 :pets [\"dog\" \"cat\"]}\n {:name \"Bob\" :age 12 :pets [\"dog\"]}\n {:name \"C", "end": 638, "score": 0.9998016953468323, "start": 635, "tag": "NAME", "value": "Bob" }, { "context": "b\" :age 12 :pets [\"dog\"]}\n {:name \"Chris\" :age 10}\n {:name \"Dave\" :age 11}\n ", "end": 692, "score": 0.9996728897094727, "start": 687, "tag": "NAME", "value": "Chris" }, { "context": " {:name \"Chris\" :age 10}\n {:name \"Dave\" :age 11}\n {:name \"Edgar\" :age 11 :", "end": 730, "score": 0.9996516704559326, "start": 726, "tag": "NAME", "value": "Dave" }, { "context": " {:name \"Dave\" :age 11}\n {:name \"Edgar\" :age 11 :school {:name \"Syndal\"}}\n ", "end": 769, "score": 0.9997283220291138, "start": 764, "tag": "NAME", "value": "Edgar" }, { "context": " :school {:name \"Syndal\"}}\n {:name \"Frank\" :age 10}\n {:name \"Greg\" :age 10}\n ", "end": 833, "score": 0.999666690826416, "start": 828, "tag": "NAME", "value": "Frank" }, { "context": " {:name \"Frank\" :age 10}\n {:name \"Greg\" :age 10}\n {:name \"Harry\" :age 13}\n", "end": 871, "score": 0.9997705221176147, "start": 867, "tag": "NAME", "value": "Greg" }, { "context": " {:name \"Greg\" :age 10}\n {:name \"Harry\" :age 13}\n {:name \"Indy\" :age 10}\n ", "end": 910, "score": 0.9997669458389282, "start": 905, "tag": "NAME", "value": "Harry" }, { "context": " {:name \"Harry\" :age 13}\n {:name \"Indy\" :age 10}\n {:name \"Jact\" :age 12}]]", "end": 948, "score": 0.9997361302375793, "start": 944, "tag": "NAME", "value": "Indy" }, { "context": " {:name \"Indy\" :age 10}\n {:name \"Jact\" :age 12}]]])\n\n (-> (run [conn]\n [[:db \"t", "end": 986, "score": 0.9998141527175903, "start": 982, "tag": "NAME", "value": "Jact" }, { "context": " [:pluck [\"name\"]]])\n seq)\n => [{\"name\" \"Harry\"}]\n\n (-> (run [conn]\n [[:db \"test\"]\n ", "end": 1157, "score": 0.9997762441635132, "start": 1152, "tag": "NAME", "value": "Harry" }, { "context": ":table \"users\"]\n [:filter {:age 10 :name \"Harry\"}]])\n seq)\n => nil\n\n (-> (run [conn]\n ", "end": 1267, "score": 0.9997892379760742, "start": 1262, "tag": "NAME", "value": "Harry" }, { "context": " [:filter\n [:and {:age 10} {:name \"Harry\"}]]\n [:pluck [\"name\"]]])\n seq)\n\n (-", "end": 1417, "score": 0.999793291091919, "start": 1412, "tag": "NAME", "value": "Harry" }, { "context": "e \"users\"]\n [:filter '(fn [x] (== x.name \"Chris\"))]])\n seq)\n\n (-> (run [conn]\n [[:db", "end": 1573, "score": 0.9997019171714783, "start": 1568, "tag": "NAME", "value": "Chris" }, { "context": " [:table \"users\"]\n [:map '(fn [x] (== \"Chris\" (.getField x \"name\")))]])\n seq)\n\n (-> (run", "end": 1692, "score": 0.9996472597122192, "start": 1687, "tag": "NAME", "value": "Chris" }, { "context": " seq)\n\n (js/js '(fn [x] (-> x .-name .-help (= \"Chris\"))))\n\n (-> (run [conn]\n [[:db \"test\"]\n ", "end": 1892, "score": 0.8960028886795044, "start": 1887, "tag": "NAME", "value": "Chris" }, { "context": "lter [:javascript \"(function(x){return x.name == 'Chris'})\"]]])\n seq)\n\n (-> (run [conn]\n [[:", "end": 2033, "score": 0.9995695352554321, "start": 2028, "tag": "NAME", "value": "Chris" }, { "context": "]\n [:filter #(-> % (.getField \"name\") (= \"Chris\"))]])\n seq)\n\n (-> (run [conn]\n [[:db", "end": 2173, "score": 0.9994125962257385, "start": 2168, "tag": "NAME", "value": "Chris" }, { "context": "\n [:table \"users\"]\n [:get {:name \"Anne\"}]\n [:get-field \"pets\"]\n [:nth 1]", "end": 3088, "score": 0.999783992767334, "start": 3084, "tag": "NAME", "value": "Anne" }, { "context": " (Javascript. \"(function(x){return x.name == 'Chris'})\"))\n (.run conn)\n seq)\n #_ #_(.run c", "end": 3323, "score": 0.9997727870941162, "start": 3318, "tag": "NAME", "value": "Chris" }, { "context": " [:order-by \"age\" \"name\"\n ;[:eq \"Chris\"]\n ]])\n seq)\n\n (run [conn]\n [:j", "end": 3500, "score": 0.999546229839325, "start": 3495, "tag": "NAME", "value": "Chris" }, { "context": "\n [:javascript \"(function(x){return x.name == 'Chris'})(1)\"])\n\n (lambda )\n\n\n (compile/to-ast [:row \"", "end": 3597, "score": 0.9996908903121948, "start": 3592, "tag": "NAME", "value": "Chris" }, { "context": "table \"authors\"]\n [:insert [{:name \"E.L. James\"\n :genre \"crap\"\n ", "end": 4056, "score": 0.9998830556869507, "start": 4046, "tag": "NAME", "value": "E.L. James" }, { "context": "adult\" \"spicy\"]}\n {:name \"Stephenie Meyer\"\n :genre \"crap\"\n ", "end": 4416, "score": 0.9998598694801331, "start": 4401, "tag": "NAME", "value": "Stephenie Meyer" } ]
test/one/love/scratch_test.clj
zcaudate/poha
33
(ns one.love.scratch-test (:use midje.sweet) (:require [one.love.raw.connection :as conn] [one.love.command :as commmand] [one.love.command.js :as js] [one.love.common :as one]) (:import com.rethinkdb.gen.ast.Funcall com.rethinkdb.gen.ast.Javascript)) (def conn (conn/connect conn/+defaults+)) (comment (run [conn] [:db-drop "test"]) (run [conn] [:db-create "test"]) (run [conn] [[:db "test"] [:table-create "users"]]) (run [conn] [[:db "test"] [:table "users"] [:insert [{:name "Anne" :age 10 :pets ["dog" "cat"]} {:name "Bob" :age 12 :pets ["dog"]} {:name "Chris" :age 10} {:name "Dave" :age 11} {:name "Edgar" :age 11 :school {:name "Syndal"}} {:name "Frank" :age 10} {:name "Greg" :age 10} {:name "Harry" :age 13} {:name "Indy" :age 10} {:name "Jact" :age 12}]]]) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 13}] [:pluck ["name"]]]) seq) => [{"name" "Harry"}] (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 10 :name "Harry"}]]) seq) => nil (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:and {:age 10} {:name "Harry"}]] [:pluck ["name"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter '(fn [x] (== x.name "Chris"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] (== "Chris" (.getField x "name")))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] x.name)]]) seq) (js/js '(fn [x] (-> x .-name .-help (= "Chris")))) (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:javascript "(function(x){return x.name == 'Chris'})"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter #(-> % (.getField "name") (= "Chris"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:school {:name "Syndal"}}]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:changes]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:bracket "pets"]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"] [:nth 1]]) ) (-> (run [conn] [[:db "test"] [:table "users"] [:get {:name "Anne"}] [:get-field "pets"] [:nth 1]])) (-> one/r (.table "users") (.getAll (to-array [])) (.run conn)) (-> one/r (.table "users") (.filter (Javascript. "(function(x){return x.name == 'Chris'})")) (.run conn) seq) #_ #_(.run conn) (-> (run [conn] [[:db "test"] [:table "users"] [:order-by "age" "name" ;[:eq "Chris"] ]]) seq) (run [conn] [:javascript "(function(x){return x.name == 'Chris'})(1)"]) (lambda ) (compile/to-ast [:row "names"]) (-> one/r (.row (to-array ["table"]))) ) (comment (run [conn] [:le 1 2 3]) (run [conn] [[:db "test"] [:table-create "test"]]) (run [conn] [:db "test"]) (run [conn] [[:db "test"] [:table "test"] [:insert {:data "hello world"}]]) (run [conn] [[:db "test"] [:table "authors"] [:insert [{:name "E.L. James" :genre "crap" :country "UK" :books ["Fifty Shades of Grey" "Fifty Shades Darker" "Fifty Shades Freed"] :tags ["serious" "adult" "spicy"]} {:name "Stephenie Meyer" :genre "crap" :country "USA" :books ["Twilight" "New Moon" "Eclipse" "Breaking Dawn"] :tags ["weird" "serious"]}]]]) (run [conn "test" "authors"] [:delete]) )
112944
(ns one.love.scratch-test (:use midje.sweet) (:require [one.love.raw.connection :as conn] [one.love.command :as commmand] [one.love.command.js :as js] [one.love.common :as one]) (:import com.rethinkdb.gen.ast.Funcall com.rethinkdb.gen.ast.Javascript)) (def conn (conn/connect conn/+defaults+)) (comment (run [conn] [:db-drop "test"]) (run [conn] [:db-create "test"]) (run [conn] [[:db "test"] [:table-create "users"]]) (run [conn] [[:db "test"] [:table "users"] [:insert [{:name "<NAME>" :age 10 :pets ["dog" "cat"]} {:name "<NAME>" :age 12 :pets ["dog"]} {:name "<NAME>" :age 10} {:name "<NAME>" :age 11} {:name "<NAME>" :age 11 :school {:name "Syndal"}} {:name "<NAME>" :age 10} {:name "<NAME>" :age 10} {:name "<NAME>" :age 13} {:name "<NAME>" :age 10} {:name "<NAME>" :age 12}]]]) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 13}] [:pluck ["name"]]]) seq) => [{"name" "<NAME>"}] (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 10 :name "<NAME>"}]]) seq) => nil (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:and {:age 10} {:name "<NAME>"}]] [:pluck ["name"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter '(fn [x] (== x.name "<NAME>"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] (== "<NAME>" (.getField x "name")))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] x.name)]]) seq) (js/js '(fn [x] (-> x .-name .-help (= "<NAME>")))) (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:javascript "(function(x){return x.name == '<NAME>'})"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter #(-> % (.getField "name") (= "<NAME>"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:school {:name "Syndal"}}]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:changes]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:bracket "pets"]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"] [:nth 1]]) ) (-> (run [conn] [[:db "test"] [:table "users"] [:get {:name "<NAME>"}] [:get-field "pets"] [:nth 1]])) (-> one/r (.table "users") (.getAll (to-array [])) (.run conn)) (-> one/r (.table "users") (.filter (Javascript. "(function(x){return x.name == '<NAME>'})")) (.run conn) seq) #_ #_(.run conn) (-> (run [conn] [[:db "test"] [:table "users"] [:order-by "age" "name" ;[:eq "<NAME>"] ]]) seq) (run [conn] [:javascript "(function(x){return x.name == '<NAME>'})(1)"]) (lambda ) (compile/to-ast [:row "names"]) (-> one/r (.row (to-array ["table"]))) ) (comment (run [conn] [:le 1 2 3]) (run [conn] [[:db "test"] [:table-create "test"]]) (run [conn] [:db "test"]) (run [conn] [[:db "test"] [:table "test"] [:insert {:data "hello world"}]]) (run [conn] [[:db "test"] [:table "authors"] [:insert [{:name "<NAME>" :genre "crap" :country "UK" :books ["Fifty Shades of Grey" "Fifty Shades Darker" "Fifty Shades Freed"] :tags ["serious" "adult" "spicy"]} {:name "<NAME>" :genre "crap" :country "USA" :books ["Twilight" "New Moon" "Eclipse" "Breaking Dawn"] :tags ["weird" "serious"]}]]]) (run [conn "test" "authors"] [:delete]) )
true
(ns one.love.scratch-test (:use midje.sweet) (:require [one.love.raw.connection :as conn] [one.love.command :as commmand] [one.love.command.js :as js] [one.love.common :as one]) (:import com.rethinkdb.gen.ast.Funcall com.rethinkdb.gen.ast.Javascript)) (def conn (conn/connect conn/+defaults+)) (comment (run [conn] [:db-drop "test"]) (run [conn] [:db-create "test"]) (run [conn] [[:db "test"] [:table-create "users"]]) (run [conn] [[:db "test"] [:table "users"] [:insert [{:name "PI:NAME:<NAME>END_PI" :age 10 :pets ["dog" "cat"]} {:name "PI:NAME:<NAME>END_PI" :age 12 :pets ["dog"]} {:name "PI:NAME:<NAME>END_PI" :age 10} {:name "PI:NAME:<NAME>END_PI" :age 11} {:name "PI:NAME:<NAME>END_PI" :age 11 :school {:name "Syndal"}} {:name "PI:NAME:<NAME>END_PI" :age 10} {:name "PI:NAME:<NAME>END_PI" :age 10} {:name "PI:NAME:<NAME>END_PI" :age 13} {:name "PI:NAME:<NAME>END_PI" :age 10} {:name "PI:NAME:<NAME>END_PI" :age 12}]]]) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 13}] [:pluck ["name"]]]) seq) => [{"name" "PI:NAME:<NAME>END_PI"}] (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:age 10 :name "PI:NAME:<NAME>END_PI"}]]) seq) => nil (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:and {:age 10} {:name "PI:NAME:<NAME>END_PI"}]] [:pluck ["name"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter '(fn [x] (== x.name "PI:NAME:<NAME>END_PI"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] (== "PI:NAME:<NAME>END_PI" (.getField x "name")))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:map '(fn [x] x.name)]]) seq) (js/js '(fn [x] (-> x .-name .-help (= "PI:NAME:<NAME>END_PI")))) (-> (run [conn] [[:db "test"] [:table "users"] [:filter [:javascript "(function(x){return x.name == 'PI:NAME:<NAME>END_PI'})"]]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter #(-> % (.getField "name") (= "PI:NAME:<NAME>END_PI"))]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:filter {:school {:name "Syndal"}}]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"]]) seq) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:changes]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:bracket "pets"]]) ;;seq ) (-> (run [conn] [[:db "test"] [:table "users"] [:get "39a85584-4245-4997-8695-6f012d17b865"] [:get-field "pets"] [:nth 1]]) ) (-> (run [conn] [[:db "test"] [:table "users"] [:get {:name "PI:NAME:<NAME>END_PI"}] [:get-field "pets"] [:nth 1]])) (-> one/r (.table "users") (.getAll (to-array [])) (.run conn)) (-> one/r (.table "users") (.filter (Javascript. "(function(x){return x.name == 'PI:NAME:<NAME>END_PI'})")) (.run conn) seq) #_ #_(.run conn) (-> (run [conn] [[:db "test"] [:table "users"] [:order-by "age" "name" ;[:eq "PI:NAME:<NAME>END_PI"] ]]) seq) (run [conn] [:javascript "(function(x){return x.name == 'PI:NAME:<NAME>END_PI'})(1)"]) (lambda ) (compile/to-ast [:row "names"]) (-> one/r (.row (to-array ["table"]))) ) (comment (run [conn] [:le 1 2 3]) (run [conn] [[:db "test"] [:table-create "test"]]) (run [conn] [:db "test"]) (run [conn] [[:db "test"] [:table "test"] [:insert {:data "hello world"}]]) (run [conn] [[:db "test"] [:table "authors"] [:insert [{:name "PI:NAME:<NAME>END_PI" :genre "crap" :country "UK" :books ["Fifty Shades of Grey" "Fifty Shades Darker" "Fifty Shades Freed"] :tags ["serious" "adult" "spicy"]} {:name "PI:NAME:<NAME>END_PI" :genre "crap" :country "USA" :books ["Twilight" "New Moon" "Eclipse" "Breaking Dawn"] :tags ["weird" "serious"]}]]]) (run [conn "test" "authors"] [:delete]) )
[ { "context": ";;\n;;\n;; Copyright 2014 Milinda Pathirage<milinda.pathirage@gmail.com>\n;;\n;; Licensed u", "end": 42, "score": 0.9998922348022461, "start": 25, "tag": "NAME", "value": "Milinda Pathirage" }, { "context": ";;\n;;\n;; Copyright 2014 Milinda Pathirage<milinda.pathirage@gmail.com>\n;;\n;; Licensed under the Apache License, Ver", "end": 70, "score": 0.9999293088912964, "start": 43, "tag": "EMAIL", "value": "milinda.pathirage@gmail.com" } ]
kappaql-core/src/clojure/org/pathirage/kappaql/core.clj
milinda/KappaQL
0
;; ;; ;; Copyright 2014 Milinda Pathirage<milinda.pathirage@gmail.com> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns org.pathirage.kappaql.core) (comment "Defining streams" (defstream stream (fields [:name :string :address :string :age :integer :timestamp :long]) (pk :id) (ts :timestamp)) "Querying" (select stream (fields [:name :firstname] :address :age) (window (range 30)) (where {:age (less-than 34)})) "Relation Algebric Expression" (def query {:stream stock-ticks :project [name, xx] :select condition}) (def condition [:less-than :field-name value]) (def complex-condition [:and [:less-than :field-name value] [:equal :field-name value]])) (defmacro defstream "Define a stream representing a topic in Kafka, applying functions in the body which changes the stream definition." [stream & body]) (defmacro select "Build a select query, apply any modifiers specified in the body and then generate and submit DAG of Samza jobs which is the physical execution plan of the continuous query on stream specified by `stream`. `stream` is an stream created by `defstream`. Returns a job identifier which can used to monitor the query or error incase of a failure." [stream & body]) (defmacro do-until [& clauses] (when clauses (list 'clojure.core/when (first clauses) (if (next clauses) (second clauses) (throw (IllegalArgumentException. "do-until requires even number of forms."))) (cons 'do-until (nnext clauses))))) (defmacro unless [condition & body] `(if (not ~condition) (do ~@body))) (declare handle-things) (defmacro domain [name & body] `{:tag :domain :attrs {:name (str '~name)} :content [~@body]}) (defmacro grouping [name & body] `{:tag :grouping :attrs {:name (str '~name)} :content [~@(handle-things body)]}) (declare grok-attr grok-props) (defn handle-things [things] (for [t things] {:tag :thing :attr (grok-attrs (take-while (comp not vector?) t)) :content (if-let [c (grok-props (drop-while (comp not vector?) t))] [c] [])})) (defn grok-attrs [attrs] (into {:name (str (first attrs))} (for [a (rest attrs)] (cond (list? a) [:isa (str (second a))] (string? a) [:comment a])))) (defn grok-props [props] (when props {:tag :properties, :attrs nil, :content (apply vector (for [p props] {:tag :property, :attrs {:name (str (first p))}, :content nil}))}))
104962
;; ;; ;; Copyright 2014 <NAME><<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns org.pathirage.kappaql.core) (comment "Defining streams" (defstream stream (fields [:name :string :address :string :age :integer :timestamp :long]) (pk :id) (ts :timestamp)) "Querying" (select stream (fields [:name :firstname] :address :age) (window (range 30)) (where {:age (less-than 34)})) "Relation Algebric Expression" (def query {:stream stock-ticks :project [name, xx] :select condition}) (def condition [:less-than :field-name value]) (def complex-condition [:and [:less-than :field-name value] [:equal :field-name value]])) (defmacro defstream "Define a stream representing a topic in Kafka, applying functions in the body which changes the stream definition." [stream & body]) (defmacro select "Build a select query, apply any modifiers specified in the body and then generate and submit DAG of Samza jobs which is the physical execution plan of the continuous query on stream specified by `stream`. `stream` is an stream created by `defstream`. Returns a job identifier which can used to monitor the query or error incase of a failure." [stream & body]) (defmacro do-until [& clauses] (when clauses (list 'clojure.core/when (first clauses) (if (next clauses) (second clauses) (throw (IllegalArgumentException. "do-until requires even number of forms."))) (cons 'do-until (nnext clauses))))) (defmacro unless [condition & body] `(if (not ~condition) (do ~@body))) (declare handle-things) (defmacro domain [name & body] `{:tag :domain :attrs {:name (str '~name)} :content [~@body]}) (defmacro grouping [name & body] `{:tag :grouping :attrs {:name (str '~name)} :content [~@(handle-things body)]}) (declare grok-attr grok-props) (defn handle-things [things] (for [t things] {:tag :thing :attr (grok-attrs (take-while (comp not vector?) t)) :content (if-let [c (grok-props (drop-while (comp not vector?) t))] [c] [])})) (defn grok-attrs [attrs] (into {:name (str (first attrs))} (for [a (rest attrs)] (cond (list? a) [:isa (str (second a))] (string? a) [:comment a])))) (defn grok-props [props] (when props {:tag :properties, :attrs nil, :content (apply vector (for [p props] {:tag :property, :attrs {:name (str (first p))}, :content nil}))}))
true
;; ;; ;; Copyright 2014 PI:NAME:<NAME>END_PI<PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; ;; (ns org.pathirage.kappaql.core) (comment "Defining streams" (defstream stream (fields [:name :string :address :string :age :integer :timestamp :long]) (pk :id) (ts :timestamp)) "Querying" (select stream (fields [:name :firstname] :address :age) (window (range 30)) (where {:age (less-than 34)})) "Relation Algebric Expression" (def query {:stream stock-ticks :project [name, xx] :select condition}) (def condition [:less-than :field-name value]) (def complex-condition [:and [:less-than :field-name value] [:equal :field-name value]])) (defmacro defstream "Define a stream representing a topic in Kafka, applying functions in the body which changes the stream definition." [stream & body]) (defmacro select "Build a select query, apply any modifiers specified in the body and then generate and submit DAG of Samza jobs which is the physical execution plan of the continuous query on stream specified by `stream`. `stream` is an stream created by `defstream`. Returns a job identifier which can used to monitor the query or error incase of a failure." [stream & body]) (defmacro do-until [& clauses] (when clauses (list 'clojure.core/when (first clauses) (if (next clauses) (second clauses) (throw (IllegalArgumentException. "do-until requires even number of forms."))) (cons 'do-until (nnext clauses))))) (defmacro unless [condition & body] `(if (not ~condition) (do ~@body))) (declare handle-things) (defmacro domain [name & body] `{:tag :domain :attrs {:name (str '~name)} :content [~@body]}) (defmacro grouping [name & body] `{:tag :grouping :attrs {:name (str '~name)} :content [~@(handle-things body)]}) (declare grok-attr grok-props) (defn handle-things [things] (for [t things] {:tag :thing :attr (grok-attrs (take-while (comp not vector?) t)) :content (if-let [c (grok-props (drop-while (comp not vector?) t))] [c] [])})) (defn grok-attrs [attrs] (into {:name (str (first attrs))} (for [a (rest attrs)] (cond (list? a) [:isa (str (second a))] (string? a) [:comment a])))) (defn grok-props [props] (when props {:tag :properties, :attrs nil, :content (apply vector (for [p props] {:tag :property, :attrs {:name (str (first p))}, :content nil}))}))
[ { "context": " (merge s r))))))\n\n(def s '({:age 27 :name \"Jonah\"}\n {:age 18 :name \"Alan\"}\n {:age ", "end": 209, "score": 0.999825119972229, "start": 204, "tag": "NAME", "value": "Jonah" }, { "context": "({:age 27 :name \"Jonah\"}\n {:age 18 :name \"Alan\"}\n {:age 28 :name \"Glory\"}\n {:age", "end": 241, "score": 0.9998140335083008, "start": 237, "tag": "NAME", "value": "Alan" }, { "context": " {:age 18 :name \"Alan\"}\n {:age 28 :name \"Glory\"}\n {:age 18 :name \"Popeye\"}\n {:ag", "end": 274, "score": 0.9998002052307129, "start": 269, "tag": "NAME", "value": "Glory" }, { "context": " {:age 28 :name \"Glory\"}\n {:age 18 :name \"Popeye\"}\n {:age 28 :name \"Alan\"}))\n\n(def r '({:n", "end": 308, "score": 0.9995582103729248, "start": 302, "tag": "NAME", "value": "Popeye" }, { "context": "{:age 18 :name \"Popeye\"}\n {:age 28 :name \"Alan\"}))\n\n(def r '({:nemesis \"Whales\" :name \"Jonah\"}\n ", "end": 340, "score": 0.9998136758804321, "start": 336, "tag": "NAME", "value": "Alan" }, { "context": "ame \"Alan\"}))\n\n(def r '({:nemesis \"Whales\" :name \"Jonah\"}\n {:nemesis \"Spiders\" :name \"Jonah\"}\n ", "end": 386, "score": 0.9997765421867371, "start": 381, "tag": "NAME", "value": "Jonah" }, { "context": "name \"Jonah\"}\n {:nemesis \"Spiders\" :name \"Jonah\"}\n {:nemesis \"Ghosts\" :name \"Alan\"}\n ", "end": 430, "score": 0.9997997879981995, "start": 425, "tag": "NAME", "value": "Jonah" }, { "context": ":name \"Jonah\"}\n {:nemesis \"Ghosts\" :name \"Alan\"}\n {:nemesis \"Zombies\" :name \"Alan\"}\n ", "end": 472, "score": 0.99981290102005, "start": 468, "tag": "NAME", "value": "Alan" }, { "context": "emesis \"Ghosts\" :name \"Alan\"}\n {:nemesis \"Zombies\" :name \"Alan\"}\n {:nemesis \"Buffy\" :name \"", "end": 502, "score": 0.9931594729423523, "start": 495, "tag": "NAME", "value": "Zombies" }, { "context": ":name \"Alan\"}\n {:nemesis \"Zombies\" :name \"Alan\"}\n {:nemesis \"Buffy\" :name \"Glory\"}))\n\n(p", "end": 515, "score": 0.9997872710227966, "start": 511, "tag": "NAME", "value": "Alan" }, { "context": "mesis \"Zombies\" :name \"Alan\"}\n {:nemesis \"Buffy\" :name \"Glory\"}))\n\n(pprint (sort-by :name (hash-j", "end": 543, "score": 0.9990749359130859, "start": 538, "tag": "NAME", "value": "Buffy" }, { "context": "\" :name \"Alan\"}\n {:nemesis \"Buffy\" :name \"Glory\"}))\n\n(pprint (sort-by :name (hash-join s :name r ", "end": 557, "score": 0.9997106790542603, "start": 552, "tag": "NAME", "value": "Glory" } ]
Task/Hash-join/Clojure/hash-join.clj
LaudateCorpus1/RosettaCodeData
1
(defn hash-join [table1 col1 table2 col2] (let [hashed (group-by col1 table1)] (flatten (for [r table2] (for [s (hashed (col2 r))] (merge s r)))))) (def s '({:age 27 :name "Jonah"} {:age 18 :name "Alan"} {:age 28 :name "Glory"} {:age 18 :name "Popeye"} {:age 28 :name "Alan"})) (def r '({:nemesis "Whales" :name "Jonah"} {:nemesis "Spiders" :name "Jonah"} {:nemesis "Ghosts" :name "Alan"} {:nemesis "Zombies" :name "Alan"} {:nemesis "Buffy" :name "Glory"})) (pprint (sort-by :name (hash-join s :name r :name)))
116255
(defn hash-join [table1 col1 table2 col2] (let [hashed (group-by col1 table1)] (flatten (for [r table2] (for [s (hashed (col2 r))] (merge s r)))))) (def s '({:age 27 :name "<NAME>"} {:age 18 :name "<NAME>"} {:age 28 :name "<NAME>"} {:age 18 :name "<NAME>"} {:age 28 :name "<NAME>"})) (def r '({:nemesis "Whales" :name "<NAME>"} {:nemesis "Spiders" :name "<NAME>"} {:nemesis "Ghosts" :name "<NAME>"} {:nemesis "<NAME>" :name "<NAME>"} {:nemesis "<NAME>" :name "<NAME>"})) (pprint (sort-by :name (hash-join s :name r :name)))
true
(defn hash-join [table1 col1 table2 col2] (let [hashed (group-by col1 table1)] (flatten (for [r table2] (for [s (hashed (col2 r))] (merge s r)))))) (def s '({:age 27 :name "PI:NAME:<NAME>END_PI"} {:age 18 :name "PI:NAME:<NAME>END_PI"} {:age 28 :name "PI:NAME:<NAME>END_PI"} {:age 18 :name "PI:NAME:<NAME>END_PI"} {:age 28 :name "PI:NAME:<NAME>END_PI"})) (def r '({:nemesis "Whales" :name "PI:NAME:<NAME>END_PI"} {:nemesis "Spiders" :name "PI:NAME:<NAME>END_PI"} {:nemesis "Ghosts" :name "PI:NAME:<NAME>END_PI"} {:nemesis "PI:NAME:<NAME>END_PI" :name "PI:NAME:<NAME>END_PI"} {:nemesis "PI:NAME:<NAME>END_PI" :name "PI:NAME:<NAME>END_PI"})) (pprint (sort-by :name (hash-join s :name r :name)))
[ { "context": "; The MIT License (MIT)\n;\n; Copyright (c) 2013 Zachary Tellman\n;\n; Permission is hereby granted, free of charge,", "end": 63, "score": 0.99951171875, "start": 48, "tag": "NAME", "value": "Zachary Tellman" }, { "context": "tware.)\n;\n; Partly Copied from https://github.com/ztellman/potemkin/blob/master/src/potemkin/util.clj\n; to a", "end": 695, "score": 0.9518178105354309, "start": 687, "tag": "USERNAME", "value": "ztellman" } ]
src/java_time/potemkin/util.clj
bevuta/clojure.java-time
0
; The MIT License (MIT) ; ; Copyright (c) 2013 Zachary Tellman ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software.) ; ; Partly Copied from https://github.com/ztellman/potemkin/blob/master/src/potemkin/util.clj ; to avoid having a dependency (ns java-time.potemkin.util (:import [java.util.concurrent ConcurrentHashMap])) ;;; fast-memoize (definline re-nil [x] `(let [x# ~x] (if (identical? ::nil x#) nil x#))) (definline de-nil [x] `(let [x# ~x] (if (nil? x#) ::nil x#))) (defmacro memoize-form [m f & args] `(let [k# (vector ~@args)] (let [v# (.get ~m k#)] (if-not (nil? v#) (re-nil v#) (let [v# (de-nil (~f ~@args))] (re-nil (or (.putIfAbsent ~m k# v#) v#))))))) (defn fast-memoize "A version of `memoize` which has equivalent behavior, but is faster." [f] (let [m (ConcurrentHashMap.)] (fn ([] (memoize-form m f)) ([x] (memoize-form m f x)) ([x y] (memoize-form m f x y)) ([x y z] (memoize-form m f x y z)) ([x y z w] (memoize-form m f x y z w)) ([x y z w u] (memoize-form m f x y z w u)) ([x y z w u v] (memoize-form m f x y z w u v)) ([x y z w u v & rest] (let [k (list* x y z w u v rest)] (let [v (.get ^ConcurrentHashMap m k)] (if-not (nil? v) (re-nil v) (let [v (de-nil (apply f k))] (or (.putIfAbsent m k v) v))))))))) (defmacro doit "A version of doseq that doesn't emit all that inline-destroying chunked-seq code." [[x it] & body] (let [it-sym (gensym "iterable")] `(let [~it-sym ~it it# (.iterator ~(with-meta it-sym {:tag "Iterable"}))] (loop [] (when (.hasNext it#) (let [~x (.next it#)] ~@body) (recur))))))
112617
; The MIT License (MIT) ; ; Copyright (c) 2013 <NAME> ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software.) ; ; Partly Copied from https://github.com/ztellman/potemkin/blob/master/src/potemkin/util.clj ; to avoid having a dependency (ns java-time.potemkin.util (:import [java.util.concurrent ConcurrentHashMap])) ;;; fast-memoize (definline re-nil [x] `(let [x# ~x] (if (identical? ::nil x#) nil x#))) (definline de-nil [x] `(let [x# ~x] (if (nil? x#) ::nil x#))) (defmacro memoize-form [m f & args] `(let [k# (vector ~@args)] (let [v# (.get ~m k#)] (if-not (nil? v#) (re-nil v#) (let [v# (de-nil (~f ~@args))] (re-nil (or (.putIfAbsent ~m k# v#) v#))))))) (defn fast-memoize "A version of `memoize` which has equivalent behavior, but is faster." [f] (let [m (ConcurrentHashMap.)] (fn ([] (memoize-form m f)) ([x] (memoize-form m f x)) ([x y] (memoize-form m f x y)) ([x y z] (memoize-form m f x y z)) ([x y z w] (memoize-form m f x y z w)) ([x y z w u] (memoize-form m f x y z w u)) ([x y z w u v] (memoize-form m f x y z w u v)) ([x y z w u v & rest] (let [k (list* x y z w u v rest)] (let [v (.get ^ConcurrentHashMap m k)] (if-not (nil? v) (re-nil v) (let [v (de-nil (apply f k))] (or (.putIfAbsent m k v) v))))))))) (defmacro doit "A version of doseq that doesn't emit all that inline-destroying chunked-seq code." [[x it] & body] (let [it-sym (gensym "iterable")] `(let [~it-sym ~it it# (.iterator ~(with-meta it-sym {:tag "Iterable"}))] (loop [] (when (.hasNext it#) (let [~x (.next it#)] ~@body) (recur))))))
true
; The MIT License (MIT) ; ; Copyright (c) 2013 PI:NAME:<NAME>END_PI ; ; Permission is hereby granted, free of charge, to any person obtaining a copy ; of this software and associated documentation files (the "Software"), to deal ; in the Software without restriction, including without limitation the rights ; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ; copies of the Software, and to permit persons to whom the Software is ; furnished to do so, subject to the following conditions: ; ; The above copyright notice and this permission notice shall be included in ; all copies or substantial portions of the Software.) ; ; Partly Copied from https://github.com/ztellman/potemkin/blob/master/src/potemkin/util.clj ; to avoid having a dependency (ns java-time.potemkin.util (:import [java.util.concurrent ConcurrentHashMap])) ;;; fast-memoize (definline re-nil [x] `(let [x# ~x] (if (identical? ::nil x#) nil x#))) (definline de-nil [x] `(let [x# ~x] (if (nil? x#) ::nil x#))) (defmacro memoize-form [m f & args] `(let [k# (vector ~@args)] (let [v# (.get ~m k#)] (if-not (nil? v#) (re-nil v#) (let [v# (de-nil (~f ~@args))] (re-nil (or (.putIfAbsent ~m k# v#) v#))))))) (defn fast-memoize "A version of `memoize` which has equivalent behavior, but is faster." [f] (let [m (ConcurrentHashMap.)] (fn ([] (memoize-form m f)) ([x] (memoize-form m f x)) ([x y] (memoize-form m f x y)) ([x y z] (memoize-form m f x y z)) ([x y z w] (memoize-form m f x y z w)) ([x y z w u] (memoize-form m f x y z w u)) ([x y z w u v] (memoize-form m f x y z w u v)) ([x y z w u v & rest] (let [k (list* x y z w u v rest)] (let [v (.get ^ConcurrentHashMap m k)] (if-not (nil? v) (re-nil v) (let [v (de-nil (apply f k))] (or (.putIfAbsent m k v) v))))))))) (defmacro doit "A version of doseq that doesn't emit all that inline-destroying chunked-seq code." [[x it] & body] (let [it-sym (gensym "iterable")] `(let [~it-sym ~it it# (.iterator ~(with-meta it-sym {:tag "Iterable"}))] (loop [] (when (.hasNext it#) (let [~x (.next it#)] ~@body) (recur))))))
[ { "context": "2}\n :personae [{:name \"rgregerg\",\n :object", "end": 4837, "score": 0.9886379241943359, "start": 4829, "tag": "USERNAME", "value": "rgregerg" }, { "context": " :member [{:name \"rolf\",\n ", "end": 4962, "score": 0.9469367265701294, "start": 4958, "tag": "USERNAME", "value": "rolf" }, { "context": " :mbox \"mailto:rolf@example.org\"}]}]))\n diff-profile \"dev-resources/profil", "end": 5045, "score": 0.9999216198921204, "start": 5029, "tag": "EMAIL", "value": "rolf@example.org" }, { "context": " :member\n [{:name \"alice\",\n :mbox \"mailto:al", "end": 10649, "score": 0.9958639740943909, "start": 10644, "tag": "NAME", "value": "alice" }, { "context": "ce\",\n :mbox \"mailto:alice@example.org\",\n :objectType \"Age", "end": 10714, "score": 0.9999178051948547, "start": 10697, "tag": "EMAIL", "value": "alice@example.org" }, { "context": " :member\n [{:name \"bob\",\n :mbox \"mailto:al", "end": 11093, "score": 0.9958382248878479, "start": 11090, "tag": "NAME", "value": "bob" }, { "context": "ob\",\n :mbox \"mailto:alice@example.org\",\n :objectType \"Age", "end": 11158, "score": 0.9999188184738159, "start": 11141, "tag": "EMAIL", "value": "alice@example.org" } ]
src/test/com/yetanalytics/xapipe/filter_test.clj
yetanalytics/xapipe
3
(ns com.yetanalytics.xapipe.filter-test (:require [clojure.test :refer :all] [com.yetanalytics.xapipe.filter :refer :all] [com.yetanalytics.xapipe.test-support :as sup] [clojure.set :as cset] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [com.yetanalytics.pan.objects.profile :as prof])) (use-fixtures :once (sup/instrument-fixture)) (deftest get-profile-test (testing "slurps the profile from wherever" (testing "a local file" (is (s/valid? ::prof/profile (get-profile "dev-resources/profiles/calibration.jsonld")))) (testing "a remote file via https" (is (s/valid? ::prof/profile (get-profile "https://raw.githubusercontent.com/yetanalytics/xapipe/925a16340a1c7f568b98b6d39d88d2e446ea87d5/dev-resources/profiles/calibration.jsonld")))))) (deftest template-filter-xf-test (let [;; Turn into a transducer to show sequence behavior template-filter-xf (fn [cfg] (let [pred (template-filter-pred cfg)] (filter pred))) a-profile "dev-resources/profiles/calibration_a.jsonld" a-template-ids (-> a-profile get-profile :templates (->> (mapv :id))) a-statements (into [] (sup/gen-statements 50 :profiles [a-profile] :parameters {:seed 42})) b-profile "dev-resources/profiles/calibration_b.jsonld" b-template-ids (-> b-profile get-profile :templates (->> (mapv :id))) b-statements (into [] (sup/gen-statements 50 :profiles [b-profile] :parameters {:seed 24})) all-statements (interleave a-statements b-statements)] (testing "Profile template filter filters by profile + template IDs" (are [profile-urls template-ids statements] (= statements (map :statement (sequence (template-filter-xf {:profile-urls profile-urls :template-ids template-ids}) (mapv (fn [s] {:statement s :attachments []}) all-statements)))) ;; By profiles only ;; Just A [a-profile] [] a-statements ;; Just B [b-profile] [] b-statements ;; Both [a-profile b-profile] [] all-statements ;; None [] [] [] ;; All A template IDs [a-profile] a-template-ids a-statements ;; All B template IDs [b-profile] b-template-ids b-statements ;; All template IDs [a-profile b-profile] (concat a-template-ids b-template-ids) all-statements)) (testing "Filtering by single or multiple template IDs" (are [profile-urls n-templates template-ids statements] ;; For a given grouping of IDs, the resulting statements ;; are a subset of the given profile (every? (fn [ids] (cset/subset? (into #{} (comp (template-filter-xf {:profile-urls profile-urls :template-ids ids}) (map :statement)) (mapv (fn [s] {:statement s :attachments []}) all-statements)) (set statements))) (partition-all n-templates template-ids)) [a-profile] 1 a-template-ids a-statements [a-profile] 5 a-template-ids a-statements [b-profile] 1 b-template-ids b-statements [b-profile] 5 b-template-ids b-statements)))) (deftest concept-filter-test (let [concept-filter-xf (fn [cfg] (let [pred (concept-filter-pred cfg)] (filter pred))) ;; Profile emits a single sequence of 9 statements in a single ;; primary pattern: Two verbs, two object activity types, 4 context ;; activity types and an attachment usage type conc-profile "dev-resources/profiles/calibration_concept.jsonld" conc-stmt (into [] (sup/gen-statements 9 :profiles [conc-profile] :parameters {:seed 42} :personae [{:name "rgregerg", :objectType "Group", :member [{:name "rolf", :mbox "mailto:rolf@example.org"}]}])) diff-profile "dev-resources/profiles/calibration_a.jsonld" diff-stmt (into [] (sup/gen-statements 9 :profiles [diff-profile] :parameters {:seed 42}))] (testing "All Statements Pass when profile-urls but no concept-type or ids are provided, and all fail when not containing any concepts from the profile" (are [profile-urls passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types [] :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; Pass all profile statements [conc-profile] 9 conc-stmt ;; Fail all non-profile statements [conc-profile] 0 diff-stmt)) (testing "Filtering by content types, but no specific ids" (are [profile-urls concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types concept-types :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All Statements have one of the two Verbs [conc-profile] ["Verb"] 9 conc-stmt ;; All Statements have one of the three activity types [conc-profile] ["ActivityType"] 9 conc-stmt ;; Only one statement has the Attachment Usage Type [conc-profile] ["AttachmentUsageType"] 1 conc-stmt)) (testing "Filtering by specific verb ids" (are [verb-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:verb-ids verb-ids :concept-types concept-types :profile-urls [] :activity-type-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All but one statement has verb-1 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-1"] [] 8 conc-stmt ;; One statement has verb-2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] [] 1 conc-stmt ;; No statements have verb-3 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-3"] [] 0 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain Verb ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] ["ActivityType"] 0 conc-stmt)) (testing "Filtering by specific activity type ids" (are [activity-type-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls [] :activity-type-ids activity-type-ids :concept-types concept-types :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; 8 statements have type 1 as the object's type ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] [] 8 conc-stmt ;; One statement has type 2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-2"] [] 1 conc-stmt ;; 4 Statements contain type 3 (this also tests all context activity matching) ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-3"] [] 4 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain ActivityType ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] ["Verb"] 0 conc-stmt)))) (deftest pattern-filter-pred-test (let [profile-url "dev-resources/profiles/calibration_strict_pattern.jsonld" profile-url-alt "dev-resources/profiles/calibration_strict_pattern_alt.jsonld" ;; This strict pattern expects activities 1, 2 and 3, in order [a b c] (sup/gen-statements 3 :parameters {:seed 42} :profiles [profile-url] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "alice", :mbox "mailto:alice@example.org", :objectType "Agent"}]}]) [d e f] (sup/gen-statements 3 :parameters {:seed 43} :profiles [profile-url-alt] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "bob", :mbox "mailto:alice@example.org", :objectType "Agent"}]}])] (sup/art [testing-tag pred-config statements states] (testing testing-tag (let [pred (try (pattern-filter-pred pred-config) (catch Exception _ ::compile-exception)) states' (if (= ::compile-exception pred) ::compile-exception (try (doall (rest (reductions (fn [[state _] s] (pred state {:statement s})) [{} nil] statements))) (catch Exception _ ::match-exception)))] (when-not (keyword? states') (testing "no meta" (is (every? (comp empty? meta) states')))) (testing "expected states" (is (= states states'))))) "In order, is matched" {:profile-urls [profile-url] :pattern-ids []} [a b c a] [;; a starts [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true] ;; a again starts again [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true]] "Out of order, drop match drop" {:profile-urls [profile-url] :pattern-ids []} [b a c] [;; b drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false] ;; a picks up [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; c drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false]] "Multiple Profiles" {:profile-urls [profile-url profile-url-alt] :pattern-ids []} [a d b e c f] [;; a starts a pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; d starts another pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues first pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; e continues second [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {"f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; d accepts + terminates [{:accepts [["f851859f-b0fe-4b36-9939-4276b96d302d" "https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true]] "Invalid multiple profiles with conflicting profile ids" {:profile-urls [profile-url profile-url] :pattern-ids []} [a] ::compile-exception "Invalid multiple profiles with conflicting pattern/template ids" {:profile-urls [profile-url "dev-resources/profiles/calibration_strict_pattern_conflict.jsonld"] :pattern-ids []} [a] ::compile-exception))) (deftest stateless-predicates-test (testing "transforms config into stateless predicates" (is (s/valid? (s/keys :opt-un [:com.yetanalytics.xapipe.filter.stateless-predicates/template]) (stateless-predicates {:template {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :template-ids []}}))))) (deftest stateful-predicates-test (testing "transforms config into stateful predicates" ;; Cannot test this pred because of gen failure in PAN (is (function? (:pattern (stateful-predicates {:pattern {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :pattern-ids []}}))))))
4657
(ns com.yetanalytics.xapipe.filter-test (:require [clojure.test :refer :all] [com.yetanalytics.xapipe.filter :refer :all] [com.yetanalytics.xapipe.test-support :as sup] [clojure.set :as cset] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [com.yetanalytics.pan.objects.profile :as prof])) (use-fixtures :once (sup/instrument-fixture)) (deftest get-profile-test (testing "slurps the profile from wherever" (testing "a local file" (is (s/valid? ::prof/profile (get-profile "dev-resources/profiles/calibration.jsonld")))) (testing "a remote file via https" (is (s/valid? ::prof/profile (get-profile "https://raw.githubusercontent.com/yetanalytics/xapipe/925a16340a1c7f568b98b6d39d88d2e446ea87d5/dev-resources/profiles/calibration.jsonld")))))) (deftest template-filter-xf-test (let [;; Turn into a transducer to show sequence behavior template-filter-xf (fn [cfg] (let [pred (template-filter-pred cfg)] (filter pred))) a-profile "dev-resources/profiles/calibration_a.jsonld" a-template-ids (-> a-profile get-profile :templates (->> (mapv :id))) a-statements (into [] (sup/gen-statements 50 :profiles [a-profile] :parameters {:seed 42})) b-profile "dev-resources/profiles/calibration_b.jsonld" b-template-ids (-> b-profile get-profile :templates (->> (mapv :id))) b-statements (into [] (sup/gen-statements 50 :profiles [b-profile] :parameters {:seed 24})) all-statements (interleave a-statements b-statements)] (testing "Profile template filter filters by profile + template IDs" (are [profile-urls template-ids statements] (= statements (map :statement (sequence (template-filter-xf {:profile-urls profile-urls :template-ids template-ids}) (mapv (fn [s] {:statement s :attachments []}) all-statements)))) ;; By profiles only ;; Just A [a-profile] [] a-statements ;; Just B [b-profile] [] b-statements ;; Both [a-profile b-profile] [] all-statements ;; None [] [] [] ;; All A template IDs [a-profile] a-template-ids a-statements ;; All B template IDs [b-profile] b-template-ids b-statements ;; All template IDs [a-profile b-profile] (concat a-template-ids b-template-ids) all-statements)) (testing "Filtering by single or multiple template IDs" (are [profile-urls n-templates template-ids statements] ;; For a given grouping of IDs, the resulting statements ;; are a subset of the given profile (every? (fn [ids] (cset/subset? (into #{} (comp (template-filter-xf {:profile-urls profile-urls :template-ids ids}) (map :statement)) (mapv (fn [s] {:statement s :attachments []}) all-statements)) (set statements))) (partition-all n-templates template-ids)) [a-profile] 1 a-template-ids a-statements [a-profile] 5 a-template-ids a-statements [b-profile] 1 b-template-ids b-statements [b-profile] 5 b-template-ids b-statements)))) (deftest concept-filter-test (let [concept-filter-xf (fn [cfg] (let [pred (concept-filter-pred cfg)] (filter pred))) ;; Profile emits a single sequence of 9 statements in a single ;; primary pattern: Two verbs, two object activity types, 4 context ;; activity types and an attachment usage type conc-profile "dev-resources/profiles/calibration_concept.jsonld" conc-stmt (into [] (sup/gen-statements 9 :profiles [conc-profile] :parameters {:seed 42} :personae [{:name "rgregerg", :objectType "Group", :member [{:name "rolf", :mbox "mailto:<EMAIL>"}]}])) diff-profile "dev-resources/profiles/calibration_a.jsonld" diff-stmt (into [] (sup/gen-statements 9 :profiles [diff-profile] :parameters {:seed 42}))] (testing "All Statements Pass when profile-urls but no concept-type or ids are provided, and all fail when not containing any concepts from the profile" (are [profile-urls passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types [] :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; Pass all profile statements [conc-profile] 9 conc-stmt ;; Fail all non-profile statements [conc-profile] 0 diff-stmt)) (testing "Filtering by content types, but no specific ids" (are [profile-urls concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types concept-types :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All Statements have one of the two Verbs [conc-profile] ["Verb"] 9 conc-stmt ;; All Statements have one of the three activity types [conc-profile] ["ActivityType"] 9 conc-stmt ;; Only one statement has the Attachment Usage Type [conc-profile] ["AttachmentUsageType"] 1 conc-stmt)) (testing "Filtering by specific verb ids" (are [verb-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:verb-ids verb-ids :concept-types concept-types :profile-urls [] :activity-type-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All but one statement has verb-1 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-1"] [] 8 conc-stmt ;; One statement has verb-2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] [] 1 conc-stmt ;; No statements have verb-3 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-3"] [] 0 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain Verb ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] ["ActivityType"] 0 conc-stmt)) (testing "Filtering by specific activity type ids" (are [activity-type-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls [] :activity-type-ids activity-type-ids :concept-types concept-types :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; 8 statements have type 1 as the object's type ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] [] 8 conc-stmt ;; One statement has type 2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-2"] [] 1 conc-stmt ;; 4 Statements contain type 3 (this also tests all context activity matching) ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-3"] [] 4 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain ActivityType ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] ["Verb"] 0 conc-stmt)))) (deftest pattern-filter-pred-test (let [profile-url "dev-resources/profiles/calibration_strict_pattern.jsonld" profile-url-alt "dev-resources/profiles/calibration_strict_pattern_alt.jsonld" ;; This strict pattern expects activities 1, 2 and 3, in order [a b c] (sup/gen-statements 3 :parameters {:seed 42} :profiles [profile-url] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "<NAME>", :mbox "mailto:<EMAIL>", :objectType "Agent"}]}]) [d e f] (sup/gen-statements 3 :parameters {:seed 43} :profiles [profile-url-alt] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "<NAME>", :mbox "mailto:<EMAIL>", :objectType "Agent"}]}])] (sup/art [testing-tag pred-config statements states] (testing testing-tag (let [pred (try (pattern-filter-pred pred-config) (catch Exception _ ::compile-exception)) states' (if (= ::compile-exception pred) ::compile-exception (try (doall (rest (reductions (fn [[state _] s] (pred state {:statement s})) [{} nil] statements))) (catch Exception _ ::match-exception)))] (when-not (keyword? states') (testing "no meta" (is (every? (comp empty? meta) states')))) (testing "expected states" (is (= states states'))))) "In order, is matched" {:profile-urls [profile-url] :pattern-ids []} [a b c a] [;; a starts [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true] ;; a again starts again [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true]] "Out of order, drop match drop" {:profile-urls [profile-url] :pattern-ids []} [b a c] [;; b drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false] ;; a picks up [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; c drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false]] "Multiple Profiles" {:profile-urls [profile-url profile-url-alt] :pattern-ids []} [a d b e c f] [;; a starts a pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; d starts another pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues first pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; e continues second [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {"f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; d accepts + terminates [{:accepts [["f851859f-b0fe-4b36-9939-4276b96d302d" "https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true]] "Invalid multiple profiles with conflicting profile ids" {:profile-urls [profile-url profile-url] :pattern-ids []} [a] ::compile-exception "Invalid multiple profiles with conflicting pattern/template ids" {:profile-urls [profile-url "dev-resources/profiles/calibration_strict_pattern_conflict.jsonld"] :pattern-ids []} [a] ::compile-exception))) (deftest stateless-predicates-test (testing "transforms config into stateless predicates" (is (s/valid? (s/keys :opt-un [:com.yetanalytics.xapipe.filter.stateless-predicates/template]) (stateless-predicates {:template {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :template-ids []}}))))) (deftest stateful-predicates-test (testing "transforms config into stateful predicates" ;; Cannot test this pred because of gen failure in PAN (is (function? (:pattern (stateful-predicates {:pattern {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :pattern-ids []}}))))))
true
(ns com.yetanalytics.xapipe.filter-test (:require [clojure.test :refer :all] [com.yetanalytics.xapipe.filter :refer :all] [com.yetanalytics.xapipe.test-support :as sup] [clojure.set :as cset] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [com.yetanalytics.pan.objects.profile :as prof])) (use-fixtures :once (sup/instrument-fixture)) (deftest get-profile-test (testing "slurps the profile from wherever" (testing "a local file" (is (s/valid? ::prof/profile (get-profile "dev-resources/profiles/calibration.jsonld")))) (testing "a remote file via https" (is (s/valid? ::prof/profile (get-profile "https://raw.githubusercontent.com/yetanalytics/xapipe/925a16340a1c7f568b98b6d39d88d2e446ea87d5/dev-resources/profiles/calibration.jsonld")))))) (deftest template-filter-xf-test (let [;; Turn into a transducer to show sequence behavior template-filter-xf (fn [cfg] (let [pred (template-filter-pred cfg)] (filter pred))) a-profile "dev-resources/profiles/calibration_a.jsonld" a-template-ids (-> a-profile get-profile :templates (->> (mapv :id))) a-statements (into [] (sup/gen-statements 50 :profiles [a-profile] :parameters {:seed 42})) b-profile "dev-resources/profiles/calibration_b.jsonld" b-template-ids (-> b-profile get-profile :templates (->> (mapv :id))) b-statements (into [] (sup/gen-statements 50 :profiles [b-profile] :parameters {:seed 24})) all-statements (interleave a-statements b-statements)] (testing "Profile template filter filters by profile + template IDs" (are [profile-urls template-ids statements] (= statements (map :statement (sequence (template-filter-xf {:profile-urls profile-urls :template-ids template-ids}) (mapv (fn [s] {:statement s :attachments []}) all-statements)))) ;; By profiles only ;; Just A [a-profile] [] a-statements ;; Just B [b-profile] [] b-statements ;; Both [a-profile b-profile] [] all-statements ;; None [] [] [] ;; All A template IDs [a-profile] a-template-ids a-statements ;; All B template IDs [b-profile] b-template-ids b-statements ;; All template IDs [a-profile b-profile] (concat a-template-ids b-template-ids) all-statements)) (testing "Filtering by single or multiple template IDs" (are [profile-urls n-templates template-ids statements] ;; For a given grouping of IDs, the resulting statements ;; are a subset of the given profile (every? (fn [ids] (cset/subset? (into #{} (comp (template-filter-xf {:profile-urls profile-urls :template-ids ids}) (map :statement)) (mapv (fn [s] {:statement s :attachments []}) all-statements)) (set statements))) (partition-all n-templates template-ids)) [a-profile] 1 a-template-ids a-statements [a-profile] 5 a-template-ids a-statements [b-profile] 1 b-template-ids b-statements [b-profile] 5 b-template-ids b-statements)))) (deftest concept-filter-test (let [concept-filter-xf (fn [cfg] (let [pred (concept-filter-pred cfg)] (filter pred))) ;; Profile emits a single sequence of 9 statements in a single ;; primary pattern: Two verbs, two object activity types, 4 context ;; activity types and an attachment usage type conc-profile "dev-resources/profiles/calibration_concept.jsonld" conc-stmt (into [] (sup/gen-statements 9 :profiles [conc-profile] :parameters {:seed 42} :personae [{:name "rgregerg", :objectType "Group", :member [{:name "rolf", :mbox "mailto:PI:EMAIL:<EMAIL>END_PI"}]}])) diff-profile "dev-resources/profiles/calibration_a.jsonld" diff-stmt (into [] (sup/gen-statements 9 :profiles [diff-profile] :parameters {:seed 42}))] (testing "All Statements Pass when profile-urls but no concept-type or ids are provided, and all fail when not containing any concepts from the profile" (are [profile-urls passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types [] :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; Pass all profile statements [conc-profile] 9 conc-stmt ;; Fail all non-profile statements [conc-profile] 0 diff-stmt)) (testing "Filtering by content types, but no specific ids" (are [profile-urls concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls profile-urls :concept-types concept-types :activity-type-ids [] :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All Statements have one of the two Verbs [conc-profile] ["Verb"] 9 conc-stmt ;; All Statements have one of the three activity types [conc-profile] ["ActivityType"] 9 conc-stmt ;; Only one statement has the Attachment Usage Type [conc-profile] ["AttachmentUsageType"] 1 conc-stmt)) (testing "Filtering by specific verb ids" (are [verb-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:verb-ids verb-ids :concept-types concept-types :profile-urls [] :activity-type-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; All but one statement has verb-1 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-1"] [] 8 conc-stmt ;; One statement has verb-2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] [] 1 conc-stmt ;; No statements have verb-3 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-3"] [] 0 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain Verb ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#verb-2"] ["ActivityType"] 0 conc-stmt)) (testing "Filtering by specific activity type ids" (are [activity-type-ids concept-types passed-num statements] (= passed-num (count (sequence (concept-filter-xf {:profile-urls [] :activity-type-ids activity-type-ids :concept-types concept-types :verb-ids [] :attachment-usage-types []}) (mapv (fn [s] {:statement s :attachments []}) statements)))) ;; 8 statements have type 1 as the object's type ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] [] 8 conc-stmt ;; One statement has type 2 ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-2"] [] 1 conc-stmt ;; 4 Statements contain type 3 (this also tests all context activity matching) ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-3"] [] 4 conc-stmt ;; No statements should pass if concept-types is not empty but ;; doesn't contain ActivityType ["https://xapinet.org/xapi/yet/calibration-concept/v1/concepts#activity-type-1"] ["Verb"] 0 conc-stmt)))) (deftest pattern-filter-pred-test (let [profile-url "dev-resources/profiles/calibration_strict_pattern.jsonld" profile-url-alt "dev-resources/profiles/calibration_strict_pattern_alt.jsonld" ;; This strict pattern expects activities 1, 2 and 3, in order [a b c] (sup/gen-statements 3 :parameters {:seed 42} :profiles [profile-url] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "PI:NAME:<NAME>END_PI", :mbox "mailto:PI:EMAIL:<EMAIL>END_PI", :objectType "Agent"}]}]) [d e f] (sup/gen-statements 3 :parameters {:seed 43} :profiles [profile-url-alt] :personae [{:name "Test Subjects", :objectType "Group", :member [{:name "PI:NAME:<NAME>END_PI", :mbox "mailto:PI:EMAIL:<EMAIL>END_PI", :objectType "Agent"}]}])] (sup/art [testing-tag pred-config statements states] (testing testing-tag (let [pred (try (pattern-filter-pred pred-config) (catch Exception _ ::compile-exception)) states' (if (= ::compile-exception pred) ::compile-exception (try (doall (rest (reductions (fn [[state _] s] (pred state {:statement s})) [{} nil] statements))) (catch Exception _ ::match-exception)))] (when-not (keyword? states') (testing "no meta" (is (every? (comp empty? meta) states')))) (testing "expected states" (is (= states states'))))) "In order, is matched" {:profile-urls [profile-url] :pattern-ids []} [a b c a] [;; a starts [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true] ;; a again starts again [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true]] "Out of order, drop match drop" {:profile-urls [profile-url] :pattern-ids []} [b a c] [;; b drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false] ;; a picks up [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; c drops [{:accepts [], :rejects [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :states-map {}} false]] "Multiple Profiles" {:profile-urls [profile-url profile-url-alt] :pattern-ids []} [a d b e c f] [;; a starts a pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; d starts another pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; b continues first pattern [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 0, :accepted? false}}}}} true] ;; e continues second [{:accepts [], :rejects [], :states-map {"d7acfddb-f4c2-49f4-a081-ad1fb8490448" {"https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}, "f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; c accepts + terminates [{:accepts [["d7acfddb-f4c2-49f4-a081-ad1fb8490448" "https://xapinet.org/xapi/yet/calibration_strict_pattern/v1/patterns#pattern-1"]], :rejects [], :states-map {"f851859f-b0fe-4b36-9939-4276b96d302d" {"https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1" #{{:state 3, :accepted? false}}}}} true] ;; d accepts + terminates [{:accepts [["f851859f-b0fe-4b36-9939-4276b96d302d" "https://xapinet.org/xapi/yet/calibration_strict_pattern_alt/v1/patterns#pattern-1"]], :rejects [], :states-map {}} true]] "Invalid multiple profiles with conflicting profile ids" {:profile-urls [profile-url profile-url] :pattern-ids []} [a] ::compile-exception "Invalid multiple profiles with conflicting pattern/template ids" {:profile-urls [profile-url "dev-resources/profiles/calibration_strict_pattern_conflict.jsonld"] :pattern-ids []} [a] ::compile-exception))) (deftest stateless-predicates-test (testing "transforms config into stateless predicates" (is (s/valid? (s/keys :opt-un [:com.yetanalytics.xapipe.filter.stateless-predicates/template]) (stateless-predicates {:template {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :template-ids []}}))))) (deftest stateful-predicates-test (testing "transforms config into stateful predicates" ;; Cannot test this pred because of gen failure in PAN (is (function? (:pattern (stateful-predicates {:pattern {:profile-urls ["dev-resources/profiles/calibration_strict_pattern.jsonld"] :pattern-ids []}}))))))
[ { "context": "gen-token)]\n (jdbc/update! db :user {:password password-hash\n :token token} [", "end": 1494, "score": 0.654721200466156, "start": 1486, "tag": "PASSWORD", "value": "password" } ]
src/ejnkrfsd/db.clj
iovxw/ejnkrfsd
0
(ns ejnkrfsd.db (:require [clojure.java.jdbc :as jdbc] [crypto.random :as random]) (:import (de.mkammerer.argon2 Argon2Factory))) (def database (atom {})) (def argon2 (Argon2Factory/create)) (defn init-db [db] (reset! database db) (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS user ( id VARCHAR NOT NULL, password VARCHAR NOT NULL, token VARCHAR NOT NULL, admin BOOLEAN DEFAULT FALSE)"])) (defn gen-token [] (random/url-part 64)) (defn new-user ([id password] (new-user @database id password)) ([db id password] (let [password-hash (.hash argon2 2 65536 1 password) token (gen-token)] (jdbc/insert! db :user {:id id, :password password-hash, :token token}) token))) (defn get-user-info ([id] (get-user-info @database id)) ([db id] (-> (jdbc/query db ["SELECT * FROM user WHERE id = ? LIMIT 1" id]) first))) (defn true-passsword? [password password-hash] (.verify argon2 password-hash password)) (defn update-token ([id] (update-token @database id)) ([db id] (let [token (gen-token)] (jdbc/update! db :user {:token token} ["id = ?" id]) token))) (defn reset-password ([id new-password] (update-password @database id new-password)) ([db id new-password] (let [password-hash (.hash argon2 2 65536 1 new-password) token (gen-token)] (jdbc/update! db :user {:password password-hash :token token} ["id = ?" id]) token)))
78372
(ns ejnkrfsd.db (:require [clojure.java.jdbc :as jdbc] [crypto.random :as random]) (:import (de.mkammerer.argon2 Argon2Factory))) (def database (atom {})) (def argon2 (Argon2Factory/create)) (defn init-db [db] (reset! database db) (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS user ( id VARCHAR NOT NULL, password VARCHAR NOT NULL, token VARCHAR NOT NULL, admin BOOLEAN DEFAULT FALSE)"])) (defn gen-token [] (random/url-part 64)) (defn new-user ([id password] (new-user @database id password)) ([db id password] (let [password-hash (.hash argon2 2 65536 1 password) token (gen-token)] (jdbc/insert! db :user {:id id, :password password-hash, :token token}) token))) (defn get-user-info ([id] (get-user-info @database id)) ([db id] (-> (jdbc/query db ["SELECT * FROM user WHERE id = ? LIMIT 1" id]) first))) (defn true-passsword? [password password-hash] (.verify argon2 password-hash password)) (defn update-token ([id] (update-token @database id)) ([db id] (let [token (gen-token)] (jdbc/update! db :user {:token token} ["id = ?" id]) token))) (defn reset-password ([id new-password] (update-password @database id new-password)) ([db id new-password] (let [password-hash (.hash argon2 2 65536 1 new-password) token (gen-token)] (jdbc/update! db :user {:password <PASSWORD>-hash :token token} ["id = ?" id]) token)))
true
(ns ejnkrfsd.db (:require [clojure.java.jdbc :as jdbc] [crypto.random :as random]) (:import (de.mkammerer.argon2 Argon2Factory))) (def database (atom {})) (def argon2 (Argon2Factory/create)) (defn init-db [db] (reset! database db) (jdbc/execute! db ["CREATE TABLE IF NOT EXISTS user ( id VARCHAR NOT NULL, password VARCHAR NOT NULL, token VARCHAR NOT NULL, admin BOOLEAN DEFAULT FALSE)"])) (defn gen-token [] (random/url-part 64)) (defn new-user ([id password] (new-user @database id password)) ([db id password] (let [password-hash (.hash argon2 2 65536 1 password) token (gen-token)] (jdbc/insert! db :user {:id id, :password password-hash, :token token}) token))) (defn get-user-info ([id] (get-user-info @database id)) ([db id] (-> (jdbc/query db ["SELECT * FROM user WHERE id = ? LIMIT 1" id]) first))) (defn true-passsword? [password password-hash] (.verify argon2 password-hash password)) (defn update-token ([id] (update-token @database id)) ([db id] (let [token (gen-token)] (jdbc/update! db :user {:token token} ["id = ?" id]) token))) (defn reset-password ([id new-password] (update-password @database id new-password)) ([db id new-password] (let [password-hash (.hash argon2 2 65536 1 new-password) token (gen-token)] (jdbc/update! db :user {:password PI:PASSWORD:<PASSWORD>END_PI-hash :token token} ["id = ?" id]) token)))
[ { "context": "all]))\n\n\n(defn setup\n []\n (h/create-test-user! \"success+1@simulator.amazonses.com\")\n (h/create-test-user! \"success+3@simulator.ama", "end": 309, "score": 0.999929666519165, "start": 276, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+3@simulator.amazonses.com\")\n (h/create-test-user! \"success+4@simulator.ama", "end": 369, "score": 0.9999307990074158, "start": 336, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "simulator.amazonses.com\")\n (h/create-test-user! \"success+4@simulator.amazonses.com\" \"Test\" #{:customer :admin}) )\n\n(defn fixture [te", "end": 429, "score": 0.999930202960968, "start": 396, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "est (h/request {:query {:user {:user/id (user/id \"success+1@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 781, "score": 0.9999229907989502, "start": 748, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+1@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 1312, "score": 0.9999248385429382, "start": 1279, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+1@simulator.amazonses.com\"\n :query {:user {:user/id (use", "end": 1838, "score": 0.9999280571937561, "start": 1805, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+2@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 1927, "score": 0.999925971031189, "start": 1894, "tag": "EMAIL", "value": "success+2@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+1@simulator.amazonses.com\")}}\n (h/decode :transit body)))))\n\n ", "end": 2200, "score": 0.9999247193336487, "start": 2167, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+3@simulator.amazonses.com\"\n :query {:user {:user/id (use", "end": 2524, "score": 0.9999236464500427, "start": 2491, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+1@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 2613, "score": 0.9999129772186279, "start": 2580, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "s (= 200 status))\n (is (= {:users {(user/id \"success+1@simulator.amazonses.com\")\n (-> (user/id \"success+1@s", "end": 2783, "score": 0.9999266266822815, "start": 2750, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "azonses.com\")\n (-> (user/id \"success+1@simulator.amazonses.com\")\n (user/fetch)\n ", "end": 2855, "score": 0.9999228119850159, "start": 2822, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+3@simulator.amazonses.com\")}}\n (h/decode :transit body)))))\n\n ", "end": 3131, "score": 0.9999273419380188, "start": 3098, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+3@simulator.amazonses.com\"\n :query {:user {:user/id (use", "end": 3536, "score": 0.999925434589386, "start": 3503, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+3@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 3625, "score": 0.9999268054962158, "start": 3592, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "s (= 200 status))\n (is (= {:users {(user/id \"success+3@simulator.amazonses.com\")\n (-> (user/id \"success+3@s", "end": 3795, "score": 0.9999247193336487, "start": 3762, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "azonses.com\")\n (-> (user/id \"success+3@simulator.amazonses.com\")\n (user/fetch)\n ", "end": 3867, "score": 0.9999271631240845, "start": 3834, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+3@simulator.amazonses.com\")}}\n (h/decode :transit body)))))\n\n ", "end": 4150, "score": 0.9999210238456726, "start": 4117, "tag": "EMAIL", "value": "success+3@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+4@simulator.amazonses.com\"\n :query {:user {:user/id (use", "end": 4489, "score": 0.999922513961792, "start": 4456, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+1@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 4578, "score": 0.9999139904975891, "start": 4545, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "s (= 200 status))\n (is (= {:users {(user/id \"success+1@simulator.amazonses.com\")\n (-> (user/id \"success+1@s", "end": 4748, "score": 0.9999204277992249, "start": 4715, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": "azonses.com\")\n (-> (user/id \"success+1@simulator.amazonses.com\")\n (user/fetch)\n ", "end": 4820, "score": 0.9999204277992249, "start": 4787, "tag": "EMAIL", "value": "success+1@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+4@simulator.amazonses.com\")}}\n (h/decode :transit body)))))\n\n ", "end": 5103, "score": 0.9999206066131592, "start": 5070, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "[request (h/request\n {:session \"success+4@simulator.amazonses.com\"\n :query {:user {:user/id (use", "end": 5523, "score": 0.9999229311943054, "start": 5490, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": " :query {:user {:user/id (user/id \"success+4@simulator.amazonses.com\")}}})\n {:keys [status headers body] :as ", "end": 5612, "score": 0.9999235272407532, "start": 5579, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "s (= 200 status))\n (is (= {:users {(user/id \"success+4@simulator.amazonses.com\")\n (-> (user/id \"success+4@s", "end": 5782, "score": 0.9999236464500427, "start": 5749, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": "azonses.com\")\n (-> (user/id \"success+4@simulator.amazonses.com\")\n (user/fetch)\n ", "end": 5854, "score": 0.9999174475669861, "start": 5821, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" }, { "context": " :session {:current-user-id (user/id \"success+4@simulator.amazonses.com\")}}\n (h/decode :transit body))))))\n", "end": 6144, "score": 0.9999070763587952, "start": 6111, "tag": "EMAIL", "value": "success+4@simulator.amazonses.com" } ]
api/test/feature/flow/query/user_test.clj
kgxsz/flow
0
(ns flow.query.user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "success+1@simulator.amazonses.com") (h/create-test-user! "success+3@simulator.amazonses.com") (h/create-test-user! "success+4@simulator.amazonses.com" "Test" #{:customer :admin}) ) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-user (testing "The handler negotiates the user query when no session is provided." (let [request (h/request {:query {:user {:user/id (user/id "success+1@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:user {:user/id (user/id "success+1@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for a non-existent user and an authorised session is provided." (let [request (h/request {:session "success+1@simulator.amazonses.com" :query {:user {:user/id (user/id "success+2@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+1@simulator.amazonses.com")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided." (let [request (h/request {:session "success+3@simulator.amazonses.com" :query {:user {:user/id (user/id "success+1@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "success+1@simulator.amazonses.com") (-> (user/id "success+1@simulator.amazonses.com") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+3@simulator.amazonses.com")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "success+3@simulator.amazonses.com" :query {:user {:user/id (user/id "success+3@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "success+3@simulator.amazonses.com") (-> (user/id "success+3@simulator.amazonses.com") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+3@simulator.amazonses.com")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided." (let [request (h/request {:session "success+4@simulator.amazonses.com" :query {:user {:user/id (user/id "success+1@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "success+1@simulator.amazonses.com") (-> (user/id "success+1@simulator.amazonses.com") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+4@simulator.amazonses.com")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "success+4@simulator.amazonses.com" :query {:user {:user/id (user/id "success+4@simulator.amazonses.com")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "success+4@simulator.amazonses.com") (-> (user/id "success+4@simulator.amazonses.com") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "success+4@simulator.amazonses.com")}} (h/decode :transit body))))))
82891
(ns flow.query.user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>") (h/create-test-user! "<EMAIL>" "Test" #{:customer :admin}) ) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-user (testing "The handler negotiates the user query when no session is provided." (let [request (h/request {:query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for a non-existent user and an authorised session is provided." (let [request (h/request {:session "<EMAIL>" :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided." (let [request (h/request {:session "<EMAIL>" :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "<EMAIL>") (-> (user/id "<EMAIL>") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "<EMAIL>" :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "<EMAIL>") (-> (user/id "<EMAIL>") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided." (let [request (h/request {:session "<EMAIL>" :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "<EMAIL>") (-> (user/id "<EMAIL>") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "<EMAIL>" :query {:user {:user/id (user/id "<EMAIL>")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "<EMAIL>") (-> (user/id "<EMAIL>") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "<EMAIL>")}} (h/decode :transit body))))))
true
(ns flow.query.user-test (:require [flow.core :refer :all] [flow.entity.authorisation :as authorisation] [flow.entity.user :as user] [flow.helpers :as h] [clojure.test :refer :all])) (defn setup [] (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI") (h/create-test-user! "PI:EMAIL:<EMAIL>END_PI" "Test" #{:customer :admin}) ) (defn fixture [test] (h/ensure-empty-table) (setup) (test) (h/ensure-empty-table)) (use-fixtures :each fixture) (deftest test-user (testing "The handler negotiates the user query when no session is provided." (let [request (h/request {:query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when an unauthorised session is provided." (let [request (h/request {:session :unauthorised :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id nil}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for a non-existent user and an authorised session is provided." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "PI:EMAIL:<EMAIL>END_PI") (-> (user/id "PI:EMAIL:<EMAIL>END_PI") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with a customer role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "PI:EMAIL:<EMAIL>END_PI") (-> (user/id "PI:EMAIL:<EMAIL>END_PI") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "PI:EMAIL:<EMAIL>END_PI") (-> (user/id "PI:EMAIL:<EMAIL>END_PI") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))))) (testing "The handler negotiates the user query when the query is being made for an existing user and an authorised session for a user with both a customer and admin role is provided, where the authorised user happens to be the same user being queried." (let [request (h/request {:session "PI:EMAIL:<EMAIL>END_PI" :query {:user {:user/id (user/id "PI:EMAIL:<EMAIL>END_PI")}}}) {:keys [status headers body] :as response} (handler request)] (is (= 200 status)) (is (= {:users {(user/id "PI:EMAIL:<EMAIL>END_PI") (-> (user/id "PI:EMAIL:<EMAIL>END_PI") (user/fetch) (select-keys (get-in h/accessible-keys [:user #{:owner :customer :admin}])))} :authorisations {} :metadata {} :session {:current-user-id (user/id "PI:EMAIL:<EMAIL>END_PI")}} (h/decode :transit body))))))
[ { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (", "end": 589, "score": 0.9977541565895081, "start": 580, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (json-codec b)", "end": 602, "score": 0.9976946115493774, "start": 595, "tag": "NAME", "value": "barbara" }, { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (", "end": 877, "score": 0.9974356293678284, "start": 868, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (json-codec b ", "end": 890, "score": 0.9982187747955322, "start": 883, "tag": "NAME", "value": "barbara" }, { "context": " b] (create-duplex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:p", "end": 1192, "score": 0.9979179501533508, "start": 1183, "tag": "NAME", "value": "aphrodite" }, { "context": "lex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:pertama 123 :k", "end": 1205, "score": 0.9981632828712463, "start": 1198, "tag": "NAME", "value": "barbara" }, { "context": " b] (create-duplex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:p", "end": 2044, "score": 0.9853646159172058, "start": 2035, "tag": "NAME", "value": "aphrodite" }, { "context": "lex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:pertama 123 :k", "end": 2057, "score": 0.9961252212524414, "start": 2050, "tag": "NAME", "value": "barbara" }, { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (", "end": 3792, "score": 0.8401797413825989, "start": 3783, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (json-codec b)", "end": 3805, "score": 0.9728426337242126, "start": 3798, "tag": "NAME", "value": "barbara" }, { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (", "end": 4084, "score": 0.8152685165405273, "start": 4075, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n json-stream (json-codec b ", "end": 4097, "score": 0.9654508233070374, "start": 4090, "tag": "NAME", "value": "barbara" }, { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->j", "end": 4400, "score": 0.9996370673179626, "start": 4391, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->json-bytes ori", "end": 4413, "score": 0.9995096921920776, "start": 4406, "tag": "NAME", "value": "barbara" }, { "context": " original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->json-bytes original)\n ", "end": 4426, "score": 0.9992592930793762, "start": 4419, "tag": "NAME", "value": "cecilia" }, { "context": "a b] (create-duplex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->j", "end": 5023, "score": 0.9996289610862732, "start": 5014, "tag": "NAME", "value": "aphrodite" }, { "context": "plex-stream)\n original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->json-framed or", "end": 5036, "score": 0.9994778633117676, "start": 5029, "tag": "NAME", "value": "barbara" }, { "context": " original {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n full-raw (->json-framed original)\n ", "end": 5049, "score": 0.9992621541023254, "start": 5042, "tag": "NAME", "value": "cecilia" }, { "context": " b] (create-duplex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:p", "end": 6968, "score": 0.8838607668876648, "start": 6959, "tag": "NAME", "value": "aphrodite" }, { "context": "lex-stream)\n original1 {:a \"aphrodite\" :b \"barbara\" :c \"cecilia\"}\n original2 {:pertama 123 :k", "end": 6981, "score": 0.9528056979179382, "start": 6974, "tag": "NAME", "value": "barbara" } ]
data/test/clojure/32c37921a46854b26a8c4ef061be74e76cd68e06json_test.clj
harshp8l/deep-learning-lang-detection
84
(ns clj-bson-rpc.json-test (:require [clj-bson-rpc.bytes :refer :all] [clj-bson-rpc.json :refer :all] [clojure.data.json :as json] [clojure.test :refer :all] [manifold.stream :as stream])) (defn- create-duplex-stream [] (let [a (stream/stream) b (stream/stream)] [(stream/splice a b) (stream/splice b a)])) (defn- ->json-bytes [m] (.getBytes (json/write-str m) "UTF-8")) (defn- ->json-framed [m] (byte-array (concat [0x1e] (->json-bytes m) [0x0a]))) (deftest decode-json (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (is (= @(stream/take! json-stream) original)) (stream/close! a))) (deftest decode-multiple-jsons (let [[a b] (create-duplex-stream) original1 {:a "aphrodite" :b "barbara" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-bytes original1) (->json-bytes original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-multiple-jsons-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "aphrodite" :b "barbara" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-framed original1) (->json-framed original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b :json-framing :rfc-7464)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-over-1MiB-message (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-over-1MiB-message-rfc-7464 (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (defn- bytes->hex [b] (apply str (mapv #(format "%02x" %) b))) (deftest encode-json (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-bytes original)))))) (deftest encode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-framed original)))))) (deftest decoder-dirty-close (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} full-raw (->json-bytes original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :none)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decoder-dirty-close-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "aphrodite" :b "barbara" :c "cecilia"} full-raw (->json-framed original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decode-garbage (let [[a b] (create-duplex-stream) garbage (byte-array [0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d]) ok-bytes (->json-bytes {:a "bom" :b "dia"}) json-stream (json-codec b)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-garbage-rfc-7464 (let [[a b] (create-duplex-stream) garbage (byte-array [0x1e 0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d 0x0a]) ok-bytes (->json-framed {:a "bom" :b "dia"}) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-invalid-frame-and-recovery-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "aphrodite" :b "barbara" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg1 (->json-framed original1) b-msg2 (->json-framed original2) broken (byte-array (concat (->json-bytes {:test "message" :xyz 123}) [0x0a])) content (byte-array (concat b-msg1 broken b-msg2)) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a content)) (is (= @(stream/take! json-stream) original1)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-framing))) (is (= @(stream/take! json-stream) original2))))
52803
(ns clj-bson-rpc.json-test (:require [clj-bson-rpc.bytes :refer :all] [clj-bson-rpc.json :refer :all] [clojure.data.json :as json] [clojure.test :refer :all] [manifold.stream :as stream])) (defn- create-duplex-stream [] (let [a (stream/stream) b (stream/stream)] [(stream/splice a b) (stream/splice b a)])) (defn- ->json-bytes [m] (.getBytes (json/write-str m) "UTF-8")) (defn- ->json-framed [m] (byte-array (concat [0x1e] (->json-bytes m) [0x0a]))) (deftest decode-json (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (is (= @(stream/take! json-stream) original)) (stream/close! a))) (deftest decode-multiple-jsons (let [[a b] (create-duplex-stream) original1 {:a "<NAME>" :b "<NAME>" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-bytes original1) (->json-bytes original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-multiple-jsons-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "<NAME>" :b "<NAME>" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-framed original1) (->json-framed original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b :json-framing :rfc-7464)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-over-1MiB-message (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-over-1MiB-message-rfc-7464 (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (defn- bytes->hex [b] (apply str (mapv #(format "%02x" %) b))) (deftest encode-json (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-bytes original)))))) (deftest encode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-framed original)))))) (deftest decoder-dirty-close (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "<NAME>"} full-raw (->json-bytes original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :none)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decoder-dirty-close-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "<NAME>" :b "<NAME>" :c "<NAME>"} full-raw (->json-framed original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decode-garbage (let [[a b] (create-duplex-stream) garbage (byte-array [0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d]) ok-bytes (->json-bytes {:a "bom" :b "dia"}) json-stream (json-codec b)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-garbage-rfc-7464 (let [[a b] (create-duplex-stream) garbage (byte-array [0x1e 0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d 0x0a]) ok-bytes (->json-framed {:a "bom" :b "dia"}) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-invalid-frame-and-recovery-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "<NAME>" :b "<NAME>" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg1 (->json-framed original1) b-msg2 (->json-framed original2) broken (byte-array (concat (->json-bytes {:test "message" :xyz 123}) [0x0a])) content (byte-array (concat b-msg1 broken b-msg2)) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a content)) (is (= @(stream/take! json-stream) original1)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-framing))) (is (= @(stream/take! json-stream) original2))))
true
(ns clj-bson-rpc.json-test (:require [clj-bson-rpc.bytes :refer :all] [clj-bson-rpc.json :refer :all] [clojure.data.json :as json] [clojure.test :refer :all] [manifold.stream :as stream])) (defn- create-duplex-stream [] (let [a (stream/stream) b (stream/stream)] [(stream/splice a b) (stream/splice b a)])) (defn- ->json-bytes [m] (.getBytes (json/write-str m) "UTF-8")) (defn- ->json-framed [m] (byte-array (concat [0x1e] (->json-bytes m) [0x0a]))) (deftest decode-json (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (is (= @(stream/take! json-stream) original)) (stream/close! a))) (deftest decode-multiple-jsons (let [[a b] (create-duplex-stream) original1 {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-bytes original1) (->json-bytes original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-multiple-jsons-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg (bbuf-concat (->json-framed original1) (->json-framed original2)) [b-part1 b-rest] (bbuf-split-at 14 b-msg) [b-part2 b-part3] (bbuf-split-at (- (count b-rest) 10) b-rest) json-stream (json-codec b :json-framing :rfc-7464)] ;; Writing both at once: (is @(stream/put! a b-msg)) (is (= @(stream/take! json-stream) original1)) (is (= @(stream/take! json-stream) original2)) ;; Arbitrary parts: (is @(stream/put! a b-part1)) (is @(stream/put! a b-part2)) (is (= @(stream/take! json-stream) original1)) (is @(stream/put! a b-part3)) (stream/close! a) (is (= @(stream/take! json-stream) original2)))) (deftest decode-over-1MiB-message (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b)] (is @(stream/put! a (->json-bytes original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (deftest decode-over-1MiB-message-rfc-7464 (let [[a b] (create-duplex-stream) ipsum (slurp "test/data/ipsum.txt") original {:pertama ipsum :kedua ipsum :ketiga ipsum :again [ipsum ipsum ipsum ipsum ipsum]} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (->json-framed original))) (stream/close! a) (is (= @(stream/take! json-stream) original)))) (defn- bytes->hex [b] (apply str (mapv #(format "%02x" %) b))) (deftest encode-json (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} json-stream (json-codec b)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-bytes original)))))) (deftest encode-json-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! json-stream original)) (is (= (bytes->hex @(stream/take! a)) (bytes->hex (->json-framed original)))))) (deftest decoder-dirty-close (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "PI:NAME:<NAME>END_PI"} full-raw (->json-bytes original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :none)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decoder-dirty-close-rfc-7464 (let [[a b] (create-duplex-stream) original {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "PI:NAME:<NAME>END_PI"} full-raw (->json-framed original) double-raw (bbuf-concat full-raw full-raw) [broken _t] (bbuf-split-at (- (count double-raw) 10) double-raw) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a broken)) (stream/close! a) (is (= @(stream/take! json-stream) original)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :trailing-garbage))))) (deftest decode-garbage (let [[a b] (create-duplex-stream) garbage (byte-array [0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d]) ok-bytes (->json-bytes {:a "bom" :b "dia"}) json-stream (json-codec b)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-garbage-rfc-7464 (let [[a b] (create-duplex-stream) garbage (byte-array [0x1e 0x7b 0x31 0x32 0x33 0x20 0x22 0x66 0x6f 0x6f 0x62 0x61 0x72 0x22 0x7d 0x0a]) ok-bytes (->json-framed {:a "bom" :b "dia"}) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a (bbuf-concat ok-bytes (bbuf-concat garbage ok-bytes)))) (is (= @(stream/take! json-stream) {:b "dia" :a "bom"})) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-json))) (stream/close! a))) (deftest decode-invalid-frame-and-recovery-rfc-7464 (let [[a b] (create-duplex-stream) original1 {:a "PI:NAME:<NAME>END_PI" :b "PI:NAME:<NAME>END_PI" :c "cecilia"} original2 {:pertama 123 :kedua "Apa kabar Abu Bakar!"} b-msg1 (->json-framed original1) b-msg2 (->json-framed original2) broken (byte-array (concat (->json-bytes {:test "message" :xyz 123}) [0x0a])) content (byte-array (concat b-msg1 broken b-msg2)) json-stream (json-codec b :json-framing :rfc-7464)] (is @(stream/put! a content)) (is (= @(stream/take! json-stream) original1)) (let [error @(stream/take! json-stream)] (is (instance? clojure.lang.ExceptionInfo error)) (is (= (:type (ex-data error)) :invalid-framing))) (is (= @(stream/take! json-stream) original2))))
[ { "context": "ent-plan \"plain-amr\")\n data [{:actor \"Harry\"\n :co-actor \"Sally\"}]\n r", "end": 10547, "score": 0.9985426664352417, "start": 10542, "tag": "NAME", "value": "Harry" }, { "context": "a [{:actor \"Harry\"\n :co-actor \"Sally\"}]\n result (planner/render-dp document-p", "end": 10582, "score": 0.9987491369247437, "start": 10577, "tag": "NAME", "value": "Sally" }, { "context": "n \"plain-author-amr\")\n data [{:actor \"Paul Vigna, Michael J. Casey\"\n :co-actor \"Th", "end": 10923, "score": 0.99986332654953, "start": 10913, "tag": "NAME", "value": "Paul Vigna" }, { "context": "thor-amr\")\n data [{:actor \"Paul Vigna, Michael J. Casey\"\n :co-actor \"The Age of Cryptocur", "end": 10941, "score": 0.9998461008071899, "start": 10925, "tag": "NAME", "value": "Michael J. Casey" } ]
api/test/api/nlg/generator/planner_ng_test.clj
keoni161/accelerated-text
0
(ns api.nlg.generator.planner-ng-test (:require [api.nlg.generator.planner-ng :as planner] [api.nlg.generator.parser-ng :as parser] [api.test-utils :refer [load-test-document-plan]] [clojure.data :as data] [clojure.string :as string] [clojure.test :refer [deftest is testing]] [clojure.tools.logging :as log])) (defn compare-result [expected result] (let [[l r _] (data/diff expected result)] (is (= [] (remove nil? l))) (is (= [] (remove nil? r))))) (deftest test-compile-single-node-plan (let [compiled (parser/parse-document-plan (load-test-document-plan "single-subj") {} {:reader-profile :default})] (is (= 1 (count compiled))) (is (compare-result {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}}] :static [] :reader-profile :default} (planner/build-dp-instance (-> compiled first first)))))) (deftest plan-with-two-features (testing "Create subject with two features" (let [document-plan (load-test-document-plan "subj-w-2-features") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default}] (log/debugf "Concrete plan: %s" (pr-str concrete-plan)) (let [result (planner/build-dp-instance concrete-plan)] (log/debugf "Result: %s" (pr-str result)) (compare-result expected result)))))) (deftest plan-with-two-features-and-quote (let [document-plan (load-test-document-plan "subj-w-2-features-and-quote") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:quote "special for you" :dyn-name "$4"} :attrs {:type :benefit :source :quote}}] :static ["provides"] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan))))) (deftest plan-with-modifier (let [compiled (parser/parse-document-plan (load-test-document-plan "adjective-phrase") {} {:reader-profile :default}) concrete-plan (ffirst compiled) expected {:dynamic [{:name {:modifier "good" :dyn-name "$1"} :attrs {:type :modifier :source :modifier}} {:name {:cell :title :dyn-name "$2"} :attrs {:type :cell :source :cell}}] :static [] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan)))) (deftest plan-with-conditional-if (testing "Create plan with conditional" (let [document-plan (load-test-document-plan "subj-w-if") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence (let [concrete-plan (ffirst compiled) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$4"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default} result (planner/build-dp-instance concrete-plan)] (compare-result expected result)) ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$2"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest plan-with-conditional-if-else (testing "Create plan with if-else" (let [document-plan (load-test-document-plan "subj-w-if-else") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence - Not interesting ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results" "results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$3"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest generate-actual-text (testing "Create text with product and two features" (let [document-plan (load-test-document-plan "subj-w-2-features") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (first (planner/render-dp document-plan data :default)) expected #{"Nike Air gives comfort and support." "Nike Air offers comfort and support." "Nike Air provides comfort and support." "Nike Air gives comfort, support." "Nike Air offers comfort, support." "Nike Air provides comfort, support." "Nike Air gives support and comfort." "Nike Air offers support and comfort." "Nike Air provides support and comfort." "Nike Air gives support, comfort." "Nike Air offers support, comfort." "Nike Air provides support, comfort." "Nike Air gives comfort." "Nike Air offers comfort." "Nike Air provides comfort." "Nike Air gives support." "Nike Air offers support." "Nike Air provides support."}] (is (contains? expected result)))) (testing "Create text with product, two features and component with quote" (let [document-plan (load-test-document-plan "subj-w-2-features-and-component") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing"}] result (first (planner/render-dp document-plan data :default)) expected #{"A snug fit for everyday wear." "Premium lacing results in a snug fit for everyday wear."}] (is (contains? expected result))))) (deftest generate-complex-examples (testing "Create text with if" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "snug fit for everyday wear"] (is (string/includes? result expected)))) (testing "Create text with else" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "nylon lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "cool looking fit"] (is (string/includes? result expected))))) (deftest generate-simple-statement (is (= "X." (first (planner/render-dp (load-test-document-plan "simple-plan") [{:product-name "X"}] :default))))) (deftest ^:integration plan-with-dictionary (testing "Create text with dictionary" (let [document-plan (load-test-document-plan "subj-w-dictionary") data [{:product-name "Nike Air" :main-feature "comfort"}] result (planner/render-dp document-plan data {})] (is (seq result))))) (deftest ^:integration plan-with-amr (testing "Create text with amr" (let [document-plan (load-test-document-plan "subj-w-amr") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-amr") data [{:actor "Harry" :co-actor "Sally"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-author-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-author-amr") data [{:actor "Paul Vigna, Michael J. Casey" :co-actor "The Age of Cryptocurrency"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result)))))
69789
(ns api.nlg.generator.planner-ng-test (:require [api.nlg.generator.planner-ng :as planner] [api.nlg.generator.parser-ng :as parser] [api.test-utils :refer [load-test-document-plan]] [clojure.data :as data] [clojure.string :as string] [clojure.test :refer [deftest is testing]] [clojure.tools.logging :as log])) (defn compare-result [expected result] (let [[l r _] (data/diff expected result)] (is (= [] (remove nil? l))) (is (= [] (remove nil? r))))) (deftest test-compile-single-node-plan (let [compiled (parser/parse-document-plan (load-test-document-plan "single-subj") {} {:reader-profile :default})] (is (= 1 (count compiled))) (is (compare-result {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}}] :static [] :reader-profile :default} (planner/build-dp-instance (-> compiled first first)))))) (deftest plan-with-two-features (testing "Create subject with two features" (let [document-plan (load-test-document-plan "subj-w-2-features") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default}] (log/debugf "Concrete plan: %s" (pr-str concrete-plan)) (let [result (planner/build-dp-instance concrete-plan)] (log/debugf "Result: %s" (pr-str result)) (compare-result expected result)))))) (deftest plan-with-two-features-and-quote (let [document-plan (load-test-document-plan "subj-w-2-features-and-quote") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:quote "special for you" :dyn-name "$4"} :attrs {:type :benefit :source :quote}}] :static ["provides"] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan))))) (deftest plan-with-modifier (let [compiled (parser/parse-document-plan (load-test-document-plan "adjective-phrase") {} {:reader-profile :default}) concrete-plan (ffirst compiled) expected {:dynamic [{:name {:modifier "good" :dyn-name "$1"} :attrs {:type :modifier :source :modifier}} {:name {:cell :title :dyn-name "$2"} :attrs {:type :cell :source :cell}}] :static [] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan)))) (deftest plan-with-conditional-if (testing "Create plan with conditional" (let [document-plan (load-test-document-plan "subj-w-if") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence (let [concrete-plan (ffirst compiled) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$4"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default} result (planner/build-dp-instance concrete-plan)] (compare-result expected result)) ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$2"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest plan-with-conditional-if-else (testing "Create plan with if-else" (let [document-plan (load-test-document-plan "subj-w-if-else") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence - Not interesting ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results" "results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$3"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest generate-actual-text (testing "Create text with product and two features" (let [document-plan (load-test-document-plan "subj-w-2-features") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (first (planner/render-dp document-plan data :default)) expected #{"Nike Air gives comfort and support." "Nike Air offers comfort and support." "Nike Air provides comfort and support." "Nike Air gives comfort, support." "Nike Air offers comfort, support." "Nike Air provides comfort, support." "Nike Air gives support and comfort." "Nike Air offers support and comfort." "Nike Air provides support and comfort." "Nike Air gives support, comfort." "Nike Air offers support, comfort." "Nike Air provides support, comfort." "Nike Air gives comfort." "Nike Air offers comfort." "Nike Air provides comfort." "Nike Air gives support." "Nike Air offers support." "Nike Air provides support."}] (is (contains? expected result)))) (testing "Create text with product, two features and component with quote" (let [document-plan (load-test-document-plan "subj-w-2-features-and-component") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing"}] result (first (planner/render-dp document-plan data :default)) expected #{"A snug fit for everyday wear." "Premium lacing results in a snug fit for everyday wear."}] (is (contains? expected result))))) (deftest generate-complex-examples (testing "Create text with if" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "snug fit for everyday wear"] (is (string/includes? result expected)))) (testing "Create text with else" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "nylon lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "cool looking fit"] (is (string/includes? result expected))))) (deftest generate-simple-statement (is (= "X." (first (planner/render-dp (load-test-document-plan "simple-plan") [{:product-name "X"}] :default))))) (deftest ^:integration plan-with-dictionary (testing "Create text with dictionary" (let [document-plan (load-test-document-plan "subj-w-dictionary") data [{:product-name "Nike Air" :main-feature "comfort"}] result (planner/render-dp document-plan data {})] (is (seq result))))) (deftest ^:integration plan-with-amr (testing "Create text with amr" (let [document-plan (load-test-document-plan "subj-w-amr") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-amr") data [{:actor "<NAME>" :co-actor "<NAME>"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-author-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-author-amr") data [{:actor "<NAME>, <NAME>" :co-actor "The Age of Cryptocurrency"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result)))))
true
(ns api.nlg.generator.planner-ng-test (:require [api.nlg.generator.planner-ng :as planner] [api.nlg.generator.parser-ng :as parser] [api.test-utils :refer [load-test-document-plan]] [clojure.data :as data] [clojure.string :as string] [clojure.test :refer [deftest is testing]] [clojure.tools.logging :as log])) (defn compare-result [expected result] (let [[l r _] (data/diff expected result)] (is (= [] (remove nil? l))) (is (= [] (remove nil? r))))) (deftest test-compile-single-node-plan (let [compiled (parser/parse-document-plan (load-test-document-plan "single-subj") {} {:reader-profile :default})] (is (= 1 (count compiled))) (is (compare-result {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}}] :static [] :reader-profile :default} (planner/build-dp-instance (-> compiled first first)))))) (deftest plan-with-two-features (testing "Create subject with two features" (let [document-plan (load-test-document-plan "subj-w-2-features") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default}] (log/debugf "Concrete plan: %s" (pr-str concrete-plan)) (let [result (planner/build-dp-instance concrete-plan)] (log/debugf "Result: %s" (pr-str result)) (compare-result expected result)))))) (deftest plan-with-two-features-and-quote (let [document-plan (load-test-document-plan "subj-w-2-features-and-quote") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (let [first-segment (first compiled) concrete-plan (first first-segment) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$2"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:quote "special for you" :dyn-name "$4"} :attrs {:type :benefit :source :quote}}] :static ["provides"] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan))))) (deftest plan-with-modifier (let [compiled (parser/parse-document-plan (load-test-document-plan "adjective-phrase") {} {:reader-profile :default}) concrete-plan (ffirst compiled) expected {:dynamic [{:name {:modifier "good" :dyn-name "$1"} :attrs {:type :modifier :source :modifier}} {:name {:cell :title :dyn-name "$2"} :attrs {:type :cell :source :cell}}] :static [] :reader-profile :default}] (compare-result expected (planner/build-dp-instance concrete-plan)))) (deftest plan-with-conditional-if (testing "Create plan with conditional" (let [document-plan (load-test-document-plan "subj-w-if") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence (let [concrete-plan (ffirst compiled) expected {:dynamic [{:name {:cell :product-name :dyn-name "$1"} :attrs {:type :product :source :cell}} {:name {:cell :main-feature :dyn-name "$3"} :attrs {:type :benefit :source :cell}} {:name {:cell :secondary-feature :dyn-name "$4"} :attrs {:type :benefit :source :cell}}] :static ["provides"] :reader-profile :default} result (planner/build-dp-instance concrete-plan)] (compare-result expected result)) ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$2"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest plan-with-conditional-if-else (testing "Create plan with if-else" (let [document-plan (load-test-document-plan "subj-w-if-else") compiled (parser/parse-document-plan document-plan {} {:reader-profile :default})] (is (seq compiled)) (is (= 1 (count compiled))) (is (= 2 (count (first compiled)))) ;; First sentence - Not interesting ;; Second sentence (let [concrete-plan (nth (first compiled) 1) result (planner/build-dp-instance concrete-plan)] (is (= ["results" "results"] (result :static))) (let [gated-var (first (result :dynamic))] (is (= {:cell :lacing :dyn-name "$3"} (gated-var :name))) (is (contains? (gated-var :attrs) :gate))))))) (deftest generate-actual-text (testing "Create text with product and two features" (let [document-plan (load-test-document-plan "subj-w-2-features") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (first (planner/render-dp document-plan data :default)) expected #{"Nike Air gives comfort and support." "Nike Air offers comfort and support." "Nike Air provides comfort and support." "Nike Air gives comfort, support." "Nike Air offers comfort, support." "Nike Air provides comfort, support." "Nike Air gives support and comfort." "Nike Air offers support and comfort." "Nike Air provides support and comfort." "Nike Air gives support, comfort." "Nike Air offers support, comfort." "Nike Air provides support, comfort." "Nike Air gives comfort." "Nike Air offers comfort." "Nike Air provides comfort." "Nike Air gives support." "Nike Air offers support." "Nike Air provides support."}] (is (contains? expected result)))) (testing "Create text with product, two features and component with quote" (let [document-plan (load-test-document-plan "subj-w-2-features-and-component") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing"}] result (first (planner/render-dp document-plan data :default)) expected #{"A snug fit for everyday wear." "Premium lacing results in a snug fit for everyday wear."}] (is (contains? expected result))))) (deftest generate-complex-examples (testing "Create text with if" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "premium lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "snug fit for everyday wear"] (is (string/includes? result expected)))) (testing "Create text with else" (let [document-plan (load-test-document-plan "subj-w-if-else") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support" :lacing "nylon lacing" :style "wonderful"}] result (first (planner/render-dp document-plan data :default)) expected "cool looking fit"] (is (string/includes? result expected))))) (deftest generate-simple-statement (is (= "X." (first (planner/render-dp (load-test-document-plan "simple-plan") [{:product-name "X"}] :default))))) (deftest ^:integration plan-with-dictionary (testing "Create text with dictionary" (let [document-plan (load-test-document-plan "subj-w-dictionary") data [{:product-name "Nike Air" :main-feature "comfort"}] result (planner/render-dp document-plan data {})] (is (seq result))))) (deftest ^:integration plan-with-amr (testing "Create text with amr" (let [document-plan (load-test-document-plan "subj-w-amr") data [{:product-name "Nike Air" :main-feature "comfort" :secondary-feature "support"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-amr") data [{:actor "PI:NAME:<NAME>END_PI" :co-actor "PI:NAME:<NAME>END_PI"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result))))) (deftest ^:integration plain-plan-with-author-amr (testing "Handle plan with it" (let [document-plan (load-test-document-plan "plain-author-amr") data [{:actor "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" :co-actor "The Age of Cryptocurrency"}] result (planner/render-dp document-plan data {})] (is (seq result)) (log/debugf "Final AMR results: %s" (pr-str result)))))
[ { "context": " \"Password for opening the keystore\")\n :default \"changeit\"\n :sensitive? true)\n\n(defsetting saml-keystore-a", "end": 2933, "score": 0.718056321144104, "start": 2925, "tag": "PASSWORD", "value": "changeit" } ]
c#-metabase/enterprise/backend/src/metabase_enterprise/sso/integrations/sso_settings.clj
hanakhry/Crime_Admin
0
(ns metabase-enterprise.sso.integrations.sso-settings "Namesapce for defining settings used by the SSO backends. This is separate as both the functions needed to support the SSO backends and the generic routing code used to determine which SSO backend to use need this information. Separating out this information creates a better dependency graph and avoids circular dependencies." (:require [clojure.tools.logging :as log] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util :as u] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [saml20-clj.core :as saml] [schema.core :as s])) (def ^:private GroupMappings (s/maybe {su/KeywordOrString [su/IntGreaterThanZero]})) (def ^:private ^{:arglists '([group-mappings])} validate-group-mappings (s/validator GroupMappings)) (defsetting saml-enabled (deferred-tru "Enable SAML authentication.") :type :boolean :default false) (defsetting saml-identity-provider-uri (deferred-tru "This is the URL where your users go to log in to your identity provider. Depending on which IdP you''re using, this usually looks like https://your-org-name.example.com or https://example.com/app/my_saml_app/abc123/sso/saml")) (s/defn ^:private validate-saml-idp-cert "Validate that an encoded identity provider certificate is valid, or throw an Exception." [idp-cert-str :- s/Str] (try (instance? java.security.cert.X509Certificate (saml/->X509Certificate idp-cert-str)) (catch Throwable e (log/error e (trs "Error parsing SAML identity provider certificate")) (throw (Exception. (tru "Invalid identity provider certificate. Certificate should be a base-64 encoded string.")))))) (defsetting saml-identity-provider-certificate (deferred-tru "Encoded certificate for the identity provider. Depending on your IdP, you might need to download this, open it in a text editor, then copy and paste the certificate's contents here.") :setter (fn [new-value] ;; when setting the idp cert validate that it's something we (when new-value (validate-saml-idp-cert new-value)) (setting/set-string! :saml-identity-provider-certificate new-value))) (defsetting saml-identity-provider-issuer (deferred-tru "This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'. Depending on your IdP, this usually looks something like http://www.example.com/141xkex604w0Q5PN724v")) (defsetting saml-application-name (deferred-tru "This application name will be used for requests to the Identity Provider") :default "Metabase") (defsetting saml-keystore-path (deferred-tru "Absolute path to the Keystore file to use for signing SAML requests")) (defsetting saml-keystore-password (deferred-tru "Password for opening the keystore") :default "changeit" :sensitive? true) (defsetting saml-keystore-alias (deferred-tru "Alias for the key that Metabase should use for signing SAML requests") :default "metabase") (defsetting saml-attribute-email (deferred-tru "SAML attribute for the user''s email address") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress") (defsetting saml-attribute-firstname (deferred-tru "SAML attribute for the user''s first name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname") (defsetting saml-attribute-lastname (deferred-tru "SAML attribute for the user''s last name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname") (defsetting saml-group-sync (deferred-tru "Enable group membership synchronization with SAML.") :type :boolean :default false) (defsetting saml-attribute-group (deferred-tru "SAML attribute for group syncing") :default "member_of") (defsetting saml-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are SAML groups and values are lists of MB groups IDs (deferred-tru "JSON containing SAML to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :saml-group-mappings) validate-group-mappings)) (defn saml-configured? "Check if SAML is enabled and that the mandatory settings are configured." [] (boolean (and (saml-enabled) (saml-identity-provider-uri) (saml-identity-provider-certificate)))) (defsetting jwt-enabled (deferred-tru "Enable JWT based authentication") :type :boolean :default false) (defsetting jwt-identity-provider-uri (deferred-tru "URL of JWT based login page")) (defsetting jwt-shared-secret (deferred-tru "String used to seed the private key used to validate JWT messages") :setter (fn [new-value] (when (seq new-value) (assert (u/hexadecimal-string? new-value) "Invalid JWT Shared Secret key must be a hexadecimal-encoded 256-bit key (i.e., a 64-character string).")) (setting/set-string! :jwt-shared-secret new-value))) (defsetting jwt-attribute-email (deferred-tru "Key to retrieve the JWT user's email address") :default "email") (defsetting jwt-attribute-firstname (deferred-tru "Key to retrieve the JWT user's first name") :default "first_name") (defsetting jwt-attribute-lastname (deferred-tru "Key to retrieve the JWT user's last name") :default "last_name") (defsetting jwt-attribute-groups (deferred-tru "Key to retrieve the JWT user's groups") :default "groups") (defsetting jwt-group-sync (deferred-tru "Enable group membership synchronization with JWT.") :type :boolean :default false) (defsetting jwt-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are JWT groups and values are lists of MB groups IDs (deferred-tru "JSON containing JWT to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :jwt-group-mappings) validate-group-mappings)) (defn jwt-configured? "Check if JWT is enabled and that the mandatory settings are configured." [] (boolean (and (jwt-enabled) (jwt-identity-provider-uri) (jwt-shared-secret)))) (defsetting send-new-sso-user-admin-email? (deferred-tru "Should new email notifications be sent to admins, for all new SSO users?") :type :boolean :default true) (defsetting other-sso-configured? "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for authorization rather than the normal login form or Google Auth button." :visibility :public :setter :none :getter (fn [] (or (saml-configured?) (jwt-configured?))))
71300
(ns metabase-enterprise.sso.integrations.sso-settings "Namesapce for defining settings used by the SSO backends. This is separate as both the functions needed to support the SSO backends and the generic routing code used to determine which SSO backend to use need this information. Separating out this information creates a better dependency graph and avoids circular dependencies." (:require [clojure.tools.logging :as log] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util :as u] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [saml20-clj.core :as saml] [schema.core :as s])) (def ^:private GroupMappings (s/maybe {su/KeywordOrString [su/IntGreaterThanZero]})) (def ^:private ^{:arglists '([group-mappings])} validate-group-mappings (s/validator GroupMappings)) (defsetting saml-enabled (deferred-tru "Enable SAML authentication.") :type :boolean :default false) (defsetting saml-identity-provider-uri (deferred-tru "This is the URL where your users go to log in to your identity provider. Depending on which IdP you''re using, this usually looks like https://your-org-name.example.com or https://example.com/app/my_saml_app/abc123/sso/saml")) (s/defn ^:private validate-saml-idp-cert "Validate that an encoded identity provider certificate is valid, or throw an Exception." [idp-cert-str :- s/Str] (try (instance? java.security.cert.X509Certificate (saml/->X509Certificate idp-cert-str)) (catch Throwable e (log/error e (trs "Error parsing SAML identity provider certificate")) (throw (Exception. (tru "Invalid identity provider certificate. Certificate should be a base-64 encoded string.")))))) (defsetting saml-identity-provider-certificate (deferred-tru "Encoded certificate for the identity provider. Depending on your IdP, you might need to download this, open it in a text editor, then copy and paste the certificate's contents here.") :setter (fn [new-value] ;; when setting the idp cert validate that it's something we (when new-value (validate-saml-idp-cert new-value)) (setting/set-string! :saml-identity-provider-certificate new-value))) (defsetting saml-identity-provider-issuer (deferred-tru "This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'. Depending on your IdP, this usually looks something like http://www.example.com/141xkex604w0Q5PN724v")) (defsetting saml-application-name (deferred-tru "This application name will be used for requests to the Identity Provider") :default "Metabase") (defsetting saml-keystore-path (deferred-tru "Absolute path to the Keystore file to use for signing SAML requests")) (defsetting saml-keystore-password (deferred-tru "Password for opening the keystore") :default "<PASSWORD>" :sensitive? true) (defsetting saml-keystore-alias (deferred-tru "Alias for the key that Metabase should use for signing SAML requests") :default "metabase") (defsetting saml-attribute-email (deferred-tru "SAML attribute for the user''s email address") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress") (defsetting saml-attribute-firstname (deferred-tru "SAML attribute for the user''s first name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname") (defsetting saml-attribute-lastname (deferred-tru "SAML attribute for the user''s last name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname") (defsetting saml-group-sync (deferred-tru "Enable group membership synchronization with SAML.") :type :boolean :default false) (defsetting saml-attribute-group (deferred-tru "SAML attribute for group syncing") :default "member_of") (defsetting saml-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are SAML groups and values are lists of MB groups IDs (deferred-tru "JSON containing SAML to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :saml-group-mappings) validate-group-mappings)) (defn saml-configured? "Check if SAML is enabled and that the mandatory settings are configured." [] (boolean (and (saml-enabled) (saml-identity-provider-uri) (saml-identity-provider-certificate)))) (defsetting jwt-enabled (deferred-tru "Enable JWT based authentication") :type :boolean :default false) (defsetting jwt-identity-provider-uri (deferred-tru "URL of JWT based login page")) (defsetting jwt-shared-secret (deferred-tru "String used to seed the private key used to validate JWT messages") :setter (fn [new-value] (when (seq new-value) (assert (u/hexadecimal-string? new-value) "Invalid JWT Shared Secret key must be a hexadecimal-encoded 256-bit key (i.e., a 64-character string).")) (setting/set-string! :jwt-shared-secret new-value))) (defsetting jwt-attribute-email (deferred-tru "Key to retrieve the JWT user's email address") :default "email") (defsetting jwt-attribute-firstname (deferred-tru "Key to retrieve the JWT user's first name") :default "first_name") (defsetting jwt-attribute-lastname (deferred-tru "Key to retrieve the JWT user's last name") :default "last_name") (defsetting jwt-attribute-groups (deferred-tru "Key to retrieve the JWT user's groups") :default "groups") (defsetting jwt-group-sync (deferred-tru "Enable group membership synchronization with JWT.") :type :boolean :default false) (defsetting jwt-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are JWT groups and values are lists of MB groups IDs (deferred-tru "JSON containing JWT to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :jwt-group-mappings) validate-group-mappings)) (defn jwt-configured? "Check if JWT is enabled and that the mandatory settings are configured." [] (boolean (and (jwt-enabled) (jwt-identity-provider-uri) (jwt-shared-secret)))) (defsetting send-new-sso-user-admin-email? (deferred-tru "Should new email notifications be sent to admins, for all new SSO users?") :type :boolean :default true) (defsetting other-sso-configured? "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for authorization rather than the normal login form or Google Auth button." :visibility :public :setter :none :getter (fn [] (or (saml-configured?) (jwt-configured?))))
true
(ns metabase-enterprise.sso.integrations.sso-settings "Namesapce for defining settings used by the SSO backends. This is separate as both the functions needed to support the SSO backends and the generic routing code used to determine which SSO backend to use need this information. Separating out this information creates a better dependency graph and avoids circular dependencies." (:require [clojure.tools.logging :as log] [metabase.models.setting :as setting :refer [defsetting]] [metabase.util :as u] [metabase.util.i18n :refer [deferred-tru trs tru]] [metabase.util.schema :as su] [saml20-clj.core :as saml] [schema.core :as s])) (def ^:private GroupMappings (s/maybe {su/KeywordOrString [su/IntGreaterThanZero]})) (def ^:private ^{:arglists '([group-mappings])} validate-group-mappings (s/validator GroupMappings)) (defsetting saml-enabled (deferred-tru "Enable SAML authentication.") :type :boolean :default false) (defsetting saml-identity-provider-uri (deferred-tru "This is the URL where your users go to log in to your identity provider. Depending on which IdP you''re using, this usually looks like https://your-org-name.example.com or https://example.com/app/my_saml_app/abc123/sso/saml")) (s/defn ^:private validate-saml-idp-cert "Validate that an encoded identity provider certificate is valid, or throw an Exception." [idp-cert-str :- s/Str] (try (instance? java.security.cert.X509Certificate (saml/->X509Certificate idp-cert-str)) (catch Throwable e (log/error e (trs "Error parsing SAML identity provider certificate")) (throw (Exception. (tru "Invalid identity provider certificate. Certificate should be a base-64 encoded string.")))))) (defsetting saml-identity-provider-certificate (deferred-tru "Encoded certificate for the identity provider. Depending on your IdP, you might need to download this, open it in a text editor, then copy and paste the certificate's contents here.") :setter (fn [new-value] ;; when setting the idp cert validate that it's something we (when new-value (validate-saml-idp-cert new-value)) (setting/set-string! :saml-identity-provider-certificate new-value))) (defsetting saml-identity-provider-issuer (deferred-tru "This is a unique identifier for the IdP. Often referred to as Entity ID or simply 'Issuer'. Depending on your IdP, this usually looks something like http://www.example.com/141xkex604w0Q5PN724v")) (defsetting saml-application-name (deferred-tru "This application name will be used for requests to the Identity Provider") :default "Metabase") (defsetting saml-keystore-path (deferred-tru "Absolute path to the Keystore file to use for signing SAML requests")) (defsetting saml-keystore-password (deferred-tru "Password for opening the keystore") :default "PI:PASSWORD:<PASSWORD>END_PI" :sensitive? true) (defsetting saml-keystore-alias (deferred-tru "Alias for the key that Metabase should use for signing SAML requests") :default "metabase") (defsetting saml-attribute-email (deferred-tru "SAML attribute for the user''s email address") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress") (defsetting saml-attribute-firstname (deferred-tru "SAML attribute for the user''s first name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname") (defsetting saml-attribute-lastname (deferred-tru "SAML attribute for the user''s last name") :default "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname") (defsetting saml-group-sync (deferred-tru "Enable group membership synchronization with SAML.") :type :boolean :default false) (defsetting saml-attribute-group (deferred-tru "SAML attribute for group syncing") :default "member_of") (defsetting saml-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are SAML groups and values are lists of MB groups IDs (deferred-tru "JSON containing SAML to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :saml-group-mappings) validate-group-mappings)) (defn saml-configured? "Check if SAML is enabled and that the mandatory settings are configured." [] (boolean (and (saml-enabled) (saml-identity-provider-uri) (saml-identity-provider-certificate)))) (defsetting jwt-enabled (deferred-tru "Enable JWT based authentication") :type :boolean :default false) (defsetting jwt-identity-provider-uri (deferred-tru "URL of JWT based login page")) (defsetting jwt-shared-secret (deferred-tru "String used to seed the private key used to validate JWT messages") :setter (fn [new-value] (when (seq new-value) (assert (u/hexadecimal-string? new-value) "Invalid JWT Shared Secret key must be a hexadecimal-encoded 256-bit key (i.e., a 64-character string).")) (setting/set-string! :jwt-shared-secret new-value))) (defsetting jwt-attribute-email (deferred-tru "Key to retrieve the JWT user's email address") :default "email") (defsetting jwt-attribute-firstname (deferred-tru "Key to retrieve the JWT user's first name") :default "first_name") (defsetting jwt-attribute-lastname (deferred-tru "Key to retrieve the JWT user's last name") :default "last_name") (defsetting jwt-attribute-groups (deferred-tru "Key to retrieve the JWT user's groups") :default "groups") (defsetting jwt-group-sync (deferred-tru "Enable group membership synchronization with JWT.") :type :boolean :default false) (defsetting jwt-group-mappings ;; Should be in the form: {"groupName": [1, 2, 3]} where keys are JWT groups and values are lists of MB groups IDs (deferred-tru "JSON containing JWT to Metabase group mappings.") :type :json :default {} :setter (comp (partial setting/set-json! :jwt-group-mappings) validate-group-mappings)) (defn jwt-configured? "Check if JWT is enabled and that the mandatory settings are configured." [] (boolean (and (jwt-enabled) (jwt-identity-provider-uri) (jwt-shared-secret)))) (defsetting send-new-sso-user-admin-email? (deferred-tru "Should new email notifications be sent to admins, for all new SSO users?") :type :boolean :default true) (defsetting other-sso-configured? "Are we using an SSO integration other than LDAP or Google Auth? These integrations use the `/auth/sso` endpoint for authorization rather than the normal login form or Google Auth button." :visibility :public :setter :none :getter (fn [] (or (saml-configured?) (jwt-configured?))))
[ { "context": "ap\"\n (read-json test-file) => [{:scientificName \"Aphelandra longiflora\" :latitude 10.10 :longitude 20.20 :locality \"rive", "end": 262, "score": 0.9998844861984253, "start": 241, "tag": "NAME", "value": "Aphelandra longiflora" }, { "context": "n\"}\n {:scientificName \"Vicia faba\" :latitude 30.3 :longitude 8.9 :locality \"\"}])\n\n(", "end": 375, "score": 0.9998784065246582, "start": 365, "tag": "NAME", "value": "Vicia faba" } ]
test/dwc_io/json_test.clj
biodivdev/dwc
0
(ns dwc-io.json-test (:use midje.sweet) (:use [clojure.data.json :only [read-str write-str]]) (:use dwc-io.json)) (def test-file "resources/dwc.json") (fact "Can read json into hash-map" (read-json test-file) => [{:scientificName "Aphelandra longiflora" :latitude 10.10 :longitude 20.20 :locality "riverrun"} {:scientificName "Vicia faba" :latitude 30.3 :longitude 8.9 :locality ""}]) (fact "Can write json" (let [occs (read-json test-file) json (write-json occs)] (read-str json) => (read-str (slurp test-file))))
114725
(ns dwc-io.json-test (:use midje.sweet) (:use [clojure.data.json :only [read-str write-str]]) (:use dwc-io.json)) (def test-file "resources/dwc.json") (fact "Can read json into hash-map" (read-json test-file) => [{:scientificName "<NAME>" :latitude 10.10 :longitude 20.20 :locality "riverrun"} {:scientificName "<NAME>" :latitude 30.3 :longitude 8.9 :locality ""}]) (fact "Can write json" (let [occs (read-json test-file) json (write-json occs)] (read-str json) => (read-str (slurp test-file))))
true
(ns dwc-io.json-test (:use midje.sweet) (:use [clojure.data.json :only [read-str write-str]]) (:use dwc-io.json)) (def test-file "resources/dwc.json") (fact "Can read json into hash-map" (read-json test-file) => [{:scientificName "PI:NAME:<NAME>END_PI" :latitude 10.10 :longitude 20.20 :locality "riverrun"} {:scientificName "PI:NAME:<NAME>END_PI" :latitude 30.3 :longitude 8.9 :locality ""}]) (fact "Can write json" (let [occs (read-json test-file) json (write-json occs)] (read-str json) => (read-str (slurp test-file))))
[ { "context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2", "end": 107, "score": 0.9957491755485535, "start": 98, "tag": "NAME", "value": "Xebia B.V" } ]
src/main/clojure/com/xebia/visualreview/service/service_util.clj
andstepanuk/VisualReview
290
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 Xebia B.V. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.service-util (:require [slingshot.slingshot :as ex] [clojure.tools.logging :as log] [com.xebia.visualreview.util :as util])) (defn get-message-from-object-or-exception [object-or-exception] (if (instance? Exception object-or-exception) (.getMessage object-or-exception) (:message object-or-exception))) (defn throw-service-exception [message code] (ex/throw+ {:type :service-exception :code code :message message})) (defn rethrow-as-service-exception [object-or-exception message code] (let [exception-msg (get-message-from-object-or-exception object-or-exception)] (throw-service-exception (format message exception-msg) code))) (defmacro attempt "Attempts to execute the given form. If the form throws an exception (of either the Java or slingshot kind), it will return a slingshot exception with type 'service-exception', with the given error message and code. Parameter err-msg may contain '%s', which will be replaced by the original exception's message. For example: (attempt (something-that-triggers-an-exception) \"Could not do the thing: %s\" 1234)" [form err-msg err-code] `(ex/try+ ~form (catch Object o# (let [exception-msg# (get-message-from-object-or-exception o#)] (do (log/debug (str "An error has occured and was caught as a service exception: " exception-msg#)) (throw-service-exception (format ~err-msg exception-msg#) ~err-code)))))) (defmacro assume "When the given form returns a falsy value, assume will throw a service exception with the given error message and code. 'Assume' is primarily intended for easy sanity checking of input values for forms in the service layer." [form err-msg err-code] `(when (not ~form) (throw-service-exception ~err-msg ~err-code))) (defn format-dates [run-row] (-> run-row (util/format-date :start-time) (util/format-date :end-time) (util/format-date :creation-time)))
64417
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 <NAME>. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.service-util (:require [slingshot.slingshot :as ex] [clojure.tools.logging :as log] [com.xebia.visualreview.util :as util])) (defn get-message-from-object-or-exception [object-or-exception] (if (instance? Exception object-or-exception) (.getMessage object-or-exception) (:message object-or-exception))) (defn throw-service-exception [message code] (ex/throw+ {:type :service-exception :code code :message message})) (defn rethrow-as-service-exception [object-or-exception message code] (let [exception-msg (get-message-from-object-or-exception object-or-exception)] (throw-service-exception (format message exception-msg) code))) (defmacro attempt "Attempts to execute the given form. If the form throws an exception (of either the Java or slingshot kind), it will return a slingshot exception with type 'service-exception', with the given error message and code. Parameter err-msg may contain '%s', which will be replaced by the original exception's message. For example: (attempt (something-that-triggers-an-exception) \"Could not do the thing: %s\" 1234)" [form err-msg err-code] `(ex/try+ ~form (catch Object o# (let [exception-msg# (get-message-from-object-or-exception o#)] (do (log/debug (str "An error has occured and was caught as a service exception: " exception-msg#)) (throw-service-exception (format ~err-msg exception-msg#) ~err-code)))))) (defmacro assume "When the given form returns a falsy value, assume will throw a service exception with the given error message and code. 'Assume' is primarily intended for easy sanity checking of input values for forms in the service layer." [form err-msg err-code] `(when (not ~form) (throw-service-exception ~err-msg ~err-code))) (defn format-dates [run-row] (-> run-row (util/format-date :start-time) (util/format-date :end-time) (util/format-date :creation-time)))
true
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright 2015 PI:NAME:<NAME>END_PI. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (ns com.xebia.visualreview.service.service-util (:require [slingshot.slingshot :as ex] [clojure.tools.logging :as log] [com.xebia.visualreview.util :as util])) (defn get-message-from-object-or-exception [object-or-exception] (if (instance? Exception object-or-exception) (.getMessage object-or-exception) (:message object-or-exception))) (defn throw-service-exception [message code] (ex/throw+ {:type :service-exception :code code :message message})) (defn rethrow-as-service-exception [object-or-exception message code] (let [exception-msg (get-message-from-object-or-exception object-or-exception)] (throw-service-exception (format message exception-msg) code))) (defmacro attempt "Attempts to execute the given form. If the form throws an exception (of either the Java or slingshot kind), it will return a slingshot exception with type 'service-exception', with the given error message and code. Parameter err-msg may contain '%s', which will be replaced by the original exception's message. For example: (attempt (something-that-triggers-an-exception) \"Could not do the thing: %s\" 1234)" [form err-msg err-code] `(ex/try+ ~form (catch Object o# (let [exception-msg# (get-message-from-object-or-exception o#)] (do (log/debug (str "An error has occured and was caught as a service exception: " exception-msg#)) (throw-service-exception (format ~err-msg exception-msg#) ~err-code)))))) (defmacro assume "When the given form returns a falsy value, assume will throw a service exception with the given error message and code. 'Assume' is primarily intended for easy sanity checking of input values for forms in the service layer." [form err-msg err-code] `(when (not ~form) (throw-service-exception ~err-msg ~err-code))) (defn format-dates [run-row] (-> run-row (util/format-date :start-time) (util/format-date :end-time) (util/format-date :creation-time)))
[ { "context": "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n;; @ Copyright (c) Michael Leachim ", "end": 124, "score": 0.9997662305831909, "start": 109, "tag": "NAME", "value": "Michael Leachim" }, { "context": " @\n;; @@@@@@ At 2018-10-10 17:37 <mklimoff222@gmail.com> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n(ns wirefram", "end": 502, "score": 0.9999294281005859, "start": 481, "tag": "EMAIL", "value": "mklimoff222@gmail.com" } ]
src/wireframe/color.clj
MichaelLeachim/wireframecss
1
;; @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ;; @ Copyright (c) Michael Leachim @ ;; @ You can find additional information regarding licensing of this work in LICENSE.md @ ;; @ You must not remove this notice, or any other, from this software. @ ;; @ All rights reserved. @ ;; @@@@@@ At 2018-10-10 17:37 <mklimoff222@gmail.com> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ (ns wireframe.color (:require [com.evocomputing.colors :as cl] [wireframe.utils :refer [scale-inplace]])) (defn black-font? [color] (> (/ (+ (* 299 (cl/red color)) (* 0.587 (cl/green color)) (* 0.114 (cl/blue color))) 255) 0.5)) (defn string->color [item] (if (and (string? item) (not (empty? item))) (cl/create-color item) item)) (defn color->string [item] (if (= :com.evocomputing.colors/color (type item)) (cl/rgb-hexstr item) item)) (defn- set-hue [color hue] (cl/create-color :h (cl/clamp-hue hue) :s (cl/saturation color) :l (cl/lightness color) :a (cl/alpha color))) (defn- middle-color [color-1 color-2] (let [[color-1 color-2] (if (> (cl/hue color-1) (cl/hue color-2)) [color-1 color-2] [color-2 color-1])] (set-hue color-2 (+ (cl/hue color-2) (/ (- (cl/hue color-1) (cl/hue color-2)) 2))))) (defn- scale-generate [measure op size base] (let [base (string->color base) lightness (measure base)] (for [i (rest (range (inc size)))] (->> (scale-inplace 0 (inc size) 0 lightness i) (op base) (color->string))))) (defn- tints-and-shades [amount color] {:shades (into [] (scale-generate cl/lightness cl/darken amount color)) :tints (into [] (scale-generate cl/lightness cl/lighten amount color)) :lumos (into [] (scale-generate cl/saturation cl/saturate amount color)) :gray (into [] (scale-generate cl/saturation cl/desaturate amount color))}) (defn generate-color [interval base-string] (let [base (string->color base-string) ts (tints-and-shades 5 base)] {:pos {:base (color->string base) :gray (color->string (cl/grayscale base)) :comp (color->string (cl/opposite base)) :near-0 (color->string (cl/adjust-hue base interval)) :near-1 (color->string (cl/adjust-hue base (- interval))) :op-side-0 (color->string (cl/adjust-hue base (- 180 interval))) :op-side-1 (color->string (cl/adjust-hue base (- (- 180 interval))))} :tints (:tints ts) :shades (:shades ts) :lumos (:lumos ts) :gray (:gray ts)})) (comment (map println (generate-color 30 "#3f51b5")) )
46582
;; @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ;; @ Copyright (c) <NAME> @ ;; @ You can find additional information regarding licensing of this work in LICENSE.md @ ;; @ You must not remove this notice, or any other, from this software. @ ;; @ All rights reserved. @ ;; @@@@@@ At 2018-10-10 17:37 <<EMAIL>> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ (ns wireframe.color (:require [com.evocomputing.colors :as cl] [wireframe.utils :refer [scale-inplace]])) (defn black-font? [color] (> (/ (+ (* 299 (cl/red color)) (* 0.587 (cl/green color)) (* 0.114 (cl/blue color))) 255) 0.5)) (defn string->color [item] (if (and (string? item) (not (empty? item))) (cl/create-color item) item)) (defn color->string [item] (if (= :com.evocomputing.colors/color (type item)) (cl/rgb-hexstr item) item)) (defn- set-hue [color hue] (cl/create-color :h (cl/clamp-hue hue) :s (cl/saturation color) :l (cl/lightness color) :a (cl/alpha color))) (defn- middle-color [color-1 color-2] (let [[color-1 color-2] (if (> (cl/hue color-1) (cl/hue color-2)) [color-1 color-2] [color-2 color-1])] (set-hue color-2 (+ (cl/hue color-2) (/ (- (cl/hue color-1) (cl/hue color-2)) 2))))) (defn- scale-generate [measure op size base] (let [base (string->color base) lightness (measure base)] (for [i (rest (range (inc size)))] (->> (scale-inplace 0 (inc size) 0 lightness i) (op base) (color->string))))) (defn- tints-and-shades [amount color] {:shades (into [] (scale-generate cl/lightness cl/darken amount color)) :tints (into [] (scale-generate cl/lightness cl/lighten amount color)) :lumos (into [] (scale-generate cl/saturation cl/saturate amount color)) :gray (into [] (scale-generate cl/saturation cl/desaturate amount color))}) (defn generate-color [interval base-string] (let [base (string->color base-string) ts (tints-and-shades 5 base)] {:pos {:base (color->string base) :gray (color->string (cl/grayscale base)) :comp (color->string (cl/opposite base)) :near-0 (color->string (cl/adjust-hue base interval)) :near-1 (color->string (cl/adjust-hue base (- interval))) :op-side-0 (color->string (cl/adjust-hue base (- 180 interval))) :op-side-1 (color->string (cl/adjust-hue base (- (- 180 interval))))} :tints (:tints ts) :shades (:shades ts) :lumos (:lumos ts) :gray (:gray ts)})) (comment (map println (generate-color 30 "#3f51b5")) )
true
;; @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ;; @ Copyright (c) PI:NAME:<NAME>END_PI @ ;; @ You can find additional information regarding licensing of this work in LICENSE.md @ ;; @ You must not remove this notice, or any other, from this software. @ ;; @ All rights reserved. @ ;; @@@@@@ At 2018-10-10 17:37 <PI:EMAIL:<EMAIL>END_PI> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ (ns wireframe.color (:require [com.evocomputing.colors :as cl] [wireframe.utils :refer [scale-inplace]])) (defn black-font? [color] (> (/ (+ (* 299 (cl/red color)) (* 0.587 (cl/green color)) (* 0.114 (cl/blue color))) 255) 0.5)) (defn string->color [item] (if (and (string? item) (not (empty? item))) (cl/create-color item) item)) (defn color->string [item] (if (= :com.evocomputing.colors/color (type item)) (cl/rgb-hexstr item) item)) (defn- set-hue [color hue] (cl/create-color :h (cl/clamp-hue hue) :s (cl/saturation color) :l (cl/lightness color) :a (cl/alpha color))) (defn- middle-color [color-1 color-2] (let [[color-1 color-2] (if (> (cl/hue color-1) (cl/hue color-2)) [color-1 color-2] [color-2 color-1])] (set-hue color-2 (+ (cl/hue color-2) (/ (- (cl/hue color-1) (cl/hue color-2)) 2))))) (defn- scale-generate [measure op size base] (let [base (string->color base) lightness (measure base)] (for [i (rest (range (inc size)))] (->> (scale-inplace 0 (inc size) 0 lightness i) (op base) (color->string))))) (defn- tints-and-shades [amount color] {:shades (into [] (scale-generate cl/lightness cl/darken amount color)) :tints (into [] (scale-generate cl/lightness cl/lighten amount color)) :lumos (into [] (scale-generate cl/saturation cl/saturate amount color)) :gray (into [] (scale-generate cl/saturation cl/desaturate amount color))}) (defn generate-color [interval base-string] (let [base (string->color base-string) ts (tints-and-shades 5 base)] {:pos {:base (color->string base) :gray (color->string (cl/grayscale base)) :comp (color->string (cl/opposite base)) :near-0 (color->string (cl/adjust-hue base interval)) :near-1 (color->string (cl/adjust-hue base (- interval))) :op-side-0 (color->string (cl/adjust-hue base (- 180 interval))) :op-side-1 (color->string (cl/adjust-hue base (- (- 180 interval))))} :tints (:tints ts) :shades (:shades ts) :lumos (:lumos ts) :gray (:gray ts)})) (comment (map println (generate-color 30 "#3f51b5")) )
[ { "context": "-oidc-callback-request\n (let [password [:cached \"password\"]\n state-map {:redirect-uri \"https://www.t", "end": 1263, "score": 0.9970746636390686, "start": 1255, "tag": "PASSWORD", "value": "password" }, { "context": "llback-request-handler\n (let [password [:cached \"password\"]\n state-map {:redirect-uri \"https://www.t", "end": 7826, "score": 0.6620818376541138, "start": 7818, "tag": "PASSWORD", "value": "password" }, { "context": " :subject \"john.doe\"})\n t/now (constantly (tc/from-l", "end": 9696, "score": 0.9569902420043945, "start": 9688, "tag": "NAME", "value": "john.doe" }, { "context": " :https}\n oidc-authenticator {:password password\n :subject-key subj", "end": 10028, "score": 0.9982770681381226, "start": 10020, "tag": "PASSWORD", "value": "password" }, { "context": " :value [\"john.doe\" current-time-ms {:jwt-access-token access-token}", "end": 10333, "score": 0.9873426556587219, "start": 10325, "tag": "USERNAME", "value": "john.doe" }, { "context": "d :oidc\n :authorization/principal \"john.doe\"\n :authorization/user \"john.doe\"\n ", "end": 10880, "score": 0.9995474219322205, "start": 10872, "tag": "USERNAME", "value": "john.doe" }, { "context": "l \"john.doe\"\n :authorization/user \"john.doe\"\n :authorization/metadata {:jwt-ac", "end": 10927, "score": 0.9989068508148193, "start": 10919, "tag": "USERNAME", "value": "john.doe" }, { "context": " :https}\n oidc-authenticator {:password password\n :subject-key subj", "end": 12238, "score": 0.9986135959625244, "start": 12230, "tag": "PASSWORD", "value": "password" }, { "context": " :https}\n oidc-authenticator {:password password\n :subject-key subj", "end": 13753, "score": 0.9976746439933777, "start": 13745, "tag": "PASSWORD", "value": "password" }, { "context": " :uri \"/test\"}\n password [:cached \"password\"]\n code-verifier \"code-verifier-1234\"\n ", "end": 14514, "score": 0.9472486972808838, "start": 14506, "tag": "PASSWORD", "value": "password" }, { "context": " :authorization/user \"auth-user\"\n :head", "end": 21393, "score": 0.9575474262237549, "start": 21384, "tag": "USERNAME", "value": "auth-user" }, { "context": "dc/authorize\"\n :password [:cached \"test-password\"]}]\n (testing \"valid configuration\"\n (is ", "end": 24991, "score": 0.9966077208518982, "start": 24978, "tag": "PASSWORD", "value": "test-password" } ]
waiter/test/waiter/auth/oidc_test.clj
pandashadopan/waiter
0
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.auth.oidc-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.core.async :as async] [clojure.string :as str] [clojure.test :refer :all] [waiter.auth.jwt :as jwt] [waiter.auth.oidc :refer :all] [waiter.cookie-support :as cookie-support] [waiter.status-codes :refer :all] [waiter.test-helpers :refer :all] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (waiter.auth.oidc OidcAuthenticator))) (deftest test-validate-oidc-callback-request (let [password [:cached "password"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) current-time-ms (System/currentTimeMillis) expired-time-ms (- current-time-ms 10000) not-expired-time-ms (+ current-time-ms 10000)] (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (= {:code access-code :code-verifier (str "decoded:" challenge-cookie) :state-map state-map} (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) (str "decoded:" cookie-value)) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Decoded challenge cookie is invalid" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (str not-expired-time-ms)}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has invalid format" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has expired" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier nil :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier " " :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter code is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter state is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str "foo" "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge cookie set" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=invalid" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Unable to parse state" (validate-oidc-callback-request password request)))) (let [state-map {:callback-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The state query parameter is invalid" (validate-oidc-callback-request password request)))))) (deftest test-oidc-callback-request-handler (let [password [:cached "password"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) access-token (str "access-token-" (rand-int 1000)) subject-key :subject current-time-ms (System/currentTimeMillis) current-time-secs (/ current-time-ms 1000)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (assoc-in response [:cookies name] {:age (int age-in-seconds) :value value})) cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/current-time-secs (constantly current-time-secs) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/extract-claims (constantly {:expiry-time (+ current-time-secs 1000) :subject "john.doe"}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password password :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:cookies {"x-waiter-auth" {:age 1000 :value ["john.doe" current-time-ms {:jwt-access-token access-token}]} "x-waiter-oidc-challenge" {:age 0 :value ""}} :headers {"cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" "https://www.test.com/redirect-uri"} :status http-302-moved-temporarily :authorization/method :oidc :authorization/principal "john.doe" :authorization/user "john.doe" :authorization/metadata {:jwt-access-token access-token} :waiter/response-source :waiter} response)))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/validate-access-token (fn [& _] (throw (ex-info "Created from validate-access-token" {})))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password password :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan (ex-info "Created from request-access-token" {})) result-chan))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password password :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))))) (deftest test-update-oidc-auth-response (let [request-host "www.host.com:8080" request {:headers {"host" request-host} :query-string "some-query-string" :scheme "https" :uri "/test"} password [:cached "password"] code-verifier "code-verifier-1234" state-code "status-4567" oidc-authorize-uri "https://www.test.com:9090/authorize" oidc-auth-server (jwt/->JwtAuthServer nil "jwks-url" (atom nil) oidc-authorize-uri nil) current-time-ms (System/currentTimeMillis)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (is (= challenge-cookie-duration-secs age-in-seconds)) (assoc response :cookie {name value})) utils/unique-identifier (constantly "123456") t/now (constantly (tc/from-long current-time-ms)) create-code-verifier (constantly code-verifier) create-state-code (fn [state-data in-password] (is (= password in-password)) (is (= {:redirect-uri (str "https://" request-host "/test?some-query-string")} state-data)) state-code)] (let [update-response (make-oidc-auth-response-updater oidc-auth-server password request)] (let [response {:body (utils/unique-identifier) :status http-200-ok}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :backend}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :waiter} code-challenge (utils/b64-encode-sha256 code-verifier) redirect-uri-encoded (cookie-support/url-encode (str "https://" request-host oidc-callback-uri)) authorize-uri (str oidc-authorize-uri "?" "client_id=www.host.com&" "code_challenge=" code-challenge "&" "code_challenge_method=S256&" "nonce=123456&" "redirect_uri=" redirect-uri-encoded "&" "response_type=code&" "scope=openid&" "state=" state-code)] (is (= (-> response (assoc :cookie {oidc-challenge-cookie {:code-verifier code-verifier :expiry-time (-> (t/now) (t/plus (t/seconds challenge-cookie-duration-secs)) (tc/to-long))}} :status http-302-moved-temporarily) (update :headers assoc "cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" authorize-uri)) (update-response response)))))))) (deftest test-wrap-auth-handler (with-redefs [trigger-authorize-redirect (fn [_ _ _ response] (assoc response :processed-by :oidc-updater))] (let [request-handler (fn [request] (assoc request :processed-by :request-handler :waiter/response-source :waiter))] (testing "allow oidc authentication combinations" (doseq [allow-oidc-auth-api? [false true]] (doseq [allow-oidc-auth-services? [false true]] (let [oidc-authenticator {:allow-oidc-auth-api? allow-oidc-auth-api? :allow-oidc-auth-services? allow-oidc-auth-services? :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (let [request {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?}] (is (= {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by (if (and (= status http-401-unauthorized) (contains? #{"chrome" "mozilla"} user-agent) (or (and allow-oidc-auth-api? waiter-api-call?) (and allow-oidc-auth-services? (not waiter-api-call?)))) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler request))))))))))) (testing "already authenticated" (let [oidc-authenticator {:allow-oidc-auth-api? false :allow-oidc-auth-services? false :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (is (= {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by :request-handler :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?})))))))) (testing "oidc-enabled and redirect supported" (with-redefs [supports-redirect? (constantly true)] (let [oidc-authenticator {:allow-oidc-auth-api? true :allow-oidc-auth-services? true :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (is (= {:headers {"host" "www.test.com:1234"} :processed-by (if (= status http-401-unauthorized) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:headers {"host" "www.test.com:1234"} :status status :waiter-api-call? waiter-api-call?}))))))))))) (deftest test-supports-redirect? (let [oidc-authority "www.auth.com:1234" supports-redirect-helper? (partial supports-redirect? oidc-authority)] (is (not (supports-redirect-helper? {:headers {"accept-redirect-auth" "www.test.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no" "accept-redirect-auth" oidc-authority}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" "www.auth.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no"}}))) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes"}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" oidc-authority}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority)}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority " www.foo.com")}})) (is (not (supports-redirect-helper? {:headers {"user-agent" "curl"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "jetty"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "python-requests"}}))) (is (supports-redirect-helper? {:headers {"user-agent" "chrome"}})) (is (supports-redirect-helper? {:headers {"user-agent" "mozilla"}})))) (deftest test-create-oidc-authenticator (let [jwt-auth-server (jwt/map->JwtAuthServer {}) jwt-validator (jwt/map->JwtValidator {}) make-jwt-authenticator (fn [config] (create-oidc-authenticator jwt-auth-server jwt-validator config)) config {:oidc-authorize-uri "http://www.test.com/oidc/authorize" :password [:cached "test-password"]}] (testing "valid configuration" (is (instance? OidcAuthenticator (make-jwt-authenticator config))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? false)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? false))))) (testing "invalid configuration" (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-api? "true")))) (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-services? "true")))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :oidc-authorize-uri)))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :password)))))))
80826
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.auth.oidc-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.core.async :as async] [clojure.string :as str] [clojure.test :refer :all] [waiter.auth.jwt :as jwt] [waiter.auth.oidc :refer :all] [waiter.cookie-support :as cookie-support] [waiter.status-codes :refer :all] [waiter.test-helpers :refer :all] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (waiter.auth.oidc OidcAuthenticator))) (deftest test-validate-oidc-callback-request (let [password [:cached "<PASSWORD>"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) current-time-ms (System/currentTimeMillis) expired-time-ms (- current-time-ms 10000) not-expired-time-ms (+ current-time-ms 10000)] (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (= {:code access-code :code-verifier (str "decoded:" challenge-cookie) :state-map state-map} (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) (str "decoded:" cookie-value)) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Decoded challenge cookie is invalid" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (str not-expired-time-ms)}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has invalid format" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has expired" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier nil :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier " " :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter code is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter state is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str "foo" "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge cookie set" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=invalid" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Unable to parse state" (validate-oidc-callback-request password request)))) (let [state-map {:callback-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The state query parameter is invalid" (validate-oidc-callback-request password request)))))) (deftest test-oidc-callback-request-handler (let [password [:cached "<PASSWORD>"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) access-token (str "access-token-" (rand-int 1000)) subject-key :subject current-time-ms (System/currentTimeMillis) current-time-secs (/ current-time-ms 1000)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (assoc-in response [:cookies name] {:age (int age-in-seconds) :value value})) cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/current-time-secs (constantly current-time-secs) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/extract-claims (constantly {:expiry-time (+ current-time-secs 1000) :subject "<NAME>"}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password <PASSWORD> :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:cookies {"x-waiter-auth" {:age 1000 :value ["john.doe" current-time-ms {:jwt-access-token access-token}]} "x-waiter-oidc-challenge" {:age 0 :value ""}} :headers {"cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" "https://www.test.com/redirect-uri"} :status http-302-moved-temporarily :authorization/method :oidc :authorization/principal "john.doe" :authorization/user "john.doe" :authorization/metadata {:jwt-access-token access-token} :waiter/response-source :waiter} response)))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/validate-access-token (fn [& _] (throw (ex-info "Created from validate-access-token" {})))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password <PASSWORD> :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan (ex-info "Created from request-access-token" {})) result-chan))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password <PASSWORD> :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))))) (deftest test-update-oidc-auth-response (let [request-host "www.host.com:8080" request {:headers {"host" request-host} :query-string "some-query-string" :scheme "https" :uri "/test"} password [:cached "<PASSWORD>"] code-verifier "code-verifier-1234" state-code "status-4567" oidc-authorize-uri "https://www.test.com:9090/authorize" oidc-auth-server (jwt/->JwtAuthServer nil "jwks-url" (atom nil) oidc-authorize-uri nil) current-time-ms (System/currentTimeMillis)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (is (= challenge-cookie-duration-secs age-in-seconds)) (assoc response :cookie {name value})) utils/unique-identifier (constantly "123456") t/now (constantly (tc/from-long current-time-ms)) create-code-verifier (constantly code-verifier) create-state-code (fn [state-data in-password] (is (= password in-password)) (is (= {:redirect-uri (str "https://" request-host "/test?some-query-string")} state-data)) state-code)] (let [update-response (make-oidc-auth-response-updater oidc-auth-server password request)] (let [response {:body (utils/unique-identifier) :status http-200-ok}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :backend}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :waiter} code-challenge (utils/b64-encode-sha256 code-verifier) redirect-uri-encoded (cookie-support/url-encode (str "https://" request-host oidc-callback-uri)) authorize-uri (str oidc-authorize-uri "?" "client_id=www.host.com&" "code_challenge=" code-challenge "&" "code_challenge_method=S256&" "nonce=123456&" "redirect_uri=" redirect-uri-encoded "&" "response_type=code&" "scope=openid&" "state=" state-code)] (is (= (-> response (assoc :cookie {oidc-challenge-cookie {:code-verifier code-verifier :expiry-time (-> (t/now) (t/plus (t/seconds challenge-cookie-duration-secs)) (tc/to-long))}} :status http-302-moved-temporarily) (update :headers assoc "cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" authorize-uri)) (update-response response)))))))) (deftest test-wrap-auth-handler (with-redefs [trigger-authorize-redirect (fn [_ _ _ response] (assoc response :processed-by :oidc-updater))] (let [request-handler (fn [request] (assoc request :processed-by :request-handler :waiter/response-source :waiter))] (testing "allow oidc authentication combinations" (doseq [allow-oidc-auth-api? [false true]] (doseq [allow-oidc-auth-services? [false true]] (let [oidc-authenticator {:allow-oidc-auth-api? allow-oidc-auth-api? :allow-oidc-auth-services? allow-oidc-auth-services? :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (let [request {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?}] (is (= {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by (if (and (= status http-401-unauthorized) (contains? #{"chrome" "mozilla"} user-agent) (or (and allow-oidc-auth-api? waiter-api-call?) (and allow-oidc-auth-services? (not waiter-api-call?)))) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler request))))))))))) (testing "already authenticated" (let [oidc-authenticator {:allow-oidc-auth-api? false :allow-oidc-auth-services? false :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (is (= {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by :request-handler :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?})))))))) (testing "oidc-enabled and redirect supported" (with-redefs [supports-redirect? (constantly true)] (let [oidc-authenticator {:allow-oidc-auth-api? true :allow-oidc-auth-services? true :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (is (= {:headers {"host" "www.test.com:1234"} :processed-by (if (= status http-401-unauthorized) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:headers {"host" "www.test.com:1234"} :status status :waiter-api-call? waiter-api-call?}))))))))))) (deftest test-supports-redirect? (let [oidc-authority "www.auth.com:1234" supports-redirect-helper? (partial supports-redirect? oidc-authority)] (is (not (supports-redirect-helper? {:headers {"accept-redirect-auth" "www.test.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no" "accept-redirect-auth" oidc-authority}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" "www.auth.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no"}}))) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes"}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" oidc-authority}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority)}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority " www.foo.com")}})) (is (not (supports-redirect-helper? {:headers {"user-agent" "curl"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "jetty"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "python-requests"}}))) (is (supports-redirect-helper? {:headers {"user-agent" "chrome"}})) (is (supports-redirect-helper? {:headers {"user-agent" "mozilla"}})))) (deftest test-create-oidc-authenticator (let [jwt-auth-server (jwt/map->JwtAuthServer {}) jwt-validator (jwt/map->JwtValidator {}) make-jwt-authenticator (fn [config] (create-oidc-authenticator jwt-auth-server jwt-validator config)) config {:oidc-authorize-uri "http://www.test.com/oidc/authorize" :password [:cached "<PASSWORD>"]}] (testing "valid configuration" (is (instance? OidcAuthenticator (make-jwt-authenticator config))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? false)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? false))))) (testing "invalid configuration" (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-api? "true")))) (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-services? "true")))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :oidc-authorize-uri)))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :password)))))))
true
;; ;; Copyright (c) Two Sigma Open Source, LLC ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;; (ns waiter.auth.oidc-test (:require [clj-time.coerce :as tc] [clj-time.core :as t] [clojure.core.async :as async] [clojure.string :as str] [clojure.test :refer :all] [waiter.auth.jwt :as jwt] [waiter.auth.oidc :refer :all] [waiter.cookie-support :as cookie-support] [waiter.status-codes :refer :all] [waiter.test-helpers :refer :all] [waiter.util.utils :as utils]) (:import (clojure.lang ExceptionInfo) (waiter.auth.oidc OidcAuthenticator))) (deftest test-validate-oidc-callback-request (let [password [:cached "PI:PASSWORD:<PASSWORD>END_PI"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) current-time-ms (System/currentTimeMillis) expired-time-ms (- current-time-ms 10000) not-expired-time-ms (+ current-time-ms 10000)] (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (= {:code access-code :code-verifier (str "decoded:" challenge-cookie) :state-map state-map} (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) (str "decoded:" cookie-value)) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Decoded challenge cookie is invalid" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (str not-expired-time-ms)}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has invalid format" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The challenge cookie has expired" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier nil :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier " " :expiry-time not-expired-time-ms}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge code available from cookie" (validate-oidc-callback-request password request))))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter code is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code)}] (is (thrown-with-msg? ExceptionInfo #"Query parameter state is missing" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str "foo" "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"No challenge cookie set" (validate-oidc-callback-request password request)))) (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=invalid" state-code)}] (is (thrown-with-msg? ExceptionInfo #"Unable to parse state" (validate-oidc-callback-request password request)))) (let [state-map {:callback-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code)}] (is (thrown-with-msg? ExceptionInfo #"The state query parameter is invalid" (validate-oidc-callback-request password request)))))) (deftest test-oidc-callback-request-handler (let [password [:cached "PI:PASSWORD:<PASSWORD>END_PI"] state-map {:redirect-uri "https://www.test.com/redirect-uri"} state-code (create-state-code state-map password) access-code (str "access-code-" (rand-int 1000)) challenge-cookie (str "challenge-cookie-" (rand-int 1000)) access-token (str "access-token-" (rand-int 1000)) subject-key :subject current-time-ms (System/currentTimeMillis) current-time-secs (/ current-time-ms 1000)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (assoc-in response [:cookies name] {:age (int age-in-seconds) :value value})) cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/current-time-secs (constantly current-time-secs) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/extract-claims (constantly {:expiry-time (+ current-time-secs 1000) :subject "PI:NAME:<NAME>END_PI"}) t/now (constantly (tc/from-long current-time-ms))] (let [request {:headers {"cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password PI:PASSWORD:<PASSWORD>END_PI :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:cookies {"x-waiter-auth" {:age 1000 :value ["john.doe" current-time-ms {:jwt-access-token access-token}]} "x-waiter-oidc-challenge" {:age 0 :value ""}} :headers {"cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" "https://www.test.com/redirect-uri"} :status http-302-moved-temporarily :authorization/method :oidc :authorization/principal "john.doe" :authorization/user "john.doe" :authorization/metadata {:jwt-access-token access-token} :waiter/response-source :waiter} response)))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan access-token) result-chan)) jwt/validate-access-token (fn [& _] (throw (ex-info "Created from validate-access-token" {})))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password PI:PASSWORD:<PASSWORD>END_PI :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))) (with-redefs [cookie-support/decode-cookie (fn [cookie-value in-password] (is (= password in-password)) {:code-verifier (str "decoded:" cookie-value) :expiry-time (+ current-time-ms 10000)}) jwt/get-key-id->jwk (constantly {}) jwt/request-access-token (fn [& _] (let [result-chan (async/promise-chan)] (async/>!! result-chan (ex-info "Created from request-access-token" {})) result-chan))] (let [request {:headers {"accept" "application/json" "cookie" (str oidc-challenge-cookie "=" challenge-cookie)} :query-string (str "code=" access-code "&state=" state-code) :scheme :https} oidc-authenticator {:password PI:PASSWORD:<PASSWORD>END_PI :subject-key subject-key} response-chan (oidc-callback-request-handler oidc-authenticator request) response (async/<!! response-chan)] (is (= {:headers {"content-type" "application/json"} :status http-401-unauthorized :waiter/response-source :waiter} (dissoc response :body))) (is (str/includes? (-> response :body str) "Error in retrieving access token")))))) (deftest test-update-oidc-auth-response (let [request-host "www.host.com:8080" request {:headers {"host" request-host} :query-string "some-query-string" :scheme "https" :uri "/test"} password [:cached "PI:PASSWORD:<PASSWORD>END_PI"] code-verifier "code-verifier-1234" state-code "status-4567" oidc-authorize-uri "https://www.test.com:9090/authorize" oidc-auth-server (jwt/->JwtAuthServer nil "jwks-url" (atom nil) oidc-authorize-uri nil) current-time-ms (System/currentTimeMillis)] (with-redefs [cookie-support/add-encoded-cookie (fn [response in-password name value age-in-seconds] (is (= password in-password)) (is (= challenge-cookie-duration-secs age-in-seconds)) (assoc response :cookie {name value})) utils/unique-identifier (constantly "123456") t/now (constantly (tc/from-long current-time-ms)) create-code-verifier (constantly code-verifier) create-state-code (fn [state-data in-password] (is (= password in-password)) (is (= {:redirect-uri (str "https://" request-host "/test?some-query-string")} state-data)) state-code)] (let [update-response (make-oidc-auth-response-updater oidc-auth-server password request)] (let [response {:body (utils/unique-identifier) :status http-200-ok}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :backend}] (is (= response (update-response response)))) (let [response {:body (utils/unique-identifier) :status http-401-unauthorized :waiter/response-source :waiter} code-challenge (utils/b64-encode-sha256 code-verifier) redirect-uri-encoded (cookie-support/url-encode (str "https://" request-host oidc-callback-uri)) authorize-uri (str oidc-authorize-uri "?" "client_id=www.host.com&" "code_challenge=" code-challenge "&" "code_challenge_method=S256&" "nonce=123456&" "redirect_uri=" redirect-uri-encoded "&" "response_type=code&" "scope=openid&" "state=" state-code)] (is (= (-> response (assoc :cookie {oidc-challenge-cookie {:code-verifier code-verifier :expiry-time (-> (t/now) (t/plus (t/seconds challenge-cookie-duration-secs)) (tc/to-long))}} :status http-302-moved-temporarily) (update :headers assoc "cache-control" "no-store" "content-security-policy" "default-src 'none'; frame-ancestors 'none'" "location" authorize-uri)) (update-response response)))))))) (deftest test-wrap-auth-handler (with-redefs [trigger-authorize-redirect (fn [_ _ _ response] (assoc response :processed-by :oidc-updater))] (let [request-handler (fn [request] (assoc request :processed-by :request-handler :waiter/response-source :waiter))] (testing "allow oidc authentication combinations" (doseq [allow-oidc-auth-api? [false true]] (doseq [allow-oidc-auth-services? [false true]] (let [oidc-authenticator {:allow-oidc-auth-api? allow-oidc-auth-api? :allow-oidc-auth-services? allow-oidc-auth-services? :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (let [request {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?}] (is (= {:headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by (if (and (= status http-401-unauthorized) (contains? #{"chrome" "mozilla"} user-agent) (or (and allow-oidc-auth-api? waiter-api-call?) (and allow-oidc-auth-services? (not waiter-api-call?)))) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler request))))))))))) (testing "already authenticated" (let [oidc-authenticator {:allow-oidc-auth-api? false :allow-oidc-auth-services? false :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (doseq [user-agent ["chrome" "mozilla" "jetty" "curl"]] (is (= {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :processed-by :request-handler :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:authorization/principal "auth-principal" :authorization/user "auth-user" :headers {"host" "www.test.com:1234" "user-agent" user-agent} :status status :waiter-api-call? waiter-api-call?})))))))) (testing "oidc-enabled and redirect supported" (with-redefs [supports-redirect? (constantly true)] (let [oidc-authenticator {:allow-oidc-auth-api? true :allow-oidc-auth-services? true :jwt-auth-server (Object.) :oidc-authorize-uri "http://www.test.com/authorize"} oidc-auth-handler (wrap-auth-handler oidc-authenticator request-handler)] (doseq [status [200 301 400 401 403]] (doseq [waiter-api-call? [true false]] (is (= {:headers {"host" "www.test.com:1234"} :processed-by (if (= status http-401-unauthorized) :oidc-updater :request-handler) :status status :waiter-api-call? waiter-api-call? :waiter/response-source :waiter} (oidc-auth-handler {:headers {"host" "www.test.com:1234"} :status status :waiter-api-call? waiter-api-call?}))))))))))) (deftest test-supports-redirect? (let [oidc-authority "www.auth.com:1234" supports-redirect-helper? (partial supports-redirect? oidc-authority)] (is (not (supports-redirect-helper? {:headers {"accept-redirect-auth" "www.test.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no" "accept-redirect-auth" oidc-authority}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" "www.auth.com"}}))) (is (not (supports-redirect-helper? {:headers {"accept-redirect" "no"}}))) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes"}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" oidc-authority}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority)}})) (is (supports-redirect-helper? {:headers {"accept-redirect" "yes" "accept-redirect-auth" (str "www.test.com " oidc-authority " www.foo.com")}})) (is (not (supports-redirect-helper? {:headers {"user-agent" "curl"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "jetty"}}))) (is (not (supports-redirect-helper? {:headers {"user-agent" "python-requests"}}))) (is (supports-redirect-helper? {:headers {"user-agent" "chrome"}})) (is (supports-redirect-helper? {:headers {"user-agent" "mozilla"}})))) (deftest test-create-oidc-authenticator (let [jwt-auth-server (jwt/map->JwtAuthServer {}) jwt-validator (jwt/map->JwtValidator {}) make-jwt-authenticator (fn [config] (create-oidc-authenticator jwt-auth-server jwt-validator config)) config {:oidc-authorize-uri "http://www.test.com/oidc/authorize" :password [:cached "PI:PASSWORD:<PASSWORD>END_PI"]}] (testing "valid configuration" (is (instance? OidcAuthenticator (make-jwt-authenticator config))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-api? false)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? true)))) (is (instance? OidcAuthenticator (make-jwt-authenticator (assoc config :allow-oidc-auth-services? false))))) (testing "invalid configuration" (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-api? "true")))) (is (thrown? Throwable (make-jwt-authenticator (assoc config :allow-oidc-auth-services? "true")))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :oidc-authorize-uri)))) (is (thrown? Throwable (make-jwt-authenticator (dissoc config :password)))))))
[ { "context": ": The user email.\n - `onetime-password`: The user onetime-password.\n Notice that if `onetime-password` is nil, we p", "end": 2228, "score": 0.8092885613441467, "start": 2212, "tag": "PASSWORD", "value": "onetime-password" } ]
src/ohmycards/web/services/login/core.cljs
vitorqb/oh-my-cards-web
1
(ns ohmycards.web.services.login.core (:require [cljs.core.async :as a] [ohmycards.web.kws.http :as kws.http] [ohmycards.web.kws.lenses.login :as lenses.login] [ohmycards.web.kws.services.login.core :as kws] [ohmycards.web.kws.user :as kws.user] [ohmycards.web.services.events-bus.core :as events-bus] [ohmycards.web.services.login.get-token :as get-token] [ohmycards.web.services.login.get-user :as get-user] [ohmycards.web.services.login.onetime-password :as onetime-password] [ohmycards.web.services.login.recover-token-from-cookie :as recover-token-from-cookie] [ohmycards.web.services.logging.core :as logging])) ;; Constants and declarations (declare set-user!) (logging/deflogger log "Services.Login") (def ^:dynamic ^:private *state* "The login state, with the keys described in `ohmycards.web.kws.lenses.login`." nil) (def ^:private onetime-password-url "/api/v1/auth/oneTimePassword") (def actions "Possible login actions (interactions with BE)" #{kws/send-onetime-password-action kws/get-token-action}) ;; Helper functions (defn- try-login-from-cookies! "Tries to log the user in using the browser cookies." [opts] (a/go (log "Trying to log user in using cookies...") (when-let [token (a/<! (recover-token-from-cookie/main! opts))] (log "Token found: " token) (let [user (a/<! (get-user/main! opts token))] (set-user! user))))) (defn- set-finished-loading! [state] (log "Login initialized.") (swap! state assoc lenses.login/initialized? true)) ;; API (defn init! "Initialization logic for the service. Tries to log the user in if he is not yet logged in. `opts.state`: An atom-like variable where we will store the login state. `opts.run-http-action`: A function used to run `ohmycards.web.protocols.http/HttpAction`." [{:keys [state] :as opts}] (log "Initializing...") (set! *state* state) (a/go (a/<! (try-login-from-cookies! opts)) (set-finished-loading! state))) (defn main "Performs login for a given user. - `email`: The user email. - `onetime-password`: The user onetime-password. Notice that if `onetime-password` is nil, we perform the login first step (send the password to the user by email). If it is non-nil, we perform the second step. Returns a channel with: `{::kws/error-message String ::kws/token token}` For `::kws/send-onetime-password`, `::kws/token` is always nil. For `::kws/get-token`, the `::kws/token` contains the token object." [{::kws/keys [onetime-password] :as args} opts] (if onetime-password (get-token/send! args opts) (onetime-password/send! args opts))) (defn set-user! "Set's an user to the state." [user] (log "Setting new user: " user) (swap! *state* assoc lenses.login/current-user user) (events-bus/send! kws/new-user user)) (defn is-logged-in? "Returns true if an user is currently logged in." [] (some? (lenses.login/current-user @*state*)))
62874
(ns ohmycards.web.services.login.core (:require [cljs.core.async :as a] [ohmycards.web.kws.http :as kws.http] [ohmycards.web.kws.lenses.login :as lenses.login] [ohmycards.web.kws.services.login.core :as kws] [ohmycards.web.kws.user :as kws.user] [ohmycards.web.services.events-bus.core :as events-bus] [ohmycards.web.services.login.get-token :as get-token] [ohmycards.web.services.login.get-user :as get-user] [ohmycards.web.services.login.onetime-password :as onetime-password] [ohmycards.web.services.login.recover-token-from-cookie :as recover-token-from-cookie] [ohmycards.web.services.logging.core :as logging])) ;; Constants and declarations (declare set-user!) (logging/deflogger log "Services.Login") (def ^:dynamic ^:private *state* "The login state, with the keys described in `ohmycards.web.kws.lenses.login`." nil) (def ^:private onetime-password-url "/api/v1/auth/oneTimePassword") (def actions "Possible login actions (interactions with BE)" #{kws/send-onetime-password-action kws/get-token-action}) ;; Helper functions (defn- try-login-from-cookies! "Tries to log the user in using the browser cookies." [opts] (a/go (log "Trying to log user in using cookies...") (when-let [token (a/<! (recover-token-from-cookie/main! opts))] (log "Token found: " token) (let [user (a/<! (get-user/main! opts token))] (set-user! user))))) (defn- set-finished-loading! [state] (log "Login initialized.") (swap! state assoc lenses.login/initialized? true)) ;; API (defn init! "Initialization logic for the service. Tries to log the user in if he is not yet logged in. `opts.state`: An atom-like variable where we will store the login state. `opts.run-http-action`: A function used to run `ohmycards.web.protocols.http/HttpAction`." [{:keys [state] :as opts}] (log "Initializing...") (set! *state* state) (a/go (a/<! (try-login-from-cookies! opts)) (set-finished-loading! state))) (defn main "Performs login for a given user. - `email`: The user email. - `onetime-password`: The user <PASSWORD>. Notice that if `onetime-password` is nil, we perform the login first step (send the password to the user by email). If it is non-nil, we perform the second step. Returns a channel with: `{::kws/error-message String ::kws/token token}` For `::kws/send-onetime-password`, `::kws/token` is always nil. For `::kws/get-token`, the `::kws/token` contains the token object." [{::kws/keys [onetime-password] :as args} opts] (if onetime-password (get-token/send! args opts) (onetime-password/send! args opts))) (defn set-user! "Set's an user to the state." [user] (log "Setting new user: " user) (swap! *state* assoc lenses.login/current-user user) (events-bus/send! kws/new-user user)) (defn is-logged-in? "Returns true if an user is currently logged in." [] (some? (lenses.login/current-user @*state*)))
true
(ns ohmycards.web.services.login.core (:require [cljs.core.async :as a] [ohmycards.web.kws.http :as kws.http] [ohmycards.web.kws.lenses.login :as lenses.login] [ohmycards.web.kws.services.login.core :as kws] [ohmycards.web.kws.user :as kws.user] [ohmycards.web.services.events-bus.core :as events-bus] [ohmycards.web.services.login.get-token :as get-token] [ohmycards.web.services.login.get-user :as get-user] [ohmycards.web.services.login.onetime-password :as onetime-password] [ohmycards.web.services.login.recover-token-from-cookie :as recover-token-from-cookie] [ohmycards.web.services.logging.core :as logging])) ;; Constants and declarations (declare set-user!) (logging/deflogger log "Services.Login") (def ^:dynamic ^:private *state* "The login state, with the keys described in `ohmycards.web.kws.lenses.login`." nil) (def ^:private onetime-password-url "/api/v1/auth/oneTimePassword") (def actions "Possible login actions (interactions with BE)" #{kws/send-onetime-password-action kws/get-token-action}) ;; Helper functions (defn- try-login-from-cookies! "Tries to log the user in using the browser cookies." [opts] (a/go (log "Trying to log user in using cookies...") (when-let [token (a/<! (recover-token-from-cookie/main! opts))] (log "Token found: " token) (let [user (a/<! (get-user/main! opts token))] (set-user! user))))) (defn- set-finished-loading! [state] (log "Login initialized.") (swap! state assoc lenses.login/initialized? true)) ;; API (defn init! "Initialization logic for the service. Tries to log the user in if he is not yet logged in. `opts.state`: An atom-like variable where we will store the login state. `opts.run-http-action`: A function used to run `ohmycards.web.protocols.http/HttpAction`." [{:keys [state] :as opts}] (log "Initializing...") (set! *state* state) (a/go (a/<! (try-login-from-cookies! opts)) (set-finished-loading! state))) (defn main "Performs login for a given user. - `email`: The user email. - `onetime-password`: The user PI:PASSWORD:<PASSWORD>END_PI. Notice that if `onetime-password` is nil, we perform the login first step (send the password to the user by email). If it is non-nil, we perform the second step. Returns a channel with: `{::kws/error-message String ::kws/token token}` For `::kws/send-onetime-password`, `::kws/token` is always nil. For `::kws/get-token`, the `::kws/token` contains the token object." [{::kws/keys [onetime-password] :as args} opts] (if onetime-password (get-token/send! args opts) (onetime-password/send! args opts))) (defn set-user! "Set's an user to the state." [user] (log "Setting new user: " user) (swap! *state* assoc lenses.login/current-user user) (events-bus/send! kws/new-user user)) (defn is-logged-in? "Returns true if an user is currently logged in." [] (some? (lenses.login/current-user @*state*)))
[ { "context": " \"form\"}\n [:input {:type \"text\" :name \"username\" :placeholder \"username\"}]\n ]\n ", "end": 602, "score": 0.9992357492446899, "start": 594, "tag": "USERNAME", "value": "username" }, { "context": "nput {:type \"text\" :name \"username\" :placeholder \"username\"}]\n ]\n [:div {:class \"form\"}", "end": 626, "score": 0.9993983507156372, "start": 618, "tag": "USERNAME", "value": "username" }, { "context": "nput {:type \"text\" :name \"password\" :placeholder \"password\"}]\n ]\n [:a {:class \"prettyLi", "end": 750, "score": 0.9992870688438416, "start": 742, "tag": "PASSWORD", "value": "password" }, { "context": "d \"get\"}\n [:input {:type \"text\" :name \"username\"} \"Username\"]\n [:input {:type \"text\" :", "end": 1342, "score": 0.9991719722747803, "start": 1334, "tag": "USERNAME", "value": "username" }, { "context": " [:input {:type \"text\" :name \"username\"} \"Username\"]\n [:input {:type \"text\" :name \"passwo", "end": 1354, "score": 0.9993324279785156, "start": 1346, "tag": "USERNAME", "value": "Username" }, { "context": " [:input {:type \"text\" :name \"password\"} \"Password\"]\n [:input {:type \"submit\" :value \"Log", "end": 1418, "score": 0.9989892244338989, "start": 1410, "tag": "PASSWORD", "value": "Password" }, { "context": "d \"get\"}\n [:input {:type \"text\" :name \"username\"} \"Username\"]\n [:input {:type \"text\" :", "end": 1815, "score": 0.9990846514701843, "start": 1807, "tag": "USERNAME", "value": "username" }, { "context": " [:input {:type \"text\" :name \"username\"} \"Username\"]\n [:input {:type \"text\" :name \"passwo", "end": 1827, "score": 0.999184787273407, "start": 1819, "tag": "USERNAME", "value": "Username" }, { "context": " [:input {:type \"text\" :name \"password\"} \"Password\"]\n [:input {:type \"text\" :name \"email\"", "end": 1891, "score": 0.9740521311759949, "start": 1883, "tag": "PASSWORD", "value": "Password" } ]
src/threat_end/web.clj
lsenjov/threat-end
0
(ns threat-end.web (:require [taoensso.timbre :as log] [threat-end.db :as db] [clojure.data.json :as json] [hiccup.core :refer [html]:as h] ) ) (def css [:link {:rel "stylesheet" :type "text/css" :href "css/style.css"}]) (def logo [:div [:img {:src "img/logo.png" :class "logo"}]]) (defn index [] (html [:html [:head css] [:body [:div {:class "container"} logo [:div {:class "container-sub"} [:h1 "Threat End"]] [:div {:class "form"} [:input {:type "text" :name "username" :placeholder "username"}] ] [:div {:class "form"} [:input {:type "text" :name "password" :placeholder "password"}] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-go"} "Login"] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-stop"} "Register"] ] ] ] ] ) ) ;; Not used for mockup (defn login [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "Password"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn register [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "Password"] [:input {:type "text" :name "email"} "email"] [:input {:type "text" :name "region"} "region"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn forage [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "view-box"} [:div {:class "view-head"} "Forage"] ] [:div {:class "news-img"} [:div [:img {:src "img/historic.png" :class "logo"}]] ] [:div {:class "container-sub"} [:div {:class "news-relationship"} "ANIMALIA / MACROPODIDAE" ] [:div {:class "news-story"} "Historic rock wallaby..." ] ] [:div {:class "container-sub"} [:div {:class "challenge-box"} [:div {:class "challenge-message"} [:h2 "Challenge"] "You have a new challenge for the Petrogale" ] [:div {:class "challenge-link"} ] ] ] [:div {:class "container-sub"} "Suggested Species"] [:a {:href "apilinks"} [:div {:class "container-sub"} "Api Demonstrations"] ] ] ] ] ) ) (defn api-examples [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} [:a {:href "./api/species/nearby/152.7528/-27.6188/1000/"} "Show all nearby species sightings within 1000 metres of a coordinate" [:br] "/threatend/api/species/nearby/:xcoord/:ycoord/:distMetres/" ] ] [:div {:class "container-sub"} [:a {:href "./api/species/scientific/manorina melanocephala/"} "Get json data for a single species" [:br] "/threatend/api/species/scientific/:speciesName/" ] ] ] ] ] ) )
31697
(ns threat-end.web (:require [taoensso.timbre :as log] [threat-end.db :as db] [clojure.data.json :as json] [hiccup.core :refer [html]:as h] ) ) (def css [:link {:rel "stylesheet" :type "text/css" :href "css/style.css"}]) (def logo [:div [:img {:src "img/logo.png" :class "logo"}]]) (defn index [] (html [:html [:head css] [:body [:div {:class "container"} logo [:div {:class "container-sub"} [:h1 "Threat End"]] [:div {:class "form"} [:input {:type "text" :name "username" :placeholder "username"}] ] [:div {:class "form"} [:input {:type "text" :name "password" :placeholder "<PASSWORD>"}] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-go"} "Login"] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-stop"} "Register"] ] ] ] ] ) ) ;; Not used for mockup (defn login [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "<PASSWORD>"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn register [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "<PASSWORD>"] [:input {:type "text" :name "email"} "email"] [:input {:type "text" :name "region"} "region"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn forage [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "view-box"} [:div {:class "view-head"} "Forage"] ] [:div {:class "news-img"} [:div [:img {:src "img/historic.png" :class "logo"}]] ] [:div {:class "container-sub"} [:div {:class "news-relationship"} "ANIMALIA / MACROPODIDAE" ] [:div {:class "news-story"} "Historic rock wallaby..." ] ] [:div {:class "container-sub"} [:div {:class "challenge-box"} [:div {:class "challenge-message"} [:h2 "Challenge"] "You have a new challenge for the Petrogale" ] [:div {:class "challenge-link"} ] ] ] [:div {:class "container-sub"} "Suggested Species"] [:a {:href "apilinks"} [:div {:class "container-sub"} "Api Demonstrations"] ] ] ] ] ) ) (defn api-examples [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} [:a {:href "./api/species/nearby/152.7528/-27.6188/1000/"} "Show all nearby species sightings within 1000 metres of a coordinate" [:br] "/threatend/api/species/nearby/:xcoord/:ycoord/:distMetres/" ] ] [:div {:class "container-sub"} [:a {:href "./api/species/scientific/manorina melanocephala/"} "Get json data for a single species" [:br] "/threatend/api/species/scientific/:speciesName/" ] ] ] ] ] ) )
true
(ns threat-end.web (:require [taoensso.timbre :as log] [threat-end.db :as db] [clojure.data.json :as json] [hiccup.core :refer [html]:as h] ) ) (def css [:link {:rel "stylesheet" :type "text/css" :href "css/style.css"}]) (def logo [:div [:img {:src "img/logo.png" :class "logo"}]]) (defn index [] (html [:html [:head css] [:body [:div {:class "container"} logo [:div {:class "container-sub"} [:h1 "Threat End"]] [:div {:class "form"} [:input {:type "text" :name "username" :placeholder "username"}] ] [:div {:class "form"} [:input {:type "text" :name "password" :placeholder "PI:PASSWORD:<PASSWORD>END_PI"}] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-go"} "Login"] ] [:a {:class "prettyLink" :href "forage"} [:div {:class "but-stop"} "Register"] ] ] ] ] ) ) ;; Not used for mockup (defn login [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "PI:PASSWORD:<PASSWORD>END_PI"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn register [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} "Login"] logo [:form {:action "forage" :method "get"} [:input {:type "text" :name "username"} "Username"] [:input {:type "text" :name "password"} "PI:PASSWORD:<PASSWORD>END_PI"] [:input {:type "text" :name "email"} "email"] [:input {:type "text" :name "region"} "region"] [:input {:type "submit" :value "Log In"}] ] ] ] ] ) ) (defn forage [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "view-box"} [:div {:class "view-head"} "Forage"] ] [:div {:class "news-img"} [:div [:img {:src "img/historic.png" :class "logo"}]] ] [:div {:class "container-sub"} [:div {:class "news-relationship"} "ANIMALIA / MACROPODIDAE" ] [:div {:class "news-story"} "Historic rock wallaby..." ] ] [:div {:class "container-sub"} [:div {:class "challenge-box"} [:div {:class "challenge-message"} [:h2 "Challenge"] "You have a new challenge for the Petrogale" ] [:div {:class "challenge-link"} ] ] ] [:div {:class "container-sub"} "Suggested Species"] [:a {:href "apilinks"} [:div {:class "container-sub"} "Api Demonstrations"] ] ] ] ] ) ) (defn api-examples [] (html [:html [:head css] [:body [:div {:class "container"} [:div {:class "container-sub"} [:a {:href "./api/species/nearby/152.7528/-27.6188/1000/"} "Show all nearby species sightings within 1000 metres of a coordinate" [:br] "/threatend/api/species/nearby/:xcoord/:ycoord/:distMetres/" ] ] [:div {:class "container-sub"} [:a {:href "./api/species/scientific/manorina melanocephala/"} "Get json data for a single species" [:br] "/threatend/api/species/scientific/:speciesName/" ] ] ] ] ] ) )
[ { "context": ";; Copyright 2015 Ben Ashford\n;;\n;; Licensed under the Apache License, Version ", "end": 29, "score": 0.9998711943626404, "start": 18, "tag": "NAME", "value": "Ben Ashford" } ]
src/redis_async/scripting.clj
benashford/redis-async
19
;; Copyright 2015 Ben Ashford ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns redis-async.scripting (:require [clojure.core.async :as a] [redis-async.core :as core] [redis-async.client :as client] [redis-async.protocol :as protocol])) (def ^:private misc (atom {})) (defn script-name->sha [pool script-name] (get-in @misc [pool :scripts script-name])) (defn save-script [pool script-name script-body] (if script-body (a/go (let [result (a/<! (client/script-load pool script-body))] (if-not (core/is-error? result) (swap! misc assoc-in [pool :scripts script-name] (protocol/->clj result))) result)) (throw (ex-info "No script provided" {:name script-name})))) (defn call-saved-script [pool sha keys args] (apply client/evalsha pool sha (count keys) (concat keys args))) (defmacro defscript [script-name script-body] (let [script-name-str (name script-name)] `(defn ~script-name ([pool#] (~script-name pool# [] [])) ([pool# keys#] (~script-name pool# keys# [])) ([pool# keys# args#] (if-let [sha# (script-name->sha pool# ~script-name-str)] (call-saved-script pool# sha# keys# args#) (a/go (let [sha# (a/<! (save-script pool# ~script-name-str ~script-body))] (if (core/is-error? sha#) sha# (a/<! (call-saved-script pool# (protocol/->clj sha#) keys# args#)))))))))) (defn from "Convenience function to load a script into a String so it can be defined with defscript" [path-to-script] (when-let [script-url (clojure.java.io/resource path-to-script)] (slurp script-url)))
63981
;; Copyright 2015 <NAME> ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns redis-async.scripting (:require [clojure.core.async :as a] [redis-async.core :as core] [redis-async.client :as client] [redis-async.protocol :as protocol])) (def ^:private misc (atom {})) (defn script-name->sha [pool script-name] (get-in @misc [pool :scripts script-name])) (defn save-script [pool script-name script-body] (if script-body (a/go (let [result (a/<! (client/script-load pool script-body))] (if-not (core/is-error? result) (swap! misc assoc-in [pool :scripts script-name] (protocol/->clj result))) result)) (throw (ex-info "No script provided" {:name script-name})))) (defn call-saved-script [pool sha keys args] (apply client/evalsha pool sha (count keys) (concat keys args))) (defmacro defscript [script-name script-body] (let [script-name-str (name script-name)] `(defn ~script-name ([pool#] (~script-name pool# [] [])) ([pool# keys#] (~script-name pool# keys# [])) ([pool# keys# args#] (if-let [sha# (script-name->sha pool# ~script-name-str)] (call-saved-script pool# sha# keys# args#) (a/go (let [sha# (a/<! (save-script pool# ~script-name-str ~script-body))] (if (core/is-error? sha#) sha# (a/<! (call-saved-script pool# (protocol/->clj sha#) keys# args#)))))))))) (defn from "Convenience function to load a script into a String so it can be defined with defscript" [path-to-script] (when-let [script-url (clojure.java.io/resource path-to-script)] (slurp script-url)))
true
;; Copyright 2015 PI:NAME:<NAME>END_PI ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns redis-async.scripting (:require [clojure.core.async :as a] [redis-async.core :as core] [redis-async.client :as client] [redis-async.protocol :as protocol])) (def ^:private misc (atom {})) (defn script-name->sha [pool script-name] (get-in @misc [pool :scripts script-name])) (defn save-script [pool script-name script-body] (if script-body (a/go (let [result (a/<! (client/script-load pool script-body))] (if-not (core/is-error? result) (swap! misc assoc-in [pool :scripts script-name] (protocol/->clj result))) result)) (throw (ex-info "No script provided" {:name script-name})))) (defn call-saved-script [pool sha keys args] (apply client/evalsha pool sha (count keys) (concat keys args))) (defmacro defscript [script-name script-body] (let [script-name-str (name script-name)] `(defn ~script-name ([pool#] (~script-name pool# [] [])) ([pool# keys#] (~script-name pool# keys# [])) ([pool# keys# args#] (if-let [sha# (script-name->sha pool# ~script-name-str)] (call-saved-script pool# sha# keys# args#) (a/go (let [sha# (a/<! (save-script pool# ~script-name-str ~script-body))] (if (core/is-error? sha#) sha# (a/<! (call-saved-script pool# (protocol/->clj sha#) keys# args#)))))))))) (defn from "Convenience function to load a script into a String so it can be defined with defscript" [path-to-script] (when-let [script-url (clojure.java.io/resource path-to-script)] (slurp script-url)))
[ { "context": " valid real credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 330, "score": 0.7253270149230957, "start": 326, "tag": "KEY", "value": "abcd" }, { "context": "id real credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 331, "score": 0.5332542061805725, "start": 330, "tag": "PASSWORD", "value": "7" }, { "context": "d real credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 332, "score": 0.4941321611404419, "start": 331, "tag": "KEY", "value": "d" }, { "context": " real credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 333, "score": 0.5334050059318542, "start": 332, "tag": "PASSWORD", "value": "7" }, { "context": "real credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 337, "score": 0.5477830171585083, "start": 333, "tag": "KEY", "value": "8-c8" }, { "context": " credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n ", "end": 338, "score": 0.5021466016769409, "start": 337, "tag": "PASSWORD", "value": "7" }, { "context": "credentials.\n (define-credentials \"abcd7d78-c874-47d9-a829-ccaa51ae75c9\"\n \"-----BEGIN RSA PRIVATE ", "end": 362, "score": 0.5794423222541809, "start": 338, "tag": "KEY", "value": "4-47d9-a829-ccaa51ae75c9" }, { "context": " \"-----BEGIN RSA PRIVATE KEY-----\n MIIEowIBAAKCAQEAsaa4gcNl4jx9YF7Y/6B+v29c0KBs1vxym", "end": 415, "score": 0.6409581899642944, "start": 415, "tag": "KEY", "value": "" }, { "context": "BEGIN RSA PRIVATE KEY-----\n MIIEowIBAAKCAQEAsaa4gcNl4jx9YF7Y/6B+v29c0KBs1vxym0p4hwjZl5GteQgR\n uFW5wM93F2lUFiVEQoM+Ti3AQjEDWdeuOIfo66LgbNLH7B3JhbkwHti/bMsq7T66\n Gs3cOhMcKDrTswOv8x72QzsOf1FNs7Yzsu1iwJpttNg+VCRj169hQ/YI39KSuYzQ\n aXdjK0++EPsFtr2fU7E4cHGCDlAr8Tgt2gY8xmIuLF513jqJ2fhurja+YZriGwuO\n qdBDLVpJOB1iz8bQ1CGMMGbkYl64jfsMHMBeueP9RyZ50I2Jrr8v05qG2dYDeQYn\n d7BjAy2VLiWewRFQRltMOWC3nbZAla+282J/swIDAQABAoIBAAvPfrK5z9szlE5E\n 3/5WqDaH686+6517WQ8z60Fm+DhYagUC4VK0+E12PX+j9AAo6BnX6dt+tSpxYbym\n VyHQ/04zHOJ/POVYsZ4fSrCyT", "end": 1043, "score": 0.8461796641349792, "start": 445, "tag": "KEY", "value": "MIIEowIBAAKCAQEAsaa4gcNl4jx9YF7Y/6B+v29c0KBs1vxym0p4hwjZl5GteQgR\n uFW5wM93F2lUFiVEQoM+Ti3AQjEDWdeuOIfo66LgbNLH7B3JhbkwHti/bMsq7T66\n Gs3cOhMcKDrTswOv8x72QzsOf1FNs7Yzsu1iwJpttNg+VCRj169hQ/YI39KSuYzQ\n aXdjK0++EPsFtr2fU7E4cHGCDlAr8Tgt2gY8xmIuLF513jqJ2fhurja+YZriGwuO\n qdBDLVpJOB1iz8bQ1CGMMGbkYl64jfsMHMBeueP9RyZ50I2Jrr8v05qG2dYDeQYn\n d7BjAy2VLiWewRFQRltMOWC3nbZAla+282J/swIDAQABAoIBAAvPfrK5z9szlE5E\n 3/5WqDaH686+6517WQ8z60Fm+DhYagUC4VK0+E12PX+j9AAo6BnX6dt+tSpxYbym" }, { "context": "12PX+j9AAo6BnX6dt+tSpxYbym\n VyHQ/04zHOJ/POVYsZ4fSrCyTj+oXik5o1vG1d5SiOuvxYVAOIFcTJj5oyQZvqW0\n ", "end": 1085, "score": 0.6873061060905457, "start": 1068, "tag": "KEY", "value": "VyHQ/04zHOJ/POVYs" }, { "context": "SpxYbym\n VyHQ/04zHOJ/POVYsZ4fSrCyTj+oXik5o1vG1d5SiOuvxYVAOIFcTJj5oyQZvqW0\n ", "end": 1087, "score": 0.5766646862030029, "start": 1086, "tag": "KEY", "value": "4" }, { "context": "bym\n VyHQ/04zHOJ/POVYsZ4fSrCyTj+oXik5o1vG1d5SiOuvxYVAOIFcTJj5oyQZvqW0\n ", "end": 1095, "score": 0.5548101663589478, "start": 1090, "tag": "KEY", "value": "CyTj+" }, { "context": "04zHOJ/POVYsZ4fSrCyTj+oXik5o1vG1d5SiOuvxYVAOIFcTJj5oyQZvqW0\n 9kjt+UO+wI5mVfZ4GN8s/LVs9PgURmYiSzy9Ed43kc4p9pSLQ448f7mnv134WknT\n l/2z5/+q0DXj2Nx/JV0OsTR5KV4b0u87aSNrRldcKnfOWK9BubP4T9yGMjPyeuZP\n XA0UQMRlGpql8I+4rRvdHio+N2lpHsFDzd7ckmjWMjXdeU2dGhE6580YbEpuLQRb\n SN86ylkCgYEA3d/0W2S4wtmbV4X9AhLDe4vWLP1GmMcmcZ2wwuljEK14xNdeYzyD\n z42PZ6RsGtAtdUHe6/e+7TRpz/f938f4ygawCV7zXkF65bPm54zz9o7+CM9p4P3V\n AntDVO5IskiE6hb5A7wR0UdRNLDhov38Ngh+iUEDJ9MuZ75GWj6UbGcCgYEAzPmE\n om9eaDC3g2hmBwTB54bAMgskRT9sdaFFJtMHx7VU0xw9E34qfD17o0LDa9n62TDv\n getytWnluzwyhRw6UPhzseQw6", "end": 1755, "score": 0.6294983625411987, "start": 1123, "tag": "KEY", "value": "5oyQZvqW0\n 9kjt+UO+wI5mVfZ4GN8s/LVs9PgURmYiSzy9Ed43kc4p9pSLQ448f7mnv134WknT\n l/2z5/+q0DXj2Nx/JV0OsTR5KV4b0u87aSNrRldcKnfOWK9BubP4T9yGMjPyeuZP\n XA0UQMRlGpql8I+4rRvdHio+N2lpHsFDzd7ckmjWMjXdeU2dGhE6580YbEpuLQRb\n SN86ylkCgYEA3d/0W2S4wtmbV4X9AhLDe4vWLP1GmMcmcZ2wwuljEK14xNdeYzyD\n z42PZ6RsGtAtdUHe6/e+7TRpz/f938f4ygawCV7zXkF65bPm54zz9o7+CM9p4P3V\n AntDVO5IskiE6hb5A7wR0UdRNLDhov38Ngh+iUEDJ9MuZ75GWj6UbGcCgYEAzPmE\n om9eaDC3g2hmBwTB54bAMgskRT9sdaFFJtMHx7VU0xw9E34qfD17o0LDa9n62TDv" }, { "context": "w9E34qfD17o0LDa9n62TDv\n getytWnluzwyhRw6UPhzseQw6R+7wtLlLPAj9mC58l34ONXwPSME0Exp/9WAVErt\n Z0Ng6xPmifesQ/fSUM52aCIgu", "end": 1844, "score": 0.5917530059814453, "start": 1783, "tag": "KEY", "value": "ytWnluzwyhRw6UPhzseQw6R+7wtLlLPAj9mC58l34ONXwPSME0Exp/9WAVErt" }, { "context": "8l34ONXwPSME0Exp/9WAVErt\n Z0Ng6xPmifesQ/fSUM52aCIgufyQOQ1zCx9ogtUCgYBotpOKtqSEQVMRIYlg+x4L\n Jtnz7azt2b+JC5UqyB8a9ePzc", "end": 1933, "score": 0.6092745065689087, "start": 1870, "tag": "KEY", "value": "0Ng6xPmifesQ/fSUM52aCIgufyQOQ1zCx9ogtUCgYBotpOKtqSEQVMRIYlg+x4L" }, { "context": "gYBotpOKtqSEQVMRIYlg+x4L\n Jtnz7azt2b+JC5UqyB8a9ePzcnl3eE31HKg7j9v9Y5awql/dGdWf+Yaewjms7aG7\n JyDZq1hMebbYxekKCvnwuVenL", "end": 2022, "score": 0.593429446220398, "start": 1959, "tag": "KEY", "value": "tnz7azt2b+JC5UqyB8a9ePzcnl3eE31HKg7j9v9Y5awql/dGdWf+Yaewjms7aG7" }, { "context": "Y5awql/dGdWf+Yaewjms7aG7\n JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3J", "end": 2053, "score": 0.5181694030761719, "start": 2048, "tag": "KEY", "value": "yDZq1" }, { "context": "/dGdWf+Yaewjms7aG7\n JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYl", "end": 2055, "score": 0.5105640888214111, "start": 2054, "tag": "KEY", "value": "M" }, { "context": "f+Yaewjms7aG7\n JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds\n", "end": 2062, "score": 0.5104800462722778, "start": 2059, "tag": "KEY", "value": "xek" }, { "context": "ms7aG7\n JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds\n ", "end": 2071, "score": 0.5217937231063843, "start": 2066, "tag": "KEY", "value": "wuVen" }, { "context": " JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds\n ", "end": 2076, "score": 0.5485434532165527, "start": 2074, "tag": "KEY", "value": "Zh" }, { "context": " JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds\n ", "end": 2082, "score": 0.5177462100982666, "start": 2081, "tag": "KEY", "value": "O" }, { "context": " JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds\n 8OFXQbmNiBt0ltZ5LOO7rQKBgB1/HrYdXrGRqSbw5BXIenrt6kSJU+vfJ6V50rC2\n l50GnDFRE/z1H/oHAv7IgcTIdo/AugaxMi2nEpcyH3cGS+IRDt0foGY72dI8dRxV\n ZmdzHe8h1LGhH9Q8cNnk1TAqsi/vJGDC0nShxYA/MvwI8qwMOf/cQWdiUALVy6Nj\n HrANAoGBAIK6Lh0mZLtan60F1rUoXqME7yIGQgf/cP+RKLwE36kqF5DQx9aFwPZx\n 9aWuKH+/XjdHf/J1n/AQ1j/G/WExs3UNfrvDgYea5QDnvc2gMBDRkdBwFZHYZLIn\n e+viqMbgmORJDP/8vbpd0yZjT25ImysJE5cSCGiqHOotDs3jdlUX\n -----END RSA PRIVATE KEY-", "end": 2633, "score": 0.9284476041793823, "start": 2085, "tag": "KEY", "value": "PDkHo6SJFJc+8sx+3JYll7JUds\n 8OFXQbmNiBt0ltZ5LOO7rQKBgB1/HrYdXrGRqSbw5BXIenrt6kSJU+vfJ6V50rC2\n l50GnDFRE/z1H/oHAv7IgcTIdo/AugaxMi2nEpcyH3cGS+IRDt0foGY72dI8dRxV\n ZmdzHe8h1LGhH9Q8cNnk1TAqsi/vJGDC0nShxYA/MvwI8qwMOf/cQWdiUALVy6Nj\n HrANAoGBAIK6Lh0mZLtan60F1rUoXqME7yIGQgf/cP+RKLwE36kqF5DQx9aFwPZx\n 9aWuKH+/XjdHf/J1n/AQ1j/G/WExs3UNfrvDgYea5QDnvc2gMBDRkdBwFZHYZLIn\n e+viqMbgmORJDP/8vbpd0yZjT25ImysJE5cSCGiqHOotDs3jdlUX" }, { "context": "WS-Authentication\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE", "end": 4280, "score": 0.5090316534042358, "start": 4278, "tag": "KEY", "value": "aa" }, { "context": "tication\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd", "end": 4288, "score": 0.5627657175064087, "start": 4287, "tag": "KEY", "value": "9" }, { "context": "ation\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==\"\n \"X-MWS-Time\" \"153", "end": 4634, "score": 0.9287694692611694, "start": 4290, "tag": "KEY", "value": "I/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==\"" }, { "context": "ation\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==\"\n \"X-MWS-Time\" \"153", "end": 5324, "score": 0.9415642023086548, "start": 4980, "tag": "KEY", "value": "I/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==\"" }, { "context": "cation\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:kYZR1udBwE02ct55cSWq5MZuGsC6xgVmK6TWYQ/+2IAbhqG7jZWhP95bPxTqo1f12XUWsX/oeUAp8jhvdUcsXsjVMeBwvQNgnC/HP1TNQasC2LMGfOs76WnsfKoV5zWDh+SNqMqn4pIXce3DALG9d/FB2Uu4mIg9kgQIUnfJJDljfLMjR7aMgDINPU7ToM51TqTJh+ReG7LAVwsEzSwFfj4zZFFpx8XrWn3inx5ZUvT7YcFhW4vOZaeI48HSnj80bCf1LDtWXzU7yk9gon+AlIYBTtrPQTSqyofBGZUtZCBexnoEp6NUhk5XkwqK56jizT7PZCN094kh1eofr3hSTg==\"\n \"X-MWS-Time\" \"153", "end": 6021, "score": 0.9380262494087219, "start": 5676, "tag": "KEY", "value": "kYZR1udBwE02ct55cSWq5MZuGsC6xgVmK6TWYQ/+2IAbhqG7jZWhP95bPxTqo1f12XUWsX/oeUAp8jhvdUcsXsjVMeBwvQNgnC/HP1TNQasC2LMGfOs76WnsfKoV5zWDh+SNqMqn4pIXce3DALG9d/FB2Uu4mIg9kgQIUnfJJDljfLMjR7aMgDINPU7ToM51TqTJh+ReG7LAVwsEzSwFfj4zZFFpx8XrWn3inx5ZUvT7YcFhW4vOZaeI48HSnj80bCf1LDtWXzU7yk9gon+AlIYBTtrPQTSqyofBGZUtZCBexnoEp6NUhk5XkwqK56jizT7PZCN094kh1eofr3hSTg==\"" }, { "context": "cation\" \"MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:IzAzkGyzDtxbMlCbbWViYen/9o54B9Ijlnp1UoSIysGr/axJWwph8KRYukS+3DhYFJIBLbS1PfWI74kRTkWJl3Vmb0XgxiRfNCqresqh687ELlhNDt66p2mu/6LaVwbDKUBsIAwkQFomVfAOy3jckWZjHRySD+VABfDf4BAf5hfjTUgil63oOnH6xII51e6M160SFRz1/HpsMU/rnReniPJs22MwiqS6dhe3oU/DAzteawxujSdFA3i6Fol6kdJQN19w+0TTdOSbccjds1Wljqu/+E1ju1rXVAgcL0GuVg4dsCwrjSPY9VWfQOttpA4aHavGWNcPMh1p1kSmqlNa1g==\"\n \"X-MWS-Time\" \"153", "end": 6734, "score": 0.9830359816551208, "start": 6389, "tag": "KEY", "value": "IzAzkGyzDtxbMlCbbWViYen/9o54B9Ijlnp1UoSIysGr/axJWwph8KRYukS+3DhYFJIBLbS1PfWI74kRTkWJl3Vmb0XgxiRfNCqresqh687ELlhNDt66p2mu/6LaVwbDKUBsIAwkQFomVfAOy3jckWZjHRySD+VABfDf4BAf5hfjTUgil63oOnH6xII51e6M160SFRz1/HpsMU/rnReniPJs22MwiqS6dhe3oU/DAzteawxujSdFA3i6Fol6kdJQN19w+0TTdOSbccjds1Wljqu/+E1ju1rXVAgcL0GuVg4dsCwrjSPY9VWfQOttpA4aHavGWNcPMh1p1kSmqlNa1g==\"" }, { "context": "WS abcd7d78-c874-47d9-a829-ccaa51ae75c9:W+hIOQKAp0aEwDthAVaMa5ysJB8ddQdJdTWNonQoDuPEBVAY7F6GUXNoAZCYcos", "end": 7084, "score": 0.5350781679153442, "start": 7081, "tag": "KEY", "value": "aEw" }, { "context": "d78-c874-47d9-a829-ccaa51ae75c9:W+hIOQKAp0aEwDthAVaMa5ysJB8ddQdJdTWNonQoDuPEBVAY7F6GUXNoAZCYcosxgbm2rfp", "end": 7092, "score": 0.6109935641288757, "start": 7089, "tag": "KEY", "value": "aMa" }, { "context": "74-47d9-a829-ccaa51ae75c9:W+hIOQKAp0aEwDthAVaMa5ysJB8ddQdJdTWNonQoDuPEBVAY7F6GUXNoAZCYcosxgbm2rfpwyfLrS7U5b77GMFpnvvUwUSCgRziZNvfhuZfWUuW9po7OkWQUXCDvd/NtJdLOu6o1bKCGHYKjdaw/8AVH876afGyPF7+Ce2vD+YFRfY+zXF0MVWiS2WfwUwLSdOXb+Csnb21XT59zDs8qBg0gUj6WagZiJ+hYTbAt1zcNCdqs/mVt5hKA7ASxB9VY7GI4QM/n0EoyC/ruUm8DYS7kkxuxKeZuNkvpexFR4IPXQax1q7EtCIgw4yekegK210uxxYoOf+EBV2wMIVpKvw==\"\n \"X-MWS-Time\" \"153", "end": 7416, "score": 0.9258646368980408, "start": 7095, "tag": "KEY", "value": "JB8ddQdJdTWNonQoDuPEBVAY7F6GUXNoAZCYcosxgbm2rfpwyfLrS7U5b77GMFpnvvUwUSCgRziZNvfhuZfWUuW9po7OkWQUXCDvd/NtJdLOu6o1bKCGHYKjdaw/8AVH876afGyPF7+Ce2vD+YFRfY+zXF0MVWiS2WfwUwLSdOXb+Csnb21XT59zDs8qBg0gUj6WagZiJ+hYTbAt1zcNCdqs/mVt5hKA7ASxB9VY7GI4QM/n0EoyC/ruUm8DYS7kkxuxKeZuNkvpexFR4IPXQax1q7EtCIgw4yekegK210uxxYoOf+EBV2wMIVpKvw==\"" } ]
test/clojure_mauth_client/request_test.clj
mdsol/clojure-mauth-client
0
(ns clojure-mauth-client.request-test (:require [clojure.test :refer :all] [clojure-mauth-client.request :refer :all] [clojure.data.json :as json]) (:use [clojure-mauth-client.credentials])) (use-fixtures :once (fn [f] ;Note: these are NOT valid real credentials. (define-credentials "abcd7d78-c874-47d9-a829-ccaa51ae75c9" "-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAsaa4gcNl4jx9YF7Y/6B+v29c0KBs1vxym0p4hwjZl5GteQgR uFW5wM93F2lUFiVEQoM+Ti3AQjEDWdeuOIfo66LgbNLH7B3JhbkwHti/bMsq7T66 Gs3cOhMcKDrTswOv8x72QzsOf1FNs7Yzsu1iwJpttNg+VCRj169hQ/YI39KSuYzQ aXdjK0++EPsFtr2fU7E4cHGCDlAr8Tgt2gY8xmIuLF513jqJ2fhurja+YZriGwuO qdBDLVpJOB1iz8bQ1CGMMGbkYl64jfsMHMBeueP9RyZ50I2Jrr8v05qG2dYDeQYn d7BjAy2VLiWewRFQRltMOWC3nbZAla+282J/swIDAQABAoIBAAvPfrK5z9szlE5E 3/5WqDaH686+6517WQ8z60Fm+DhYagUC4VK0+E12PX+j9AAo6BnX6dt+tSpxYbym VyHQ/04zHOJ/POVYsZ4fSrCyTj+oXik5o1vG1d5SiOuvxYVAOIFcTJj5oyQZvqW0 9kjt+UO+wI5mVfZ4GN8s/LVs9PgURmYiSzy9Ed43kc4p9pSLQ448f7mnv134WknT l/2z5/+q0DXj2Nx/JV0OsTR5KV4b0u87aSNrRldcKnfOWK9BubP4T9yGMjPyeuZP XA0UQMRlGpql8I+4rRvdHio+N2lpHsFDzd7ckmjWMjXdeU2dGhE6580YbEpuLQRb SN86ylkCgYEA3d/0W2S4wtmbV4X9AhLDe4vWLP1GmMcmcZ2wwuljEK14xNdeYzyD z42PZ6RsGtAtdUHe6/e+7TRpz/f938f4ygawCV7zXkF65bPm54zz9o7+CM9p4P3V AntDVO5IskiE6hb5A7wR0UdRNLDhov38Ngh+iUEDJ9MuZ75GWj6UbGcCgYEAzPmE om9eaDC3g2hmBwTB54bAMgskRT9sdaFFJtMHx7VU0xw9E34qfD17o0LDa9n62TDv getytWnluzwyhRw6UPhzseQw6R+7wtLlLPAj9mC58l34ONXwPSME0Exp/9WAVErt Z0Ng6xPmifesQ/fSUM52aCIgufyQOQ1zCx9ogtUCgYBotpOKtqSEQVMRIYlg+x4L Jtnz7azt2b+JC5UqyB8a9ePzcnl3eE31HKg7j9v9Y5awql/dGdWf+Yaewjms7aG7 JyDZq1hMebbYxekKCvnwuVenLMyZhPKM80O5x6PDkHo6SJFJc+8sx+3JYll7JUds 8OFXQbmNiBt0ltZ5LOO7rQKBgB1/HrYdXrGRqSbw5BXIenrt6kSJU+vfJ6V50rC2 l50GnDFRE/z1H/oHAv7IgcTIdo/AugaxMi2nEpcyH3cGS+IRDt0foGY72dI8dRxV ZmdzHe8h1LGhH9Q8cNnk1TAqsi/vJGDC0nShxYA/MvwI8qwMOf/cQWdiUALVy6Nj HrANAoGBAIK6Lh0mZLtan60F1rUoXqME7yIGQgf/cP+RKLwE36kqF5DQx9aFwPZx 9aWuKH+/XjdHf/J1n/AQ1j/G/WExs3UNfrvDgYea5QDnvc2gMBDRkdBwFZHYZLIn e+viqMbgmORJDP/8vbpd0yZjT25ImysJE5cSCGiqHOotDs3jdlUX -----END RSA PRIVATE KEY-----" "https://mauth-sandbox.imedidata.net") (with-redefs [clojure-mauth-client.header/epoch-seconds (fn [] 1532825948) clj-http.client/request (fn [{:keys [client timeout filter worker-pool keepalive as follow-redirects max-redirects response trace-redirects allow-unsafe-redirect-methods proxy-host proxy-port tunnel?] :as opts :or {client nil timeout 60000 follow-redirects true max-redirects 10 filter nil worker-pool nil response (promise) keepalive 120000 as :auto tunnel? false proxy-host nil proxy-port 3128}} & [callback]] opts)] (f) ) )) (def mock-get {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==" "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-get-with-qs {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gI/yUeSTbiOWggLvCv2IJP19GFvmlE8RoaUrIpyLE8DY/mCQd8CUPgT9xNHGNqgPGe9f4CZdiFCC79Xvp6seZAq8/CnqA1dsJW6f46scqqTs+4N1TJml6GNCT9xU4tjUyHWFWpCBQlSvpoTFsLSq2d2zas9M9q1sgwPBS/oPGEN1agCQLHZS/Ime4ub8MuXh0Q8aWodqCpVi4GPiap/KLIQEzbvhsdayxmAcs2XDjpt+CReRf3tBCzB1RucVEfBehxtDQGgvrs/UCUbkpq7gY7f2k0RkrH+IopfhYfdNpmCHW12OEQoZ74TVbh61Uo+xcD1der46+tWk0mdnlyXKow==" "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing?testABCD=1234" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-post {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:kYZR1udBwE02ct55cSWq5MZuGsC6xgVmK6TWYQ/+2IAbhqG7jZWhP95bPxTqo1f12XUWsX/oeUAp8jhvdUcsXsjVMeBwvQNgnC/HP1TNQasC2LMGfOs76WnsfKoV5zWDh+SNqMqn4pIXce3DALG9d/FB2Uu4mIg9kgQIUnfJJDljfLMjR7aMgDINPU7ToM51TqTJh+ReG7LAVwsEzSwFfj4zZFFpx8XrWn3inx5ZUvT7YcFhW4vOZaeI48HSnj80bCf1LDtWXzU7yk9gon+AlIYBTtrPQTSqyofBGZUtZCBexnoEp6NUhk5XkwqK56jizT7PZCN094kh1eofr3hSTg==" "X-MWS-Time" "1532825948"}, :url "https://www.mdsol.com/api/v2/testing1" :method :post :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto} ) (def mock-delete {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:IzAzkGyzDtxbMlCbbWViYen/9o54B9Ijlnp1UoSIysGr/axJWwph8KRYukS+3DhYFJIBLbS1PfWI74kRTkWJl3Vmb0XgxiRfNCqresqh687ELlhNDt66p2mu/6LaVwbDKUBsIAwkQFomVfAOy3jckWZjHRySD+VABfDf4BAf5hfjTUgil63oOnH6xII51e6M160SFRz1/HpsMU/rnReniPJs22MwiqS6dhe3oU/DAzteawxujSdFA3i6Fol6kdJQN19w+0TTdOSbccjds1Wljqu/+E1ju1rXVAgcL0GuVg4dsCwrjSPY9VWfQOttpA4aHavGWNcPMh1p1kSmqlNa1g==" "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing2" :method :delete :body "\"\"", :throw-exceptions false :as :auto}) (def mock-put {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:W+hIOQKAp0aEwDthAVaMa5ysJB8ddQdJdTWNonQoDuPEBVAY7F6GUXNoAZCYcosxgbm2rfpwyfLrS7U5b77GMFpnvvUwUSCgRziZNvfhuZfWUuW9po7OkWQUXCDvd/NtJdLOu6o1bKCGHYKjdaw/8AVH876afGyPF7+Ce2vD+YFRfY+zXF0MVWiS2WfwUwLSdOXb+Csnb21XT59zDs8qBg0gUj6WagZiJ+hYTbAt1zcNCdqs/mVt5hKA7ASxB9VY7GI4QM/n0EoyC/ruUm8DYS7kkxuxKeZuNkvpexFR4IPXQax1q7EtCIgw4yekegK210uxxYoOf+EBV2wMIVpKvw==" "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing3" :method :put :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto}) (def mock-payload (-> {:a {:b 123}} json/write-str)) (deftest header-test (testing "It should make a valid GET request." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing") (= mock-get) is ) )) (testing "It should make a valid GET request with a querystring." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing?testABCD=1234") (= mock-get-with-qs) is ) )) (testing "It should make a valid POST request." (let [creds (get-credentials)] (-> (post! "https://www.mdsol.com" "/api/v2/testing1" mock-payload) (= mock-post) is ) )) (testing "It should make a valid DELETE request." (let [creds (get-credentials)] (-> (delete! "https://www.mdsol.com" "/api/v2/testing2") (= mock-delete) is ) )) (testing "It should make a valid PUT request." (let [creds (get-credentials)] (-> (put! "https://www.mdsol.com" "/api/v2/testing3" mock-payload) (= mock-put) is ) )) )
19953
(ns clojure-mauth-client.request-test (:require [clojure.test :refer :all] [clojure-mauth-client.request :refer :all] [clojure.data.json :as json]) (:use [clojure-mauth-client.credentials])) (use-fixtures :once (fn [f] ;Note: these are NOT valid real credentials. (define-credentials "<KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD> <KEY>" "-----BEGIN RSA PRIVATE KEY<KEY>----- <KEY> <KEY>Z<KEY>fSr<KEY>oXik5o1vG1d5SiOuvxYVAOIFcTJj<KEY> get<KEY> Z<KEY> J<KEY> J<KEY>h<KEY>ebbY<KEY>KCvn<KEY>LMy<KEY>PKM80<KEY>5x6<KEY> -----END RSA PRIVATE KEY-----" "https://mauth-sandbox.imedidata.net") (with-redefs [clojure-mauth-client.header/epoch-seconds (fn [] 1532825948) clj-http.client/request (fn [{:keys [client timeout filter worker-pool keepalive as follow-redirects max-redirects response trace-redirects allow-unsafe-redirect-methods proxy-host proxy-port tunnel?] :as opts :or {client nil timeout 60000 follow-redirects true max-redirects 10 filter nil worker-pool nil response (promise) keepalive 120000 as :auto tunnel? false proxy-host nil proxy-port 3128}} & [callback]] opts)] (f) ) )) (def mock-get {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-cc<KEY>51ae75c<KEY>:g<KEY> "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-get-with-qs {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:g<KEY> "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing?testABCD=1234" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-post {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:<KEY> "X-MWS-Time" "1532825948"}, :url "https://www.mdsol.com/api/v2/testing1" :method :post :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto} ) (def mock-delete {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:<KEY> "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing2" :method :delete :body "\"\"", :throw-exceptions false :as :auto}) (def mock-put {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:W+hIOQKAp0<KEY>DthAV<KEY>5ys<KEY> "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing3" :method :put :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto}) (def mock-payload (-> {:a {:b 123}} json/write-str)) (deftest header-test (testing "It should make a valid GET request." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing") (= mock-get) is ) )) (testing "It should make a valid GET request with a querystring." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing?testABCD=1234") (= mock-get-with-qs) is ) )) (testing "It should make a valid POST request." (let [creds (get-credentials)] (-> (post! "https://www.mdsol.com" "/api/v2/testing1" mock-payload) (= mock-post) is ) )) (testing "It should make a valid DELETE request." (let [creds (get-credentials)] (-> (delete! "https://www.mdsol.com" "/api/v2/testing2") (= mock-delete) is ) )) (testing "It should make a valid PUT request." (let [creds (get-credentials)] (-> (put! "https://www.mdsol.com" "/api/v2/testing3" mock-payload) (= mock-put) is ) )) )
true
(ns clojure-mauth-client.request-test (:require [clojure.test :refer :all] [clojure-mauth-client.request :refer :all] [clojure.data.json :as json]) (:use [clojure-mauth-client.credentials])) (use-fixtures :once (fn [f] ;Note: these are NOT valid real credentials. (define-credentials "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI" "-----BEGIN RSA PRIVATE KEYPI:KEY:<KEY>END_PI----- PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PIZPI:KEY:<KEY>END_PIfSrPI:KEY:<KEY>END_PIoXik5o1vG1d5SiOuvxYVAOIFcTJjPI:KEY:<KEY>END_PI getPI:KEY:<KEY>END_PI ZPI:KEY:<KEY>END_PI JPI:KEY:<KEY>END_PI JPI:KEY:<KEY>END_PIhPI:KEY:<KEY>END_PIebbYPI:KEY:<KEY>END_PIKCvnPI:KEY:<KEY>END_PILMyPI:KEY:<KEY>END_PIPKM80PI:KEY:<KEY>END_PI5x6PI:KEY:<KEY>END_PI -----END RSA PRIVATE KEY-----" "https://mauth-sandbox.imedidata.net") (with-redefs [clojure-mauth-client.header/epoch-seconds (fn [] 1532825948) clj-http.client/request (fn [{:keys [client timeout filter worker-pool keepalive as follow-redirects max-redirects response trace-redirects allow-unsafe-redirect-methods proxy-host proxy-port tunnel?] :as opts :or {client nil timeout 60000 follow-redirects true max-redirects 10 filter nil worker-pool nil response (promise) keepalive 120000 as :auto tunnel? false proxy-host nil proxy-port 3128}} & [callback]] opts)] (f) ) )) (def mock-get {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccPI:KEY:<KEY>END_PI51ae75cPI:KEY:<KEY>END_PI:gPI:KEY:<KEY>END_PI "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-get-with-qs {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:gPI:KEY:<KEY>END_PI "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing?testABCD=1234" :method :get, :body "\"\"", :throw-exceptions false :as :auto} ) (def mock-post {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:PI:KEY:<KEY>END_PI "X-MWS-Time" "1532825948"}, :url "https://www.mdsol.com/api/v2/testing1" :method :post :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto} ) (def mock-delete {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:PI:KEY:<KEY>END_PI "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing2" :method :delete :body "\"\"", :throw-exceptions false :as :auto}) (def mock-put {:headers {"X-MWS-Authentication" "MWS abcd7d78-c874-47d9-a829-ccaa51ae75c9:W+hIOQKAp0PI:KEY:<KEY>END_PIDthAVPI:KEY:<KEY>END_PI5ysPI:KEY:<KEY>END_PI "X-MWS-Time" "1532825948"} :url "https://www.mdsol.com/api/v2/testing3" :method :put :body "\"{\\\"a\\\":{\\\"b\\\":123}}\"" :throw-exceptions false :as :auto}) (def mock-payload (-> {:a {:b 123}} json/write-str)) (deftest header-test (testing "It should make a valid GET request." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing") (= mock-get) is ) )) (testing "It should make a valid GET request with a querystring." (let [creds (get-credentials)] (-> (get! "https://www.mdsol.com" "/api/v2/testing?testABCD=1234") (= mock-get-with-qs) is ) )) (testing "It should make a valid POST request." (let [creds (get-credentials)] (-> (post! "https://www.mdsol.com" "/api/v2/testing1" mock-payload) (= mock-post) is ) )) (testing "It should make a valid DELETE request." (let [creds (get-credentials)] (-> (delete! "https://www.mdsol.com" "/api/v2/testing2") (= mock-delete) is ) )) (testing "It should make a valid PUT request." (let [creds (get-credentials)] (-> (put! "https://www.mdsol.com" "/api/v2/testing3" mock-payload) (= mock-put) is ) )) )
[ { "context": "ensso.timbre :as log])\n (:import\n [com.github.benmanes.caffeine.cache LoadingCache]))\n\n\n(st/instrument)\n", "end": 384, "score": 0.9983389973640442, "start": 376, "tag": "USERNAME", "value": "benmanes" }, { "context": "(ig/init {:blaze.db/tx-cache nil})\n :key := :blaze.db/tx-cache\n :reason := ::ig/build-failed-spec\n", "end": 784, "score": 0.7314493656158447, "start": 776, "tag": "KEY", "value": "blaze.db" }, { "context": "nit {:blaze.db/tx-cache {}})\n :key := :blaze.db/tx-cache\n :reason := ::ig/build-failed-spec\n", "end": 986, "score": 0.5462002158164978, "start": 984, "tag": "KEY", "value": "db" }, { "context": "ze.db/tx-cache {:kv-store nil}})\n :key := :blaze.db/tx-cache\n :reason := ::ig/build-failed-sp", "end": 1230, "score": 0.5151897668838501, "start": 1227, "tag": "KEY", "value": "aze" }, { "context": "b/tx-cache {:kv-store nil}})\n :key := :blaze.db/tx-cache\n :reason := ::ig/build-failed-spec\n", "end": 1233, "score": 0.5307155847549438, "start": 1231, "tag": "KEY", "value": "db" } ]
modules/db/test/blaze/db/tx_cache_test.clj
samply/blaze
50
(ns blaze.db.tx-cache-test (:require [blaze.db.kv :as kv] [blaze.db.kv.mem] [blaze.db.tx-cache] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [integrant.core :as ig] [taoensso.timbre :as log]) (:import [com.github.benmanes.caffeine.cache LoadingCache])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def system {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem)} ::kv/mem {:column-families {}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/tx-cache nil}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing store" (given-thrown (ig/init {:blaze.db/tx-cache {}}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn [~'%] (contains? ~'% :kv-store)))) (testing "invalid store" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store nil}}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `blaze.db.kv/store?)) (testing "invalid max-size" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem) :max-size nil} ::kv/mem {:column-families {}}}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `nat-int?))) (deftest empty-store-test (with-system [{cache :blaze.db/tx-cache} system] (is (nil? (.get ^LoadingCache cache 0)))))
21964
(ns blaze.db.tx-cache-test (:require [blaze.db.kv :as kv] [blaze.db.kv.mem] [blaze.db.tx-cache] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [integrant.core :as ig] [taoensso.timbre :as log]) (:import [com.github.benmanes.caffeine.cache LoadingCache])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def system {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem)} ::kv/mem {:column-families {}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/tx-cache nil}) :key := :<KEY>/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing store" (given-thrown (ig/init {:blaze.db/tx-cache {}}) :key := :blaze.<KEY>/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn [~'%] (contains? ~'% :kv-store)))) (testing "invalid store" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store nil}}) :key := :bl<KEY>.<KEY>/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `blaze.db.kv/store?)) (testing "invalid max-size" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem) :max-size nil} ::kv/mem {:column-families {}}}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `nat-int?))) (deftest empty-store-test (with-system [{cache :blaze.db/tx-cache} system] (is (nil? (.get ^LoadingCache cache 0)))))
true
(ns blaze.db.tx-cache-test (:require [blaze.db.kv :as kv] [blaze.db.kv.mem] [blaze.db.tx-cache] [blaze.test-util :refer [given-thrown with-system]] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as st] [clojure.test :as test :refer [deftest is testing]] [integrant.core :as ig] [taoensso.timbre :as log]) (:import [com.github.benmanes.caffeine.cache LoadingCache])) (st/instrument) (log/set-level! :trace) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def system {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem)} ::kv/mem {:column-families {}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/tx-cache nil}) :key := :PI:KEY:<KEY>END_PI/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing store" (given-thrown (ig/init {:blaze.db/tx-cache {}}) :key := :blaze.PI:KEY:<KEY>END_PI/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn [~'%] (contains? ~'% :kv-store)))) (testing "invalid store" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store nil}}) :key := :blPI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `blaze.db.kv/store?)) (testing "invalid max-size" (given-thrown (ig/init {:blaze.db/tx-cache {:kv-store (ig/ref ::kv/mem) :max-size nil} ::kv/mem {:column-families {}}}) :key := :blaze.db/tx-cache :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `nat-int?))) (deftest empty-store-test (with-system [{cache :blaze.db/tx-cache} system] (is (nil? (.get ^LoadingCache cache 0)))))
[ { "context": "\"})))\n (let [uri-string \"http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"]\n (is (= (", "end": 1975, "score": 0.6187439560890198, "start": 1972, "tag": "IP_ADDRESS", "value": "210" }, { "context": ")\n (let [uri-string \"http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"]\n (is (= (into ", "end": 1980, "score": 0.7738017439842224, "start": 1976, "tag": "IP_ADDRESS", "value": "FEDC" }, { "context": "let [uri-string \"http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"]\n (is (= (into {} (u", "end": 1985, "score": 0.662485659122467, "start": 1981, "tag": "IP_ADDRESS", "value": "BA98" }, { "context": "e \"http\"\n :scheme-relative \"//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"\n ", "end": 2120, "score": 0.569466233253479, "start": 2119, "tag": "IP_ADDRESS", "value": "8" }, { "context": "http\"\n :scheme-relative \"//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"\n ", "end": 2125, "score": 0.6149335503578186, "start": 2122, "tag": "IP_ADDRESS", "value": "654" }, { "context": "\"\n :scheme-relative \"//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"\n :authority ", "end": 2140, "score": 0.8204885125160217, "start": 2126, "tag": "IP_ADDRESS", "value": "3210:FEDC:BA98" }, { "context": "heme-relative \"//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html\"\n :authority \"[FE", "end": 2145, "score": 0.6576627492904663, "start": 2143, "tag": "IP_ADDRESS", "value": "54" }, { "context": "]:80/index.html\"\n :authority \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80\"\n :h", "end": 2202, "score": 0.660315990447998, "start": 2200, "tag": "IP_ADDRESS", "value": "98" }, { "context": "0/index.html\"\n :authority \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80\"\n :host", "end": 2205, "score": 0.5304029583930969, "start": 2203, "tag": "IP_ADDRESS", "value": "76" }, { "context": "ndex.html\"\n :authority \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80\"\n :host \"", "end": 2207, "score": 0.7484821677207947, "start": 2206, "tag": "IP_ADDRESS", "value": "4" }, { "context": "ex.html\"\n :authority \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80\"\n :host \"[FEDC:BA98", "end": 2217, "score": 0.672235369682312, "start": 2208, "tag": "IP_ADDRESS", "value": "3210:FEDC" }, { "context": " :authority \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80\"\n :host \"[FEDC:BA98:7654", "end": 2222, "score": 0.595431387424469, "start": 2218, "tag": "IP_ADDRESS", "value": "BA98" }, { "context": "0:FEDC:BA98:7654:3210]:80\"\n :host \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]\"\n ", "end": 2262, "score": 0.5540602803230286, "start": 2261, "tag": "IP_ADDRESS", "value": "C" }, { "context": "FEDC:BA98:7654:3210]:80\"\n :host \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]\"\n :port 80\n ", "end": 2282, "score": 0.698703408241272, "start": 2263, "tag": "IP_ADDRESS", "value": "BA98:7654:3210:FEDC" }, { "context": ":80\"\n :host \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]\"\n :port 80\n :pat", "end": 2287, "score": 0.7220237851142883, "start": 2283, "tag": "IP_ADDRESS", "value": "BA98" }, { "context": " :host \"[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]\"\n :port 80\n :path \"/i", "end": 2292, "score": 0.5230943560600281, "start": 2291, "tag": "IP_ADDRESS", "value": "4" }, { "context": "a-url)\n (authority uri-obj)\n \"someone@www.pureawesomeness.org:8088\"))\n (is (= (user-info string", "end": 5562, "score": 0.7603616714477539, "start": 5544, "tag": "EMAIL", "value": "someone@www.pureaw" }, { "context": "y uri-obj)\n \"someone@www.pureawesomeness.org:8088\"))\n (is (= (user-info string)\n ", "end": 5575, "score": 0.6628245115280151, "start": 5572, "tag": "EMAIL", "value": "org" } ]
test/org/bovinegenius/uri_test.clj
wtetzner/exploding-fish
93
(ns org.bovinegenius.uri_test (:use (org.bovinegenius exploding-fish) (org.bovinegenius.exploding-fish query-string) (clojure test)) (:require (org.bovinegenius.exploding-fish [parser :as parse])) (:import (java.net URI URL))) (deftest ensure-authority-test (let [uritest (uri {:scheme "http" :host "localhost" :port 3001 :path "/tags" :query "name=comp&from=0"}) my-uri (uri {:scheme "http" :host "localhost" :port 3000})] (is (= (str (param uritest "from" 10)) "http://localhost:3001/tags?name=comp&from=10")) (is (= (str (path my-uri "/foo")) "http://localhost:3000/foo")))) (deftest uri-test (let [uri-string "http://www.fred.net/"] (is (= [:host "www.fred.net"] (find (uri uri-string) :host))) (is (= 5 (count (uri uri-string)))) (is (= (uri {}) (empty (uri uri-string)))) (is (= "www.fred.net" (.get (uri uri-string) :host))) (is (.containsValue (uri uri-string) "www.fred.net")) (is (not (.containsValue (uri uri-string) "www.example.com"))) (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.fred.net" :path "/" :authority "www.fred.net" :scheme "http" :scheme-relative "//www.fred.net/"})) (into {} (conj (uri "http://example.com/test") {:host "www.fred.net" :path "/"})) (into {} (conj (uri "http://example.com/") [:host "www.fred.net"])) (into {} (conj (uri "http://www.fred.net/test") (find {:path "/"} :path))) (into {} (dissoc (uri "http://www.fred.net/#muh") :fragment)) {:host "www.fred.net", :path "/", :authority "www.fred.net", :scheme "http", :scheme-relative "//www.fred.net/"}))) (let [uri-string "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"] (is (= (into {} (uri uri-string)) {:scheme "http" :scheme-relative "//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html" :authority "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80" :host "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]" :port 80 :path "/index.html"}))) (let [uri-string "http://www.domain.net/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net" :scheme "http" :scheme-relative "//www.domain.net/with?query=and" :fragment "fragment"})) {:host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net", :scheme "http", :scheme-relative "//www.domain.net/with?query=and", :fragment "fragment"}))) (let [uri-string "http://www.domain.net:8080/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:port 8080 :host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net:8080" :scheme "http" :scheme-relative "//www.domain.net:8080/with?query=and" :fragment "fragment"})) {:port 8080, :host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net:8080", :scheme "http", :scheme-relative "//www.domain.net:8080/with?query=and", :fragment "fragment"})))) (deftest partial-test (is (= (uri->map (uri "/some/path")) {:path "/some/path" :scheme-relative "/some/path"})) (is (= (uri->map (uri "http:/stuff?")) {:scheme "http", :scheme-relative "/stuff?" :path "/stuff" :query ""})) (is (= (uri->map (uri "http://stuff?")) {:scheme "http", :authority "stuff", :host "stuff", :scheme-relative "//stuff?", :query ""})) (is (= (uri->map (uri "file:/some/path")) {:scheme "file", :scheme-relative "/some/path" :path "/some/path"})) (is (= (uri->map (uri "file:///some/path")) {:scheme "file", :scheme-relative "///some/path" :path "/some/path"}))) (deftest protocol-fns (let [string "http://someone@www.pureawesomeness.org:8088/some/path?x=y&a=b#awesomeness" java-uri (URI. string) java-url (URL. string) uri-obj (uri string)] (is (= (scheme string) (scheme java-uri) (scheme java-url) (scheme uri-obj) "http")) (is (= (scheme-relative string) (scheme-relative java-uri) (scheme-relative java-url) (scheme-relative uri-obj) "//someone@www.pureawesomeness.org:8088/some/path?x=y&a=b")) (is (= (authority string) (authority java-uri) (authority java-url) (authority uri-obj) "someone@www.pureawesomeness.org:8088")) (is (= (user-info string) (user-info java-uri) (user-info java-url) (user-info uri-obj) "someone")) (is (= (host string) (host java-uri) (host java-url) (host uri-obj) "www.pureawesomeness.org")) (is (= (port string) (port java-uri) (port java-url) (port uri-obj) 8088)) (is (= (path string) (path java-uri) (path java-url) (path uri-obj) "/some/path")) (is (= (query string) (query java-uri) (query java-url) (query uri-obj) "x=y&a=b")) (is (= (fragment string) (fragment java-uri) (fragment java-url) (fragment uri-obj) "awesomeness")))) (deftest uri->map-test (is (= (uri->map (URI. "http://www.test.com:8080/some/stuff.html#frag")) {:path "/some/stuff.html", :scheme "http", :authority "www.test.com:8080", :host "www.test.com", :port 8080, :scheme-relative "//www.test.com:8080/some/stuff.html", :fragment "frag"}))) (deftest query-list-test (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '("one=1" "two=2" "x=" "y"))) (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list "http://www.some-thing.com/a/path?one=1&two=2&x=&y") (query-list (URI. "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list (URL. "http://www.some-thing.com/a/path?one=1&two=2&x=&y"))))) (deftest query-pairs-test (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil]))) (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil] ["" nil] ["" ""] ["" "a"]))) (is (= (alist->query-string (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a"))) "one=1&two=2&x=&y&&=&=a")) (is (= (alist->query-string (query-pairs "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) "one=1&two=2&x=&y&&=&=a"))) (deftest param-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d+x=m%3Df&m=2" (param url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=x&m=2&a=7" (param url "a" 7 2))) (is (= (param "/some/path/stuff?thing=value" "thing" "new-value") "/some/path/stuff?thing=new-value")) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=7&a=x&m=2" (param url "d x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=7&m=2" (param url "a" 7 1))))) (deftest param-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d%20x=m%3Df&m=2" (param-raw url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2&a=7" (param-raw url "a" 7 2))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=7&a=x&m=2" (param-raw url "d%20x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=7&m=2" (param-raw url "a" 7 1))))) (deftest params-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params url "a"))) (is (= ["m=f"] (params url "d x"))))) (deftest params-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params-raw url "a"))) (is (= ["m%3Df"] (params-raw url "d%20x"))) (is (= [] (params-raw url "d x"))))) (deftest query-map-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= {"x" "y" "a" "x" "d x" "m=f" "m" "2"} (query-map url))))) (deftest raw-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d%20x" "a" "m"] (raw-keys url))))) (deftest query-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d x" "a" "m"] (query-keys url))))) (deftest normalize-path-test (let [uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/here?x=y&a=b#a-fragment" (normalize-path uri))) (is (= (normalize-path "http://foo.org") "http://foo.org")))) (deftest resolve-path-test (let [the-uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (normalize-path (resolve-path the-uri "new/path/stuff")))) (is (= "http://www.example.com/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "/new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/here/new/path/stuff?x=y&a=b#a-fragment" (resolve-path "http://www.example.com/some/awesome/path/here/?x=y&a=b#a-fragment" "new/path/stuff"))) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") "y/asdf")) "http://www.example.com/asdf/y/asdf")) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") (uri "y/asdf"))) "http://www.example.com/asdf/y/asdf")) (is (= (resolve-path "http://foo.org" "data.html") "http://foo.org/data.html")) (is (= (resolve-path "http://foo.org" "/data.html") "http://foo.org/data.html")))) (deftest absolute?-test (is (absolute? "http://www.test.net/new/path?x=y&a=w")) (is (not (absolute? "/new/path?x=y&a=w")))) (deftest resolve-uri-test (let [the-base-uri "http://a/b/c/d;p?q=1/2"] (is (let [diff-host-uri "http://e/f"] (= (resolve-uri the-base-uri diff-host-uri) diff-host-uri))) (is (= (resolve-uri the-base-uri "g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "./g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "g/") "http://a/b/c/g/")) (is (= (resolve-uri the-base-uri "/g") "http://a/g")) (is (= (resolve-uri the-base-uri "//g") "http://g")) (is (= (resolve-uri the-base-uri (URI. "//g")) (URI. "http://g"))) (is (= (resolve-uri the-base-uri "g?y") "http://a/b/c/g?y")) (is (= (resolve-uri (URI. the-base-uri) "g?y") (URI. "http://a/b/c/g?y"))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/./x")] (or (= resolved-uri "http://a/b/c/g?y/./x") (= resolved-uri "http://a/b/c/g?y/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/../x")] (or (= resolved-uri "http://a/b/c/g?y/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "g#s") "http://a/b/c/g#s")) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/./x")] (or (= resolved-uri "http://a/b/c/g#s/./x") (= resolved-uri "http://a/b/c/g#s/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/../x")] (or (= resolved-uri "http://a/b/c/g#s/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "./") "http://a/b/c/")) (is (= (resolve-uri the-base-uri "../") "http://a/b/")) (is (= (resolve-uri the-base-uri "../g") "http://a/b/g")) (is (= (resolve-uri the-base-uri "../../") "http://a/")) (is (= (resolve-uri the-base-uri "../../g") "http://a/g"))))
117170
(ns org.bovinegenius.uri_test (:use (org.bovinegenius exploding-fish) (org.bovinegenius.exploding-fish query-string) (clojure test)) (:require (org.bovinegenius.exploding-fish [parser :as parse])) (:import (java.net URI URL))) (deftest ensure-authority-test (let [uritest (uri {:scheme "http" :host "localhost" :port 3001 :path "/tags" :query "name=comp&from=0"}) my-uri (uri {:scheme "http" :host "localhost" :port 3000})] (is (= (str (param uritest "from" 10)) "http://localhost:3001/tags?name=comp&from=10")) (is (= (str (path my-uri "/foo")) "http://localhost:3000/foo")))) (deftest uri-test (let [uri-string "http://www.fred.net/"] (is (= [:host "www.fred.net"] (find (uri uri-string) :host))) (is (= 5 (count (uri uri-string)))) (is (= (uri {}) (empty (uri uri-string)))) (is (= "www.fred.net" (.get (uri uri-string) :host))) (is (.containsValue (uri uri-string) "www.fred.net")) (is (not (.containsValue (uri uri-string) "www.example.com"))) (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.fred.net" :path "/" :authority "www.fred.net" :scheme "http" :scheme-relative "//www.fred.net/"})) (into {} (conj (uri "http://example.com/test") {:host "www.fred.net" :path "/"})) (into {} (conj (uri "http://example.com/") [:host "www.fred.net"])) (into {} (conj (uri "http://www.fred.net/test") (find {:path "/"} :path))) (into {} (dissoc (uri "http://www.fred.net/#muh") :fragment)) {:host "www.fred.net", :path "/", :authority "www.fred.net", :scheme "http", :scheme-relative "//www.fred.net/"}))) (let [uri-string "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"] (is (= (into {} (uri uri-string)) {:scheme "http" :scheme-relative "//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html" :authority "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80" :host "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]" :port 80 :path "/index.html"}))) (let [uri-string "http://www.domain.net/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net" :scheme "http" :scheme-relative "//www.domain.net/with?query=and" :fragment "fragment"})) {:host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net", :scheme "http", :scheme-relative "//www.domain.net/with?query=and", :fragment "fragment"}))) (let [uri-string "http://www.domain.net:8080/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:port 8080 :host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net:8080" :scheme "http" :scheme-relative "//www.domain.net:8080/with?query=and" :fragment "fragment"})) {:port 8080, :host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net:8080", :scheme "http", :scheme-relative "//www.domain.net:8080/with?query=and", :fragment "fragment"})))) (deftest partial-test (is (= (uri->map (uri "/some/path")) {:path "/some/path" :scheme-relative "/some/path"})) (is (= (uri->map (uri "http:/stuff?")) {:scheme "http", :scheme-relative "/stuff?" :path "/stuff" :query ""})) (is (= (uri->map (uri "http://stuff?")) {:scheme "http", :authority "stuff", :host "stuff", :scheme-relative "//stuff?", :query ""})) (is (= (uri->map (uri "file:/some/path")) {:scheme "file", :scheme-relative "/some/path" :path "/some/path"})) (is (= (uri->map (uri "file:///some/path")) {:scheme "file", :scheme-relative "///some/path" :path "/some/path"}))) (deftest protocol-fns (let [string "http://someone@www.pureawesomeness.org:8088/some/path?x=y&a=b#awesomeness" java-uri (URI. string) java-url (URL. string) uri-obj (uri string)] (is (= (scheme string) (scheme java-uri) (scheme java-url) (scheme uri-obj) "http")) (is (= (scheme-relative string) (scheme-relative java-uri) (scheme-relative java-url) (scheme-relative uri-obj) "//someone@www.pureawesomeness.org:8088/some/path?x=y&a=b")) (is (= (authority string) (authority java-uri) (authority java-url) (authority uri-obj) "<EMAIL>esomeness.<EMAIL>:8088")) (is (= (user-info string) (user-info java-uri) (user-info java-url) (user-info uri-obj) "someone")) (is (= (host string) (host java-uri) (host java-url) (host uri-obj) "www.pureawesomeness.org")) (is (= (port string) (port java-uri) (port java-url) (port uri-obj) 8088)) (is (= (path string) (path java-uri) (path java-url) (path uri-obj) "/some/path")) (is (= (query string) (query java-uri) (query java-url) (query uri-obj) "x=y&a=b")) (is (= (fragment string) (fragment java-uri) (fragment java-url) (fragment uri-obj) "awesomeness")))) (deftest uri->map-test (is (= (uri->map (URI. "http://www.test.com:8080/some/stuff.html#frag")) {:path "/some/stuff.html", :scheme "http", :authority "www.test.com:8080", :host "www.test.com", :port 8080, :scheme-relative "//www.test.com:8080/some/stuff.html", :fragment "frag"}))) (deftest query-list-test (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '("one=1" "two=2" "x=" "y"))) (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list "http://www.some-thing.com/a/path?one=1&two=2&x=&y") (query-list (URI. "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list (URL. "http://www.some-thing.com/a/path?one=1&two=2&x=&y"))))) (deftest query-pairs-test (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil]))) (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil] ["" nil] ["" ""] ["" "a"]))) (is (= (alist->query-string (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a"))) "one=1&two=2&x=&y&&=&=a")) (is (= (alist->query-string (query-pairs "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) "one=1&two=2&x=&y&&=&=a"))) (deftest param-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d+x=m%3Df&m=2" (param url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=x&m=2&a=7" (param url "a" 7 2))) (is (= (param "/some/path/stuff?thing=value" "thing" "new-value") "/some/path/stuff?thing=new-value")) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=7&a=x&m=2" (param url "d x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=7&m=2" (param url "a" 7 1))))) (deftest param-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d%20x=m%3Df&m=2" (param-raw url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2&a=7" (param-raw url "a" 7 2))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=7&a=x&m=2" (param-raw url "d%20x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=7&m=2" (param-raw url "a" 7 1))))) (deftest params-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params url "a"))) (is (= ["m=f"] (params url "d x"))))) (deftest params-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params-raw url "a"))) (is (= ["m%3Df"] (params-raw url "d%20x"))) (is (= [] (params-raw url "d x"))))) (deftest query-map-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= {"x" "y" "a" "x" "d x" "m=f" "m" "2"} (query-map url))))) (deftest raw-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d%20x" "a" "m"] (raw-keys url))))) (deftest query-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d x" "a" "m"] (query-keys url))))) (deftest normalize-path-test (let [uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/here?x=y&a=b#a-fragment" (normalize-path uri))) (is (= (normalize-path "http://foo.org") "http://foo.org")))) (deftest resolve-path-test (let [the-uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (normalize-path (resolve-path the-uri "new/path/stuff")))) (is (= "http://www.example.com/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "/new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/here/new/path/stuff?x=y&a=b#a-fragment" (resolve-path "http://www.example.com/some/awesome/path/here/?x=y&a=b#a-fragment" "new/path/stuff"))) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") "y/asdf")) "http://www.example.com/asdf/y/asdf")) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") (uri "y/asdf"))) "http://www.example.com/asdf/y/asdf")) (is (= (resolve-path "http://foo.org" "data.html") "http://foo.org/data.html")) (is (= (resolve-path "http://foo.org" "/data.html") "http://foo.org/data.html")))) (deftest absolute?-test (is (absolute? "http://www.test.net/new/path?x=y&a=w")) (is (not (absolute? "/new/path?x=y&a=w")))) (deftest resolve-uri-test (let [the-base-uri "http://a/b/c/d;p?q=1/2"] (is (let [diff-host-uri "http://e/f"] (= (resolve-uri the-base-uri diff-host-uri) diff-host-uri))) (is (= (resolve-uri the-base-uri "g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "./g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "g/") "http://a/b/c/g/")) (is (= (resolve-uri the-base-uri "/g") "http://a/g")) (is (= (resolve-uri the-base-uri "//g") "http://g")) (is (= (resolve-uri the-base-uri (URI. "//g")) (URI. "http://g"))) (is (= (resolve-uri the-base-uri "g?y") "http://a/b/c/g?y")) (is (= (resolve-uri (URI. the-base-uri) "g?y") (URI. "http://a/b/c/g?y"))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/./x")] (or (= resolved-uri "http://a/b/c/g?y/./x") (= resolved-uri "http://a/b/c/g?y/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/../x")] (or (= resolved-uri "http://a/b/c/g?y/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "g#s") "http://a/b/c/g#s")) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/./x")] (or (= resolved-uri "http://a/b/c/g#s/./x") (= resolved-uri "http://a/b/c/g#s/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/../x")] (or (= resolved-uri "http://a/b/c/g#s/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "./") "http://a/b/c/")) (is (= (resolve-uri the-base-uri "../") "http://a/b/")) (is (= (resolve-uri the-base-uri "../g") "http://a/b/g")) (is (= (resolve-uri the-base-uri "../../") "http://a/")) (is (= (resolve-uri the-base-uri "../../g") "http://a/g"))))
true
(ns org.bovinegenius.uri_test (:use (org.bovinegenius exploding-fish) (org.bovinegenius.exploding-fish query-string) (clojure test)) (:require (org.bovinegenius.exploding-fish [parser :as parse])) (:import (java.net URI URL))) (deftest ensure-authority-test (let [uritest (uri {:scheme "http" :host "localhost" :port 3001 :path "/tags" :query "name=comp&from=0"}) my-uri (uri {:scheme "http" :host "localhost" :port 3000})] (is (= (str (param uritest "from" 10)) "http://localhost:3001/tags?name=comp&from=10")) (is (= (str (path my-uri "/foo")) "http://localhost:3000/foo")))) (deftest uri-test (let [uri-string "http://www.fred.net/"] (is (= [:host "www.fred.net"] (find (uri uri-string) :host))) (is (= 5 (count (uri uri-string)))) (is (= (uri {}) (empty (uri uri-string)))) (is (= "www.fred.net" (.get (uri uri-string) :host))) (is (.containsValue (uri uri-string) "www.fred.net")) (is (not (.containsValue (uri uri-string) "www.example.com"))) (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.fred.net" :path "/" :authority "www.fred.net" :scheme "http" :scheme-relative "//www.fred.net/"})) (into {} (conj (uri "http://example.com/test") {:host "www.fred.net" :path "/"})) (into {} (conj (uri "http://example.com/") [:host "www.fred.net"])) (into {} (conj (uri "http://www.fred.net/test") (find {:path "/"} :path))) (into {} (dissoc (uri "http://www.fred.net/#muh") :fragment)) {:host "www.fred.net", :path "/", :authority "www.fred.net", :scheme "http", :scheme-relative "//www.fred.net/"}))) (let [uri-string "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"] (is (= (into {} (uri uri-string)) {:scheme "http" :scheme-relative "//[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html" :authority "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80" :host "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]" :port 80 :path "/index.html"}))) (let [uri-string "http://www.domain.net/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net" :scheme "http" :scheme-relative "//www.domain.net/with?query=and" :fragment "fragment"})) {:host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net", :scheme "http", :scheme-relative "//www.domain.net/with?query=and", :fragment "fragment"}))) (let [uri-string "http://www.domain.net:8080/with?query=and#fragment"] (is (= (into {} (uri uri-string)) (into {} (uri (URI. uri-string))) (into {} (uri (URL. uri-string))) (into {} (uri {:port 8080 :host "www.domain.net" :query "query=and" :path "/with" :authority "www.domain.net:8080" :scheme "http" :scheme-relative "//www.domain.net:8080/with?query=and" :fragment "fragment"})) {:port 8080, :host "www.domain.net", :query "query=and", :path "/with", :authority "www.domain.net:8080", :scheme "http", :scheme-relative "//www.domain.net:8080/with?query=and", :fragment "fragment"})))) (deftest partial-test (is (= (uri->map (uri "/some/path")) {:path "/some/path" :scheme-relative "/some/path"})) (is (= (uri->map (uri "http:/stuff?")) {:scheme "http", :scheme-relative "/stuff?" :path "/stuff" :query ""})) (is (= (uri->map (uri "http://stuff?")) {:scheme "http", :authority "stuff", :host "stuff", :scheme-relative "//stuff?", :query ""})) (is (= (uri->map (uri "file:/some/path")) {:scheme "file", :scheme-relative "/some/path" :path "/some/path"})) (is (= (uri->map (uri "file:///some/path")) {:scheme "file", :scheme-relative "///some/path" :path "/some/path"}))) (deftest protocol-fns (let [string "http://someone@www.pureawesomeness.org:8088/some/path?x=y&a=b#awesomeness" java-uri (URI. string) java-url (URL. string) uri-obj (uri string)] (is (= (scheme string) (scheme java-uri) (scheme java-url) (scheme uri-obj) "http")) (is (= (scheme-relative string) (scheme-relative java-uri) (scheme-relative java-url) (scheme-relative uri-obj) "//someone@www.pureawesomeness.org:8088/some/path?x=y&a=b")) (is (= (authority string) (authority java-uri) (authority java-url) (authority uri-obj) "PI:EMAIL:<EMAIL>END_PIesomeness.PI:EMAIL:<EMAIL>END_PI:8088")) (is (= (user-info string) (user-info java-uri) (user-info java-url) (user-info uri-obj) "someone")) (is (= (host string) (host java-uri) (host java-url) (host uri-obj) "www.pureawesomeness.org")) (is (= (port string) (port java-uri) (port java-url) (port uri-obj) 8088)) (is (= (path string) (path java-uri) (path java-url) (path uri-obj) "/some/path")) (is (= (query string) (query java-uri) (query java-url) (query uri-obj) "x=y&a=b")) (is (= (fragment string) (fragment java-uri) (fragment java-url) (fragment uri-obj) "awesomeness")))) (deftest uri->map-test (is (= (uri->map (URI. "http://www.test.com:8080/some/stuff.html#frag")) {:path "/some/stuff.html", :scheme "http", :authority "www.test.com:8080", :host "www.test.com", :port 8080, :scheme-relative "//www.test.com:8080/some/stuff.html", :fragment "frag"}))) (deftest query-list-test (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '("one=1" "two=2" "x=" "y"))) (is (= (query-list (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list "http://www.some-thing.com/a/path?one=1&two=2&x=&y") (query-list (URI. "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) (query-list (URL. "http://www.some-thing.com/a/path?one=1&two=2&x=&y"))))) (deftest query-pairs-test (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil]))) (is (= (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) '(["one" "1"] ["two" "2"] ["x" ""] ["y" nil] ["" nil] ["" ""] ["" "a"]))) (is (= (alist->query-string (query-pairs (uri "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a"))) "one=1&two=2&x=&y&&=&=a")) (is (= (alist->query-string (query-pairs "http://www.some-thing.com/a/path?one=1&two=2&x=&y&&=&=a")) "one=1&two=2&x=&y&&=&=a"))) (deftest param-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d+x=m%3Df&m=2" (param url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=x&m=2&a=7" (param url "a" 7 2))) (is (= (param "/some/path/stuff?thing=value" "thing" "new-value") "/some/path/stuff?thing=new-value")) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=7&a=x&m=2" (param url "d x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d+x=m%3Df&a=7&m=2" (param url "a" 7 1))))) (deftest param-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= "http://www.test.net/some/path?x=y&a=7&d%20x=m%3Df&m=2" (param-raw url "a" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2&a=7" (param-raw url "a" 7 2))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=7&a=x&m=2" (param-raw url "d%20x" 7))) (is (= "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=7&m=2" (param-raw url "a" 7 1))))) (deftest params-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params url "a"))) (is (= ["m=f"] (params url "d x"))))) (deftest params-raw-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["w" "x"] (params-raw url "a"))) (is (= ["m%3Df"] (params-raw url "d%20x"))) (is (= [] (params-raw url "d x"))))) (deftest query-map-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= {"x" "y" "a" "x" "d x" "m=f" "m" "2"} (query-map url))))) (deftest raw-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d%20x" "a" "m"] (raw-keys url))))) (deftest query-keys-test (let [url "http://www.test.net/some/path?x=y&a=w&d%20x=m%3Df&a=x&m=2"] (is (= ["x" "a" "d x" "a" "m"] (query-keys url))))) (deftest normalize-path-test (let [uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/here?x=y&a=b#a-fragment" (normalize-path uri))) (is (= (normalize-path "http://foo.org") "http://foo.org")))) (deftest resolve-path-test (let [the-uri "http://www.example.com/some/path/../awesome/./thing/../path/here?x=y&a=b#a-fragment"] (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/new/path/stuff?x=y&a=b#a-fragment" (normalize-path (resolve-path the-uri "new/path/stuff")))) (is (= "http://www.example.com/new/path/stuff?x=y&a=b#a-fragment" (resolve-path the-uri "/new/path/stuff"))) (is (= "http://www.example.com/some/awesome/path/here/new/path/stuff?x=y&a=b#a-fragment" (resolve-path "http://www.example.com/some/awesome/path/here/?x=y&a=b#a-fragment" "new/path/stuff"))) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") "y/asdf")) "http://www.example.com/asdf/y/asdf")) (is (= (str (resolve-path (uri "http://www.example.com/asdf/x") (uri "y/asdf"))) "http://www.example.com/asdf/y/asdf")) (is (= (resolve-path "http://foo.org" "data.html") "http://foo.org/data.html")) (is (= (resolve-path "http://foo.org" "/data.html") "http://foo.org/data.html")))) (deftest absolute?-test (is (absolute? "http://www.test.net/new/path?x=y&a=w")) (is (not (absolute? "/new/path?x=y&a=w")))) (deftest resolve-uri-test (let [the-base-uri "http://a/b/c/d;p?q=1/2"] (is (let [diff-host-uri "http://e/f"] (= (resolve-uri the-base-uri diff-host-uri) diff-host-uri))) (is (= (resolve-uri the-base-uri "g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "./g") "http://a/b/c/g")) (is (= (resolve-uri the-base-uri "g/") "http://a/b/c/g/")) (is (= (resolve-uri the-base-uri "/g") "http://a/g")) (is (= (resolve-uri the-base-uri "//g") "http://g")) (is (= (resolve-uri the-base-uri (URI. "//g")) (URI. "http://g"))) (is (= (resolve-uri the-base-uri "g?y") "http://a/b/c/g?y")) (is (= (resolve-uri (URI. the-base-uri) "g?y") (URI. "http://a/b/c/g?y"))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/./x")] (or (= resolved-uri "http://a/b/c/g?y/./x") (= resolved-uri "http://a/b/c/g?y/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g?y/../x")] (or (= resolved-uri "http://a/b/c/g?y/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "g#s") "http://a/b/c/g#s")) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/./x")] (or (= resolved-uri "http://a/b/c/g#s/./x") (= resolved-uri "http://a/b/c/g#s/x")))) (is (let [resolved-uri (resolve-uri the-base-uri "g#s/../x")] (or (= resolved-uri "http://a/b/c/g#s/../x") (= resolved-uri "http://a/b/c/x")))) (is (= (resolve-uri the-base-uri "./") "http://a/b/c/")) (is (= (resolve-uri the-base-uri "../") "http://a/b/")) (is (= (resolve-uri the-base-uri "../g") "http://a/b/g")) (is (= (resolve-uri the-base-uri "../../") "http://a/")) (is (= (resolve-uri the-base-uri "../../g") "http://a/g"))))
[ { "context": "doc \"Useful file manipulation fns\"\n :author \"Sam Aaron\"}\n overtone.helpers.file\n (:import [java.net UR", "end": 70, "score": 0.9998888373374939, "start": 61, "tag": "NAME", "value": "Sam Aaron" } ]
src/overtone/helpers/file.clj
fvides/overtone
1
(ns ^{:doc "Useful file manipulation fns" :author "Sam Aaron"} overtone.helpers.file (:import [java.net URL] [java.io StringWriter]) (:use [overtone.helpers.string] [clojure.java.io] [overtone.helpers.system :only [windows-os?]]) (:require [org.satta.glob :as satta-glob] [clojure.string :as str])) (def ^{:dynamic true} *verbose-overtone-file-helpers* false) (def ^{:dynamic true} *authorization-header* false) (defn get-current-directory [] (. (java.io.File. ".") getCanonicalPath)) (defn print-if-verbose "Prints the arguments if *verbose-overtone-file-helpers* is bound to true. If it is also bound to an integer, will print a corresponding number of spaces at the start of each line to indent the output." [& to-print] (when *verbose-overtone-file-helpers* (when (integer? *verbose-overtone-file-helpers*) (dotimes [_ *verbose-overtone-file-helpers*] (print " "))) (apply println to-print))) (defn pretty-file-size "Takes number of bytes and returns a prettied string with an appropriate unit: b, kb or mb." [n-bytes] (let [n-kb (int (/ n-bytes 1024)) n-mb (int (/ n-kb 1024))] (cond (< n-bytes 1024) (str n-bytes " B") (< n-kb 1024) (str n-kb " KB") :else (str n-mb " MB")))) (defn file? "Returns true if f is of type java.io.File" [f] (= java.io.File (type f))) (defn- files->abs-paths "Given a seq of java.io.File objects, returns a seq of absolute paths for each file." [files] (map #(.getAbsolutePath %) files)) (defn- files->names "Given a seq of java.io.File objects, returns a seq of names for each file." [files] (map #(.getName %) files)) (defn file-separator "Returns the system's file separator" [] java.io.File/separator) (defn home-dir "Returns the user's home directory" [] (System/getProperty "user.home")) (declare mk-path) (defn resolve-tilde-path "Returns a string which represents the resolution of paths starting with ~ to point to home directory." [path] (let [path (if (file? path) (.getCanonicalPath path) (str path))] (cond (= "~" path) (home-dir) (.startsWith path (str "~" (file-separator))) (mk-path (home-dir) (chop-first-n (inc (count (file-separator))) path)) :default path))) (defn ensure-trailing-file-separator "Returns a string representing the supplied path that ends with the appropriate file separator." [path] (let [path (resolve-tilde-path path)] (if (.endsWith path (file-separator)) path (str path (file-separator))))) (defn subdir? "Returns true if sdir is a subdirectory of dir" [sdir dir] (let [sdir (resolve-tilde-path sdir) sdir (ensure-trailing-file-separator sdir) dir (resolve-tilde-path dir) dir (ensure-trailing-file-separator dir)] (.startsWith sdir dir))) (defn mk-path "Takes a seq of strings and returns a string which is a concatanation of all the input strings separated by the system's default file separator." [& parts] (let [path (apply str (interpose (file-separator) parts))] (resolve-tilde-path path))) (defn canonical-path "Returns a string representing the canonical version of this path" [path] (let [path (resolve-tilde-path path) f (file path)] (.getCanonicalPath f))) (defn ls* "Given a path to a directory, returns a seq of java.io.File objects representing the directory contents" [path] (let [path (resolve-tilde-path path) f (file path)] (cond (.isFile f) (seq (cons f nil)) (.isDirectory f) (seq (.listFiles f)) :else (satta-glob/glob path)))) (defn ls-paths "Given a path to a directory, returns a seq of strings representing the full paths of all files and dirs within." [path] (files->abs-paths (ls* path))) (defn ls-names "Given a path to a directory, returns a seq of strings representing the names of all files and dirs within. Similar to ls in a shell." [path] (files->names (ls* path))) (defn ls-file-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->abs-paths files))) (defn ls-file-names "Given a path to a directory, returns a seq of strings representing the name of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->names files))) (defn ls-dir-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->abs-paths files))) (defn ls-dir-names "Given a path to a directory, returns a seq of strings representing the name of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->names files))) (defn glob "Given a glob pattern returns a seq of java.io.File instances which match. Ignores dot files unless explicitly included. Examples: (glob \"*.{jpg,gif}\") (glob \".*\") (glob \"/usr/*/se*\")" [pattern] (let [pattern (resolve-tilde-path pattern)] (satta-glob/glob pattern))) (defn remote-file-size "Returns the size of the file referenced by url in bytes." [url] (let [url (if (= URL (type url)) url (URL. url)) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.getContentLength con))) (defn- percentage-slices "Returns a seq of maps of length num-slices where each map represents the percentage and the associated percentage of size usage: (percentage-slices 1000 2) ;=> ({:perc 50N, :val 500N} {:perc 100, :val 1000})" [size num-slices] (map (fn [slice] (let [perc (/ (inc slice) num-slices)] {:perc (* 100 perc) :val (* size perc)})) (range num-slices))) (defn- print-file-copy-status "Print copy status in percentage - granularity times - evenly as num-copied-bytes approaches file-size" [num-copied-bytes buf-size file-size slices] (let [min num-copied-bytes max (+ buf-size num-copied-bytes)] (when-let [slice (some (fn [slice] (when (and (> (:val slice) min) (< (:val slice) max)) slice)) slices)] (print-if-verbose (str (:perc slice) "% (" (pretty-file-size num-copied-bytes) ") completed"))))) (defn- remote-file-copy [in-stream out-stream file-size] "Similar to the corresponding implementation of #'do-copy in 'clojure.java.io but also tracks how many bytes have been downloaded and prints percentage statements when *verbose-overtone-file-helpers* is bound to true." (let [buf-size 2048 buffer (make-array Byte/TYPE buf-size) slices (percentage-slices file-size 100)] (loop [bytes-copied 0] (let [size (.read in-stream buffer)] (print-file-copy-status bytes-copied size file-size slices) (when (pos? size) (do (.write out-stream buffer 0 size) (recur (+ size bytes-copied)))))) (print-if-verbose "--> Download successful"))) (defn- download-file-without-timeout "Downloads remote file at url to local file specified by target path. Has potential to block current thread whilst reading data from remote host. See download-file-with-timeout for a non-blocking version." [url target-path] (let [target-path (resolve-tilde-path target-path)] (with-open [in (input-stream url) out (output-stream target-path)] (copy in out)) target-path)) (defn- download-file-with-timeout "Downloads remote file at url to local file specified by target path. If data transfer stalls for more than timeout ms, throws a java.net.SocketTimeoutException" [url target-path timeout] (let [target-path (resolve-tilde-path target-path) size (remote-file-size url) url (URL. url) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (output-stream target-path)] (remote-file-copy in out size)) target-path)) (defn get-file-with-timeout "Returns a stringified version of the file pointed to by url. If download stalls for more than timeout ms an exception is thrown." [url timeout] (let [url (URL. url) con (.openConnection url) size (remote-file-size url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (StringWriter.)] ;; NOTE: this seems broken when size is -1, which happens when getContentLength is absent (copy in out size) (.toString out)))) (defn file-size "Returns the size of the file pointed to by path in bytes" [path] (let [path (resolve-tilde-path path)] (.length (file path)))) (defn file-name "Returns the name of path-or-file." [path-or-file] (.getName (file path-or-file))) (defn file-extension "Returns the file extension of path-or-file" [path-or-file] (let [name (file-name path-or-file)] (if (re-seq #"\.." name) (last (split-on-char name "."))))) (defn mkdir! "Makes a dir at path if it doesn't already exist." [path] (let [path (resolve-tilde-path path) f (file path)] (when-not (.exists f) (.mkdir f)))) (defn absolute-path? "Returns true if the path is absolute. false otherwise." [path] (let [path (resolve-tilde-path path) f (file path)] (.isAbsolute f))) (defn mkdir-p! "Makes a dir at path if it doesn't already exist. Also creates all subdirectories if necessary" [path] (let [path (resolve-tilde-path path) f (file path)] (.mkdirs f))) (defn rm-rf! "Removes a file or dir and all its subdirectories. Similar to rm -rf on *NIX" [path] (let [path (resolve-tilde-path path) file (file path)] (if (.isDirectory file) (let [children (.list file)] (doall (map #(rm-rf! (mk-path path %)) children)) (.delete file)) (.delete file)))) (defn mv! "Moves a file from source to dest path" [src dest] (let [src (resolve-tilde-path src) dest (resolve-tilde-path dest) f-src (file src) f-dest (file dest)] (when-not (.renameTo f-src f-dest) (copy f-src f-dest) (delete-file f-src)))) (defn path-exists? "Returns true if file or dir specified by path exists" [path] (let [path (canonical-path path) f (file path)] (.exists f))) (defn ensure-path-exists! "Throws an exception if path does not exist." [path] (when-not (path-exists? path) (throw (Exception. (str "Error: unable locate path: " path))))) (defn file-exists? "Returns true if a file specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isFile f)))) (defn dir-exists? "Returns true if a directory specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isDirectory f)))) (defn dir-empty? "Returns true if the directory specified by path is empty or doesn't exist" [path] (let [contents (ls-names path)] (empty? contents))) (defn mk-tmp-dir! "Creates a unique temporary directory on the filesystem. Typically in /tmp on *NIX systems. Returns a File object pointing to the new directory. Raises an exception if the directory couldn't be created after 10000 tries." [] (let [base-dir (file (System/getProperty "java.io.tmpdir")) base-name (str (System/currentTimeMillis) "-" (long (rand 1000000000)) "-") tmp-base (mk-path base-dir base-name) max-attempts 10000] (loop [num-attempts 1] (if (= num-attempts max-attempts) (throw (Exception. (str "Failed to create temporary directory after " max-attempts " attempts."))) (let [tmp-dir-name (str tmp-base num-attempts) tmp-dir (file tmp-dir-name)] (if (.mkdir tmp-dir) tmp-dir (recur (inc num-attempts)))))))) (defn- download-file* ([url path] (download-file-without-timeout url path)) ([url path timeout] (download-file-with-timeout url path timeout)) ([url path timeout n-retries] (download-file* url path timeout n-retries 5000)) ([url path timeout n-retries wait-t] (download-file* url path timeout n-retries wait-t 0)) ([url path timeout n-retries wait-t attempts-made] (when (>= attempts-made n-retries) (throw (Exception. (str "Aborting! Download failed after " n-retries " attempts. URL attempted to download: " url )))) (let [path (resolve-tilde-path path)] (try (download-file-with-timeout url path timeout) (catch java.io.FileNotFoundException e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download failed. File not found: " url )) (throw (Exception. (str "Aborting! Download failed. File not found: " url )))) (catch Exception e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download timed out. Retry " (inc attempts-made) ": " url )) (download-file* url path timeout n-retries wait-t (inc attempts-made))))))) (defn- print-download-file [url] (let [size (remote-file-size url) p-size (pretty-file-size size) size-str (if (<= size 0) "" (str "(" p-size ")"))] (print-if-verbose (str "--> Downloading file " size-str " - " url)))) (defn download-file "Downloads the file pointed to by url to local path. If no timeout is specified will use blocking io to transfer data. If timeout is specified, transfer will block for at most timeout ms before throwing a java.net.SocketTimeoutException if data transfer has stalled. It's also possible to specify n-retries to determine how many attempts to make to download the file and also the wait-t between attempts in ms (defaults to 5000 ms) Verbose mode is enabled by binding *verbose-overtone-file-helpers* to true." ([url path] (print-download-file url) (download-file* url path)) ([url path timeout] (print-download-file url) (download-file* url path timeout)) ([url path timeout n-retries] (print-download-file url) (download-file* url path timeout n-retries)) ([url path timeout n-retries wait-t] (print-download-file url) (download-file* url path timeout n-retries wait-t)))
46358
(ns ^{:doc "Useful file manipulation fns" :author "<NAME>"} overtone.helpers.file (:import [java.net URL] [java.io StringWriter]) (:use [overtone.helpers.string] [clojure.java.io] [overtone.helpers.system :only [windows-os?]]) (:require [org.satta.glob :as satta-glob] [clojure.string :as str])) (def ^{:dynamic true} *verbose-overtone-file-helpers* false) (def ^{:dynamic true} *authorization-header* false) (defn get-current-directory [] (. (java.io.File. ".") getCanonicalPath)) (defn print-if-verbose "Prints the arguments if *verbose-overtone-file-helpers* is bound to true. If it is also bound to an integer, will print a corresponding number of spaces at the start of each line to indent the output." [& to-print] (when *verbose-overtone-file-helpers* (when (integer? *verbose-overtone-file-helpers*) (dotimes [_ *verbose-overtone-file-helpers*] (print " "))) (apply println to-print))) (defn pretty-file-size "Takes number of bytes and returns a prettied string with an appropriate unit: b, kb or mb." [n-bytes] (let [n-kb (int (/ n-bytes 1024)) n-mb (int (/ n-kb 1024))] (cond (< n-bytes 1024) (str n-bytes " B") (< n-kb 1024) (str n-kb " KB") :else (str n-mb " MB")))) (defn file? "Returns true if f is of type java.io.File" [f] (= java.io.File (type f))) (defn- files->abs-paths "Given a seq of java.io.File objects, returns a seq of absolute paths for each file." [files] (map #(.getAbsolutePath %) files)) (defn- files->names "Given a seq of java.io.File objects, returns a seq of names for each file." [files] (map #(.getName %) files)) (defn file-separator "Returns the system's file separator" [] java.io.File/separator) (defn home-dir "Returns the user's home directory" [] (System/getProperty "user.home")) (declare mk-path) (defn resolve-tilde-path "Returns a string which represents the resolution of paths starting with ~ to point to home directory." [path] (let [path (if (file? path) (.getCanonicalPath path) (str path))] (cond (= "~" path) (home-dir) (.startsWith path (str "~" (file-separator))) (mk-path (home-dir) (chop-first-n (inc (count (file-separator))) path)) :default path))) (defn ensure-trailing-file-separator "Returns a string representing the supplied path that ends with the appropriate file separator." [path] (let [path (resolve-tilde-path path)] (if (.endsWith path (file-separator)) path (str path (file-separator))))) (defn subdir? "Returns true if sdir is a subdirectory of dir" [sdir dir] (let [sdir (resolve-tilde-path sdir) sdir (ensure-trailing-file-separator sdir) dir (resolve-tilde-path dir) dir (ensure-trailing-file-separator dir)] (.startsWith sdir dir))) (defn mk-path "Takes a seq of strings and returns a string which is a concatanation of all the input strings separated by the system's default file separator." [& parts] (let [path (apply str (interpose (file-separator) parts))] (resolve-tilde-path path))) (defn canonical-path "Returns a string representing the canonical version of this path" [path] (let [path (resolve-tilde-path path) f (file path)] (.getCanonicalPath f))) (defn ls* "Given a path to a directory, returns a seq of java.io.File objects representing the directory contents" [path] (let [path (resolve-tilde-path path) f (file path)] (cond (.isFile f) (seq (cons f nil)) (.isDirectory f) (seq (.listFiles f)) :else (satta-glob/glob path)))) (defn ls-paths "Given a path to a directory, returns a seq of strings representing the full paths of all files and dirs within." [path] (files->abs-paths (ls* path))) (defn ls-names "Given a path to a directory, returns a seq of strings representing the names of all files and dirs within. Similar to ls in a shell." [path] (files->names (ls* path))) (defn ls-file-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->abs-paths files))) (defn ls-file-names "Given a path to a directory, returns a seq of strings representing the name of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->names files))) (defn ls-dir-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->abs-paths files))) (defn ls-dir-names "Given a path to a directory, returns a seq of strings representing the name of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->names files))) (defn glob "Given a glob pattern returns a seq of java.io.File instances which match. Ignores dot files unless explicitly included. Examples: (glob \"*.{jpg,gif}\") (glob \".*\") (glob \"/usr/*/se*\")" [pattern] (let [pattern (resolve-tilde-path pattern)] (satta-glob/glob pattern))) (defn remote-file-size "Returns the size of the file referenced by url in bytes." [url] (let [url (if (= URL (type url)) url (URL. url)) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.getContentLength con))) (defn- percentage-slices "Returns a seq of maps of length num-slices where each map represents the percentage and the associated percentage of size usage: (percentage-slices 1000 2) ;=> ({:perc 50N, :val 500N} {:perc 100, :val 1000})" [size num-slices] (map (fn [slice] (let [perc (/ (inc slice) num-slices)] {:perc (* 100 perc) :val (* size perc)})) (range num-slices))) (defn- print-file-copy-status "Print copy status in percentage - granularity times - evenly as num-copied-bytes approaches file-size" [num-copied-bytes buf-size file-size slices] (let [min num-copied-bytes max (+ buf-size num-copied-bytes)] (when-let [slice (some (fn [slice] (when (and (> (:val slice) min) (< (:val slice) max)) slice)) slices)] (print-if-verbose (str (:perc slice) "% (" (pretty-file-size num-copied-bytes) ") completed"))))) (defn- remote-file-copy [in-stream out-stream file-size] "Similar to the corresponding implementation of #'do-copy in 'clojure.java.io but also tracks how many bytes have been downloaded and prints percentage statements when *verbose-overtone-file-helpers* is bound to true." (let [buf-size 2048 buffer (make-array Byte/TYPE buf-size) slices (percentage-slices file-size 100)] (loop [bytes-copied 0] (let [size (.read in-stream buffer)] (print-file-copy-status bytes-copied size file-size slices) (when (pos? size) (do (.write out-stream buffer 0 size) (recur (+ size bytes-copied)))))) (print-if-verbose "--> Download successful"))) (defn- download-file-without-timeout "Downloads remote file at url to local file specified by target path. Has potential to block current thread whilst reading data from remote host. See download-file-with-timeout for a non-blocking version." [url target-path] (let [target-path (resolve-tilde-path target-path)] (with-open [in (input-stream url) out (output-stream target-path)] (copy in out)) target-path)) (defn- download-file-with-timeout "Downloads remote file at url to local file specified by target path. If data transfer stalls for more than timeout ms, throws a java.net.SocketTimeoutException" [url target-path timeout] (let [target-path (resolve-tilde-path target-path) size (remote-file-size url) url (URL. url) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (output-stream target-path)] (remote-file-copy in out size)) target-path)) (defn get-file-with-timeout "Returns a stringified version of the file pointed to by url. If download stalls for more than timeout ms an exception is thrown." [url timeout] (let [url (URL. url) con (.openConnection url) size (remote-file-size url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (StringWriter.)] ;; NOTE: this seems broken when size is -1, which happens when getContentLength is absent (copy in out size) (.toString out)))) (defn file-size "Returns the size of the file pointed to by path in bytes" [path] (let [path (resolve-tilde-path path)] (.length (file path)))) (defn file-name "Returns the name of path-or-file." [path-or-file] (.getName (file path-or-file))) (defn file-extension "Returns the file extension of path-or-file" [path-or-file] (let [name (file-name path-or-file)] (if (re-seq #"\.." name) (last (split-on-char name "."))))) (defn mkdir! "Makes a dir at path if it doesn't already exist." [path] (let [path (resolve-tilde-path path) f (file path)] (when-not (.exists f) (.mkdir f)))) (defn absolute-path? "Returns true if the path is absolute. false otherwise." [path] (let [path (resolve-tilde-path path) f (file path)] (.isAbsolute f))) (defn mkdir-p! "Makes a dir at path if it doesn't already exist. Also creates all subdirectories if necessary" [path] (let [path (resolve-tilde-path path) f (file path)] (.mkdirs f))) (defn rm-rf! "Removes a file or dir and all its subdirectories. Similar to rm -rf on *NIX" [path] (let [path (resolve-tilde-path path) file (file path)] (if (.isDirectory file) (let [children (.list file)] (doall (map #(rm-rf! (mk-path path %)) children)) (.delete file)) (.delete file)))) (defn mv! "Moves a file from source to dest path" [src dest] (let [src (resolve-tilde-path src) dest (resolve-tilde-path dest) f-src (file src) f-dest (file dest)] (when-not (.renameTo f-src f-dest) (copy f-src f-dest) (delete-file f-src)))) (defn path-exists? "Returns true if file or dir specified by path exists" [path] (let [path (canonical-path path) f (file path)] (.exists f))) (defn ensure-path-exists! "Throws an exception if path does not exist." [path] (when-not (path-exists? path) (throw (Exception. (str "Error: unable locate path: " path))))) (defn file-exists? "Returns true if a file specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isFile f)))) (defn dir-exists? "Returns true if a directory specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isDirectory f)))) (defn dir-empty? "Returns true if the directory specified by path is empty or doesn't exist" [path] (let [contents (ls-names path)] (empty? contents))) (defn mk-tmp-dir! "Creates a unique temporary directory on the filesystem. Typically in /tmp on *NIX systems. Returns a File object pointing to the new directory. Raises an exception if the directory couldn't be created after 10000 tries." [] (let [base-dir (file (System/getProperty "java.io.tmpdir")) base-name (str (System/currentTimeMillis) "-" (long (rand 1000000000)) "-") tmp-base (mk-path base-dir base-name) max-attempts 10000] (loop [num-attempts 1] (if (= num-attempts max-attempts) (throw (Exception. (str "Failed to create temporary directory after " max-attempts " attempts."))) (let [tmp-dir-name (str tmp-base num-attempts) tmp-dir (file tmp-dir-name)] (if (.mkdir tmp-dir) tmp-dir (recur (inc num-attempts)))))))) (defn- download-file* ([url path] (download-file-without-timeout url path)) ([url path timeout] (download-file-with-timeout url path timeout)) ([url path timeout n-retries] (download-file* url path timeout n-retries 5000)) ([url path timeout n-retries wait-t] (download-file* url path timeout n-retries wait-t 0)) ([url path timeout n-retries wait-t attempts-made] (when (>= attempts-made n-retries) (throw (Exception. (str "Aborting! Download failed after " n-retries " attempts. URL attempted to download: " url )))) (let [path (resolve-tilde-path path)] (try (download-file-with-timeout url path timeout) (catch java.io.FileNotFoundException e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download failed. File not found: " url )) (throw (Exception. (str "Aborting! Download failed. File not found: " url )))) (catch Exception e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download timed out. Retry " (inc attempts-made) ": " url )) (download-file* url path timeout n-retries wait-t (inc attempts-made))))))) (defn- print-download-file [url] (let [size (remote-file-size url) p-size (pretty-file-size size) size-str (if (<= size 0) "" (str "(" p-size ")"))] (print-if-verbose (str "--> Downloading file " size-str " - " url)))) (defn download-file "Downloads the file pointed to by url to local path. If no timeout is specified will use blocking io to transfer data. If timeout is specified, transfer will block for at most timeout ms before throwing a java.net.SocketTimeoutException if data transfer has stalled. It's also possible to specify n-retries to determine how many attempts to make to download the file and also the wait-t between attempts in ms (defaults to 5000 ms) Verbose mode is enabled by binding *verbose-overtone-file-helpers* to true." ([url path] (print-download-file url) (download-file* url path)) ([url path timeout] (print-download-file url) (download-file* url path timeout)) ([url path timeout n-retries] (print-download-file url) (download-file* url path timeout n-retries)) ([url path timeout n-retries wait-t] (print-download-file url) (download-file* url path timeout n-retries wait-t)))
true
(ns ^{:doc "Useful file manipulation fns" :author "PI:NAME:<NAME>END_PI"} overtone.helpers.file (:import [java.net URL] [java.io StringWriter]) (:use [overtone.helpers.string] [clojure.java.io] [overtone.helpers.system :only [windows-os?]]) (:require [org.satta.glob :as satta-glob] [clojure.string :as str])) (def ^{:dynamic true} *verbose-overtone-file-helpers* false) (def ^{:dynamic true} *authorization-header* false) (defn get-current-directory [] (. (java.io.File. ".") getCanonicalPath)) (defn print-if-verbose "Prints the arguments if *verbose-overtone-file-helpers* is bound to true. If it is also bound to an integer, will print a corresponding number of spaces at the start of each line to indent the output." [& to-print] (when *verbose-overtone-file-helpers* (when (integer? *verbose-overtone-file-helpers*) (dotimes [_ *verbose-overtone-file-helpers*] (print " "))) (apply println to-print))) (defn pretty-file-size "Takes number of bytes and returns a prettied string with an appropriate unit: b, kb or mb." [n-bytes] (let [n-kb (int (/ n-bytes 1024)) n-mb (int (/ n-kb 1024))] (cond (< n-bytes 1024) (str n-bytes " B") (< n-kb 1024) (str n-kb " KB") :else (str n-mb " MB")))) (defn file? "Returns true if f is of type java.io.File" [f] (= java.io.File (type f))) (defn- files->abs-paths "Given a seq of java.io.File objects, returns a seq of absolute paths for each file." [files] (map #(.getAbsolutePath %) files)) (defn- files->names "Given a seq of java.io.File objects, returns a seq of names for each file." [files] (map #(.getName %) files)) (defn file-separator "Returns the system's file separator" [] java.io.File/separator) (defn home-dir "Returns the user's home directory" [] (System/getProperty "user.home")) (declare mk-path) (defn resolve-tilde-path "Returns a string which represents the resolution of paths starting with ~ to point to home directory." [path] (let [path (if (file? path) (.getCanonicalPath path) (str path))] (cond (= "~" path) (home-dir) (.startsWith path (str "~" (file-separator))) (mk-path (home-dir) (chop-first-n (inc (count (file-separator))) path)) :default path))) (defn ensure-trailing-file-separator "Returns a string representing the supplied path that ends with the appropriate file separator." [path] (let [path (resolve-tilde-path path)] (if (.endsWith path (file-separator)) path (str path (file-separator))))) (defn subdir? "Returns true if sdir is a subdirectory of dir" [sdir dir] (let [sdir (resolve-tilde-path sdir) sdir (ensure-trailing-file-separator sdir) dir (resolve-tilde-path dir) dir (ensure-trailing-file-separator dir)] (.startsWith sdir dir))) (defn mk-path "Takes a seq of strings and returns a string which is a concatanation of all the input strings separated by the system's default file separator." [& parts] (let [path (apply str (interpose (file-separator) parts))] (resolve-tilde-path path))) (defn canonical-path "Returns a string representing the canonical version of this path" [path] (let [path (resolve-tilde-path path) f (file path)] (.getCanonicalPath f))) (defn ls* "Given a path to a directory, returns a seq of java.io.File objects representing the directory contents" [path] (let [path (resolve-tilde-path path) f (file path)] (cond (.isFile f) (seq (cons f nil)) (.isDirectory f) (seq (.listFiles f)) :else (satta-glob/glob path)))) (defn ls-paths "Given a path to a directory, returns a seq of strings representing the full paths of all files and dirs within." [path] (files->abs-paths (ls* path))) (defn ls-names "Given a path to a directory, returns a seq of strings representing the names of all files and dirs within. Similar to ls in a shell." [path] (files->names (ls* path))) (defn ls-file-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->abs-paths files))) (defn ls-file-names "Given a path to a directory, returns a seq of strings representing the name of only the files within." [path] (let [files (filter #(.isFile %) (ls* path))] (files->names files))) (defn ls-dir-paths "Given a path to a directory, returns a seq of strings representing the full paths of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->abs-paths files))) (defn ls-dir-names "Given a path to a directory, returns a seq of strings representing the name of only the dirs within. " [path] (let [files (filter #(.isDirectory %) (ls* path))] (files->names files))) (defn glob "Given a glob pattern returns a seq of java.io.File instances which match. Ignores dot files unless explicitly included. Examples: (glob \"*.{jpg,gif}\") (glob \".*\") (glob \"/usr/*/se*\")" [pattern] (let [pattern (resolve-tilde-path pattern)] (satta-glob/glob pattern))) (defn remote-file-size "Returns the size of the file referenced by url in bytes." [url] (let [url (if (= URL (type url)) url (URL. url)) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.getContentLength con))) (defn- percentage-slices "Returns a seq of maps of length num-slices where each map represents the percentage and the associated percentage of size usage: (percentage-slices 1000 2) ;=> ({:perc 50N, :val 500N} {:perc 100, :val 1000})" [size num-slices] (map (fn [slice] (let [perc (/ (inc slice) num-slices)] {:perc (* 100 perc) :val (* size perc)})) (range num-slices))) (defn- print-file-copy-status "Print copy status in percentage - granularity times - evenly as num-copied-bytes approaches file-size" [num-copied-bytes buf-size file-size slices] (let [min num-copied-bytes max (+ buf-size num-copied-bytes)] (when-let [slice (some (fn [slice] (when (and (> (:val slice) min) (< (:val slice) max)) slice)) slices)] (print-if-verbose (str (:perc slice) "% (" (pretty-file-size num-copied-bytes) ") completed"))))) (defn- remote-file-copy [in-stream out-stream file-size] "Similar to the corresponding implementation of #'do-copy in 'clojure.java.io but also tracks how many bytes have been downloaded and prints percentage statements when *verbose-overtone-file-helpers* is bound to true." (let [buf-size 2048 buffer (make-array Byte/TYPE buf-size) slices (percentage-slices file-size 100)] (loop [bytes-copied 0] (let [size (.read in-stream buffer)] (print-file-copy-status bytes-copied size file-size slices) (when (pos? size) (do (.write out-stream buffer 0 size) (recur (+ size bytes-copied)))))) (print-if-verbose "--> Download successful"))) (defn- download-file-without-timeout "Downloads remote file at url to local file specified by target path. Has potential to block current thread whilst reading data from remote host. See download-file-with-timeout for a non-blocking version." [url target-path] (let [target-path (resolve-tilde-path target-path)] (with-open [in (input-stream url) out (output-stream target-path)] (copy in out)) target-path)) (defn- download-file-with-timeout "Downloads remote file at url to local file specified by target path. If data transfer stalls for more than timeout ms, throws a java.net.SocketTimeoutException" [url target-path timeout] (let [target-path (resolve-tilde-path target-path) size (remote-file-size url) url (URL. url) con (.openConnection url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (output-stream target-path)] (remote-file-copy in out size)) target-path)) (defn get-file-with-timeout "Returns a stringified version of the file pointed to by url. If download stalls for more than timeout ms an exception is thrown." [url timeout] (let [url (URL. url) con (.openConnection url) size (remote-file-size url)] (when *authorization-header* (.setRequestProperty con "Authorization" (*authorization-header*))) (.setReadTimeout con timeout) (with-open [in (.getInputStream con) out (StringWriter.)] ;; NOTE: this seems broken when size is -1, which happens when getContentLength is absent (copy in out size) (.toString out)))) (defn file-size "Returns the size of the file pointed to by path in bytes" [path] (let [path (resolve-tilde-path path)] (.length (file path)))) (defn file-name "Returns the name of path-or-file." [path-or-file] (.getName (file path-or-file))) (defn file-extension "Returns the file extension of path-or-file" [path-or-file] (let [name (file-name path-or-file)] (if (re-seq #"\.." name) (last (split-on-char name "."))))) (defn mkdir! "Makes a dir at path if it doesn't already exist." [path] (let [path (resolve-tilde-path path) f (file path)] (when-not (.exists f) (.mkdir f)))) (defn absolute-path? "Returns true if the path is absolute. false otherwise." [path] (let [path (resolve-tilde-path path) f (file path)] (.isAbsolute f))) (defn mkdir-p! "Makes a dir at path if it doesn't already exist. Also creates all subdirectories if necessary" [path] (let [path (resolve-tilde-path path) f (file path)] (.mkdirs f))) (defn rm-rf! "Removes a file or dir and all its subdirectories. Similar to rm -rf on *NIX" [path] (let [path (resolve-tilde-path path) file (file path)] (if (.isDirectory file) (let [children (.list file)] (doall (map #(rm-rf! (mk-path path %)) children)) (.delete file)) (.delete file)))) (defn mv! "Moves a file from source to dest path" [src dest] (let [src (resolve-tilde-path src) dest (resolve-tilde-path dest) f-src (file src) f-dest (file dest)] (when-not (.renameTo f-src f-dest) (copy f-src f-dest) (delete-file f-src)))) (defn path-exists? "Returns true if file or dir specified by path exists" [path] (let [path (canonical-path path) f (file path)] (.exists f))) (defn ensure-path-exists! "Throws an exception if path does not exist." [path] (when-not (path-exists? path) (throw (Exception. (str "Error: unable locate path: " path))))) (defn file-exists? "Returns true if a file specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isFile f)))) (defn dir-exists? "Returns true if a directory specified by path exists" [path] (let [path (resolve-tilde-path path) f (file path)] (and (.exists f) (.isDirectory f)))) (defn dir-empty? "Returns true if the directory specified by path is empty or doesn't exist" [path] (let [contents (ls-names path)] (empty? contents))) (defn mk-tmp-dir! "Creates a unique temporary directory on the filesystem. Typically in /tmp on *NIX systems. Returns a File object pointing to the new directory. Raises an exception if the directory couldn't be created after 10000 tries." [] (let [base-dir (file (System/getProperty "java.io.tmpdir")) base-name (str (System/currentTimeMillis) "-" (long (rand 1000000000)) "-") tmp-base (mk-path base-dir base-name) max-attempts 10000] (loop [num-attempts 1] (if (= num-attempts max-attempts) (throw (Exception. (str "Failed to create temporary directory after " max-attempts " attempts."))) (let [tmp-dir-name (str tmp-base num-attempts) tmp-dir (file tmp-dir-name)] (if (.mkdir tmp-dir) tmp-dir (recur (inc num-attempts)))))))) (defn- download-file* ([url path] (download-file-without-timeout url path)) ([url path timeout] (download-file-with-timeout url path timeout)) ([url path timeout n-retries] (download-file* url path timeout n-retries 5000)) ([url path timeout n-retries wait-t] (download-file* url path timeout n-retries wait-t 0)) ([url path timeout n-retries wait-t attempts-made] (when (>= attempts-made n-retries) (throw (Exception. (str "Aborting! Download failed after " n-retries " attempts. URL attempted to download: " url )))) (let [path (resolve-tilde-path path)] (try (download-file-with-timeout url path timeout) (catch java.io.FileNotFoundException e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download failed. File not found: " url )) (throw (Exception. (str "Aborting! Download failed. File not found: " url )))) (catch Exception e (rm-rf! path) (Thread/sleep wait-t) (print-if-verbose (str "Download timed out. Retry " (inc attempts-made) ": " url )) (download-file* url path timeout n-retries wait-t (inc attempts-made))))))) (defn- print-download-file [url] (let [size (remote-file-size url) p-size (pretty-file-size size) size-str (if (<= size 0) "" (str "(" p-size ")"))] (print-if-verbose (str "--> Downloading file " size-str " - " url)))) (defn download-file "Downloads the file pointed to by url to local path. If no timeout is specified will use blocking io to transfer data. If timeout is specified, transfer will block for at most timeout ms before throwing a java.net.SocketTimeoutException if data transfer has stalled. It's also possible to specify n-retries to determine how many attempts to make to download the file and also the wait-t between attempts in ms (defaults to 5000 ms) Verbose mode is enabled by binding *verbose-overtone-file-helpers* to true." ([url path] (print-download-file url) (download-file* url path)) ([url path timeout] (print-download-file url) (download-file* url path timeout)) ([url path timeout n-retries] (print-download-file url) (download-file* url path timeout n-retries)) ([url path timeout n-retries wait-t] (print-download-file url) (download-file* url path timeout n-retries wait-t)))
[ { "context": " (json/write-str {\"player\" \"Russell Westbrook\"\n ", "end": 648, "score": 0.9998772740364075, "start": 631, "tag": "NAME", "value": "Russell Westbrook" } ]
test/nbaviz/handler_test.clj
anqurvanillapy/nbaviz
0
(ns nbaviz.handler-test (:require [clojure.test :refer :all] [clojure.string :as string] [clojure.data.json :as json] [ring.mock.request :as mock] [nbaviz.handler :refer :all])) (deftest test-app (testing "main route" (let [response (app (mock/request :get "/"))] (is (= (:status response) 302)) (is (= (last (string/split (get (:headers response) "Location") #"/")) "index.html")))) (testing "POST player name route" (let [response (app (-> (mock/request :post "/player" (json/write-str {"player" "Russell Westbrook" "attrs" ["teamname"]})) (mock/content-type "application/json")))] (is (= (:status response) 200)) (let [body (json/read-str (:body response))] (is (= (get body "ok") true)) (is (= (get (first (get body "data")) "teamname") "Oklahoma City Thunder"))))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))
30437
(ns nbaviz.handler-test (:require [clojure.test :refer :all] [clojure.string :as string] [clojure.data.json :as json] [ring.mock.request :as mock] [nbaviz.handler :refer :all])) (deftest test-app (testing "main route" (let [response (app (mock/request :get "/"))] (is (= (:status response) 302)) (is (= (last (string/split (get (:headers response) "Location") #"/")) "index.html")))) (testing "POST player name route" (let [response (app (-> (mock/request :post "/player" (json/write-str {"player" "<NAME>" "attrs" ["teamname"]})) (mock/content-type "application/json")))] (is (= (:status response) 200)) (let [body (json/read-str (:body response))] (is (= (get body "ok") true)) (is (= (get (first (get body "data")) "teamname") "Oklahoma City Thunder"))))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))
true
(ns nbaviz.handler-test (:require [clojure.test :refer :all] [clojure.string :as string] [clojure.data.json :as json] [ring.mock.request :as mock] [nbaviz.handler :refer :all])) (deftest test-app (testing "main route" (let [response (app (mock/request :get "/"))] (is (= (:status response) 302)) (is (= (last (string/split (get (:headers response) "Location") #"/")) "index.html")))) (testing "POST player name route" (let [response (app (-> (mock/request :post "/player" (json/write-str {"player" "PI:NAME:<NAME>END_PI" "attrs" ["teamname"]})) (mock/content-type "application/json")))] (is (= (:status response) 200)) (let [body (json/read-str (:body response))] (is (= (get body "ok") true)) (is (= (get (first (get body "data")) "teamname") "Oklahoma City Thunder"))))) (testing "not-found route" (let [response (app (mock/request :get "/invalid"))] (is (= (:status response) 404)))))
[ { "context": " :username \"testuser\" :password \"testuser1!\"\n ", "end": 1523, "score": 0.9988883137702942, "start": 1515, "tag": "USERNAME", "value": "testuser" }, { "context": " :username \"testuser\" :password \"testuser1!\"\n ", "end": 1545, "score": 0.9990754723548889, "start": 1536, "tag": "PASSWORD", "value": "testuser1" }, { "context": "d-> []\n (in-container?) (conj :username \"testuser\" :password \"testuser1!\")\n (and (in-conta", "end": 6035, "score": 0.9995183944702148, "start": 6027, "tag": "USERNAME", "value": "testuser" }, { "context": "container?) (conj :username \"testuser\" :password \"testuser1!\")\n (and (in-container?) (not (in-eap?))) (", "end": 6057, "score": 0.9873323440551758, "start": 6048, "tag": "PASSWORD", "value": "testuser1" } ]
transactions/test/immutant/transactions_test.clj
Elknar/immutant
275
;; Copyright 2014-2017 Red Hat, Inc, and individual contributors. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns immutant.transactions-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [immutant.transactions :refer :all] [immutant.transactions.scope :refer (required not-supported)] [immutant.util :refer [in-container? in-eap? set-log-level! messaging-remoting-port]] [immutant.messaging :as msg] [immutant.caching :as csh] [clojure.java.jdbc :as sql])) (set-log-level! (or (System/getenv "LOG_LEVEL") :OFF)) (def cache (csh/cache "tx-test" :transactional? true)) (def queue (msg/queue "/queue/test" :durable? false)) (def local-remote-queue (msg/queue "remote" :durable? false)) (def conn (delay (msg/context (cond-> {:host "localhost" :xa? true} (in-container?) (assoc :port (messaging-remoting-port) :username "testuser" :password "testuser1!" :remote-type :hornetq-wildfly) (in-eap?) (dissoc :remote-type))))) (def remote-queue (delay (msg/queue "remote" :context @conn))) (def trigger (msg/queue "/queue/trigger" :durable? false)) (def spec {:connection-uri "jdbc:h2:mem:ooc;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"}) (use-fixtures :each (fn [f] (.clear cache) (try (sql/db-do-commands spec [(sql/drop-table-ddl :things) (sql/create-table-ddl :things [[:name "varchar(50)"]])]) (catch Exception _)) (f))) (use-fixtures :once (fn [f] (f) (.close @conn))) ;;; Helper methods to verify database activity (defn write-thing-to-db [spec name] (sql/insert! spec :things {:name name})) (defn read-thing-from-db [spec name] (-> (sql/query spec ["select name from things where name = ?" name]) first)) (defn count-things-in-db [spec] (-> (sql/query spec ["select count(*) c from things"]) first :c int)) (defn work [m] (csh/swap-in! cache :a (constantly 1)) (msg/publish queue "kiwi") (msg/publish @remote-queue "starfruit") (not-supported (csh/swap-in! cache :deliveries (fnil inc 0))) (sql/with-db-transaction [t spec] (write-thing-to-db t "tangerine") (when (:throw? m) (throw (Exception. "rollback"))) (when (:rollback? m) (set-rollback-only) (sql/db-set-rollback-only! t)))) (defn listener [m] (if (:tx? m) (transaction (work m)) (work m))) (defn attempt-transaction-external [& {:as m}] (try (with-open [conn (msg/context :xa? true)] (transaction (msg/publish queue "pineapple" :context conn) (work m))) (catch Exception e (-> e .getMessage)))) (defn attempt-transaction-internal [& {:as m}] (try (transaction (work m)) (catch Exception e (-> e .getMessage)))) (defn verify-success [] (is (= "kiwi" (msg/receive queue :timeout 1000))) (is (= "starfruit" (msg/receive local-remote-queue :timeout 1000))) (is (= 1 (:a cache))) (is (= "tangerine" (:name (read-thing-from-db spec "tangerine")))) (is (= 1 (count-things-in-db spec)))) (defn verify-failure [] (is (nil? (msg/receive queue :timeout 1000))) (is (nil? (msg/receive local-remote-queue :timeout 1000))) (is (nil? (:a cache))) (is (nil? (read-thing-from-db spec "tangerine"))) (is (= 0 (count-things-in-db spec)))) (deftest verify-transaction-success-external (is (nil? (attempt-transaction-external))) (is (= "pineapple" (msg/receive queue :timeout 1000))) (verify-success)) (deftest verify-transaction-failure-external (is (= "rollback" (attempt-transaction-external :throw? true))) (verify-failure)) (deftest verify-transaction-success-internal (is (nil? (attempt-transaction-internal))) (verify-success)) (deftest verify-transaction-failure-internal (is (= "rollback" (attempt-transaction-internal :throw? true))) (verify-failure)) (deftest transactional-receive (msg/publish queue "foo") (required (msg/receive queue) (set-rollback-only)) (is (= "foo" (msg/receive queue :timeout 1000)))) (deftest transactional-writes-in-listener-should-work (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true}) (verify-success))) (deftest transactional-writes-in-listener-should-fail-on-exception (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :throw? true}) (verify-failure) (is (= 10 (:deliveries cache))))) (deftest transactional-writes-in-listener-should-fail-on-rollback (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :rollback? true}) (verify-failure) (is (= 1 (:deliveries cache))))) (deftest non-transactional-writes-in-listener-with-exception (with-open [_ (msg/listen trigger listener :mode :auto-ack)] (msg/publish trigger {:throw? true}) (is (= 10 (loop [i 0] (Thread/sleep 100) (if (or (= 50 i) (= 10 (:deliveries cache))) (:deliveries cache) (recur (inc i)))))) (is (= 1 (:a cache))) (is (= (repeat 10 "kiwi") (repeatedly 10 #(msg/receive queue)))) (is (= (repeat 10 "starfruit") (repeatedly 10 #(msg/receive local-remote-queue)))))) (deftest remote-xa-listen-should-work (msg/queue "remote-xa-listen" :durable? false) (let [extra-connect-opts (cond-> [] (in-container?) (conj :username "testuser" :password "testuser1!") (and (in-container?) (not (in-eap?))) (conj :remote-type :hornetq-wildfly))] (with-open [c (apply msg/context :host "localhost" :port (messaging-remoting-port) :xa? true extra-connect-opts)] (let [q (msg/queue "remote-xa-listen" :context c) p (promise)] (with-open [listener (msg/listen q (partial deliver p))] (msg/publish q :hi) (is (= :hi (deref p 60000 :fail))))))))
39567
;; Copyright 2014-2017 Red Hat, Inc, and individual contributors. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns immutant.transactions-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [immutant.transactions :refer :all] [immutant.transactions.scope :refer (required not-supported)] [immutant.util :refer [in-container? in-eap? set-log-level! messaging-remoting-port]] [immutant.messaging :as msg] [immutant.caching :as csh] [clojure.java.jdbc :as sql])) (set-log-level! (or (System/getenv "LOG_LEVEL") :OFF)) (def cache (csh/cache "tx-test" :transactional? true)) (def queue (msg/queue "/queue/test" :durable? false)) (def local-remote-queue (msg/queue "remote" :durable? false)) (def conn (delay (msg/context (cond-> {:host "localhost" :xa? true} (in-container?) (assoc :port (messaging-remoting-port) :username "testuser" :password "<PASSWORD>!" :remote-type :hornetq-wildfly) (in-eap?) (dissoc :remote-type))))) (def remote-queue (delay (msg/queue "remote" :context @conn))) (def trigger (msg/queue "/queue/trigger" :durable? false)) (def spec {:connection-uri "jdbc:h2:mem:ooc;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"}) (use-fixtures :each (fn [f] (.clear cache) (try (sql/db-do-commands spec [(sql/drop-table-ddl :things) (sql/create-table-ddl :things [[:name "varchar(50)"]])]) (catch Exception _)) (f))) (use-fixtures :once (fn [f] (f) (.close @conn))) ;;; Helper methods to verify database activity (defn write-thing-to-db [spec name] (sql/insert! spec :things {:name name})) (defn read-thing-from-db [spec name] (-> (sql/query spec ["select name from things where name = ?" name]) first)) (defn count-things-in-db [spec] (-> (sql/query spec ["select count(*) c from things"]) first :c int)) (defn work [m] (csh/swap-in! cache :a (constantly 1)) (msg/publish queue "kiwi") (msg/publish @remote-queue "starfruit") (not-supported (csh/swap-in! cache :deliveries (fnil inc 0))) (sql/with-db-transaction [t spec] (write-thing-to-db t "tangerine") (when (:throw? m) (throw (Exception. "rollback"))) (when (:rollback? m) (set-rollback-only) (sql/db-set-rollback-only! t)))) (defn listener [m] (if (:tx? m) (transaction (work m)) (work m))) (defn attempt-transaction-external [& {:as m}] (try (with-open [conn (msg/context :xa? true)] (transaction (msg/publish queue "pineapple" :context conn) (work m))) (catch Exception e (-> e .getMessage)))) (defn attempt-transaction-internal [& {:as m}] (try (transaction (work m)) (catch Exception e (-> e .getMessage)))) (defn verify-success [] (is (= "kiwi" (msg/receive queue :timeout 1000))) (is (= "starfruit" (msg/receive local-remote-queue :timeout 1000))) (is (= 1 (:a cache))) (is (= "tangerine" (:name (read-thing-from-db spec "tangerine")))) (is (= 1 (count-things-in-db spec)))) (defn verify-failure [] (is (nil? (msg/receive queue :timeout 1000))) (is (nil? (msg/receive local-remote-queue :timeout 1000))) (is (nil? (:a cache))) (is (nil? (read-thing-from-db spec "tangerine"))) (is (= 0 (count-things-in-db spec)))) (deftest verify-transaction-success-external (is (nil? (attempt-transaction-external))) (is (= "pineapple" (msg/receive queue :timeout 1000))) (verify-success)) (deftest verify-transaction-failure-external (is (= "rollback" (attempt-transaction-external :throw? true))) (verify-failure)) (deftest verify-transaction-success-internal (is (nil? (attempt-transaction-internal))) (verify-success)) (deftest verify-transaction-failure-internal (is (= "rollback" (attempt-transaction-internal :throw? true))) (verify-failure)) (deftest transactional-receive (msg/publish queue "foo") (required (msg/receive queue) (set-rollback-only)) (is (= "foo" (msg/receive queue :timeout 1000)))) (deftest transactional-writes-in-listener-should-work (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true}) (verify-success))) (deftest transactional-writes-in-listener-should-fail-on-exception (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :throw? true}) (verify-failure) (is (= 10 (:deliveries cache))))) (deftest transactional-writes-in-listener-should-fail-on-rollback (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :rollback? true}) (verify-failure) (is (= 1 (:deliveries cache))))) (deftest non-transactional-writes-in-listener-with-exception (with-open [_ (msg/listen trigger listener :mode :auto-ack)] (msg/publish trigger {:throw? true}) (is (= 10 (loop [i 0] (Thread/sleep 100) (if (or (= 50 i) (= 10 (:deliveries cache))) (:deliveries cache) (recur (inc i)))))) (is (= 1 (:a cache))) (is (= (repeat 10 "kiwi") (repeatedly 10 #(msg/receive queue)))) (is (= (repeat 10 "starfruit") (repeatedly 10 #(msg/receive local-remote-queue)))))) (deftest remote-xa-listen-should-work (msg/queue "remote-xa-listen" :durable? false) (let [extra-connect-opts (cond-> [] (in-container?) (conj :username "testuser" :password "<PASSWORD>!") (and (in-container?) (not (in-eap?))) (conj :remote-type :hornetq-wildfly))] (with-open [c (apply msg/context :host "localhost" :port (messaging-remoting-port) :xa? true extra-connect-opts)] (let [q (msg/queue "remote-xa-listen" :context c) p (promise)] (with-open [listener (msg/listen q (partial deliver p))] (msg/publish q :hi) (is (= :hi (deref p 60000 :fail))))))))
true
;; Copyright 2014-2017 Red Hat, Inc, and individual contributors. ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns immutant.transactions-test (:require [clojure.test :refer :all] [clojure.java.io :as io] [immutant.transactions :refer :all] [immutant.transactions.scope :refer (required not-supported)] [immutant.util :refer [in-container? in-eap? set-log-level! messaging-remoting-port]] [immutant.messaging :as msg] [immutant.caching :as csh] [clojure.java.jdbc :as sql])) (set-log-level! (or (System/getenv "LOG_LEVEL") :OFF)) (def cache (csh/cache "tx-test" :transactional? true)) (def queue (msg/queue "/queue/test" :durable? false)) (def local-remote-queue (msg/queue "remote" :durable? false)) (def conn (delay (msg/context (cond-> {:host "localhost" :xa? true} (in-container?) (assoc :port (messaging-remoting-port) :username "testuser" :password "PI:PASSWORD:<PASSWORD>END_PI!" :remote-type :hornetq-wildfly) (in-eap?) (dissoc :remote-type))))) (def remote-queue (delay (msg/queue "remote" :context @conn))) (def trigger (msg/queue "/queue/trigger" :durable? false)) (def spec {:connection-uri "jdbc:h2:mem:ooc;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"}) (use-fixtures :each (fn [f] (.clear cache) (try (sql/db-do-commands spec [(sql/drop-table-ddl :things) (sql/create-table-ddl :things [[:name "varchar(50)"]])]) (catch Exception _)) (f))) (use-fixtures :once (fn [f] (f) (.close @conn))) ;;; Helper methods to verify database activity (defn write-thing-to-db [spec name] (sql/insert! spec :things {:name name})) (defn read-thing-from-db [spec name] (-> (sql/query spec ["select name from things where name = ?" name]) first)) (defn count-things-in-db [spec] (-> (sql/query spec ["select count(*) c from things"]) first :c int)) (defn work [m] (csh/swap-in! cache :a (constantly 1)) (msg/publish queue "kiwi") (msg/publish @remote-queue "starfruit") (not-supported (csh/swap-in! cache :deliveries (fnil inc 0))) (sql/with-db-transaction [t spec] (write-thing-to-db t "tangerine") (when (:throw? m) (throw (Exception. "rollback"))) (when (:rollback? m) (set-rollback-only) (sql/db-set-rollback-only! t)))) (defn listener [m] (if (:tx? m) (transaction (work m)) (work m))) (defn attempt-transaction-external [& {:as m}] (try (with-open [conn (msg/context :xa? true)] (transaction (msg/publish queue "pineapple" :context conn) (work m))) (catch Exception e (-> e .getMessage)))) (defn attempt-transaction-internal [& {:as m}] (try (transaction (work m)) (catch Exception e (-> e .getMessage)))) (defn verify-success [] (is (= "kiwi" (msg/receive queue :timeout 1000))) (is (= "starfruit" (msg/receive local-remote-queue :timeout 1000))) (is (= 1 (:a cache))) (is (= "tangerine" (:name (read-thing-from-db spec "tangerine")))) (is (= 1 (count-things-in-db spec)))) (defn verify-failure [] (is (nil? (msg/receive queue :timeout 1000))) (is (nil? (msg/receive local-remote-queue :timeout 1000))) (is (nil? (:a cache))) (is (nil? (read-thing-from-db spec "tangerine"))) (is (= 0 (count-things-in-db spec)))) (deftest verify-transaction-success-external (is (nil? (attempt-transaction-external))) (is (= "pineapple" (msg/receive queue :timeout 1000))) (verify-success)) (deftest verify-transaction-failure-external (is (= "rollback" (attempt-transaction-external :throw? true))) (verify-failure)) (deftest verify-transaction-success-internal (is (nil? (attempt-transaction-internal))) (verify-success)) (deftest verify-transaction-failure-internal (is (= "rollback" (attempt-transaction-internal :throw? true))) (verify-failure)) (deftest transactional-receive (msg/publish queue "foo") (required (msg/receive queue) (set-rollback-only)) (is (= "foo" (msg/receive queue :timeout 1000)))) (deftest transactional-writes-in-listener-should-work (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true}) (verify-success))) (deftest transactional-writes-in-listener-should-fail-on-exception (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :throw? true}) (verify-failure) (is (= 10 (:deliveries cache))))) (deftest transactional-writes-in-listener-should-fail-on-rollback (with-open [_ (msg/listen trigger listener)] (msg/publish trigger {:tx? true :rollback? true}) (verify-failure) (is (= 1 (:deliveries cache))))) (deftest non-transactional-writes-in-listener-with-exception (with-open [_ (msg/listen trigger listener :mode :auto-ack)] (msg/publish trigger {:throw? true}) (is (= 10 (loop [i 0] (Thread/sleep 100) (if (or (= 50 i) (= 10 (:deliveries cache))) (:deliveries cache) (recur (inc i)))))) (is (= 1 (:a cache))) (is (= (repeat 10 "kiwi") (repeatedly 10 #(msg/receive queue)))) (is (= (repeat 10 "starfruit") (repeatedly 10 #(msg/receive local-remote-queue)))))) (deftest remote-xa-listen-should-work (msg/queue "remote-xa-listen" :durable? false) (let [extra-connect-opts (cond-> [] (in-container?) (conj :username "testuser" :password "PI:PASSWORD:<PASSWORD>END_PI!") (and (in-container?) (not (in-eap?))) (conj :remote-type :hornetq-wildfly))] (with-open [c (apply msg/context :host "localhost" :port (messaging-remoting-port) :xa? true extra-connect-opts)] (let [q (msg/queue "remote-xa-listen" :context c) p (promise)] (with-open [listener (msg/listen q (partial deliver p))] (msg/publish q :hi) (is (= :hi (deref p 60000 :fail))))))))
[ { "context": "asses->students\n {\"Sussman\" {\"AI\" [{:name \"John\" :grade \"A\"}\n {:name \"Sa", "end": 5932, "score": 0.9998701214790344, "start": 5928, "tag": "NAME", "value": "John" }, { "context": "hn\" :grade \"A\"}\n {:name \"Sally\" :grade \"B\"}]\n \"Compilers\" [{:", "end": 5985, "score": 0.9997605085372925, "start": 5980, "tag": "NAME", "value": "Sally" }, { "context": "de \"B\"}]\n \"Compilers\" [{:name \"Tom\" :grade \"B\"}\n {:n", "end": 6044, "score": 0.9998677968978882, "start": 6041, "tag": "NAME", "value": "Tom" }, { "context": "ade \"B\"}\n {:name \"John\" :grade \"B\"}]}\n \"Abelson\" {\"Machine Learn", "end": 6103, "score": 0.9998733997344971, "start": 6099, "tag": "NAME", "value": "John" }, { "context": " {:name \"John\" :grade \"B\"}]}\n \"Abelson\" {\"Machine Learning\" [{:name \"Sally\" :grade \"C\"}\n", "end": 6136, "score": 0.9998314380645752, "start": 6129, "tag": "NAME", "value": "Abelson" }, { "context": "}\n \"Abelson\" {\"Machine Learning\" [{:name \"Sally\" :grade \"C\"}\n ", "end": 6172, "score": 0.9998444318771362, "start": 6167, "tag": "NAME", "value": "Sally" }, { "context": "}\n {:name \"Tom\" :grade \"B-\"}]\n \"Compilers\" [{", "end": 6237, "score": 0.9998717904090881, "start": 6234, "tag": "NAME", "value": "Tom" }, { "context": "e \"B-\"}]\n \"Compilers\" [{:name \"Eva Lu Ator\" :grade \"B\"}\n {:n", "end": 6305, "score": 0.9998084902763367, "start": 6294, "tag": "NAME", "value": "Eva Lu Ator" }, { "context": "ade \"B\"}\n {:name \"Ben Bitdiddle\" :grade \"A\"}]}}\n\n students->profs {\"John\" ", "end": 6373, "score": 0.9998553991317749, "start": 6360, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": "diddle\" :grade \"A\"}]}}\n\n students->profs {\"John\" #{\"Sussman\"} \"Sally\" #{\"Abelson\" \"Sussman\"}\n ", "end": 6421, "score": 0.9998766183853149, "start": 6417, "tag": "NAME", "value": "John" }, { "context": "grade \"A\"}]}}\n\n students->profs {\"John\" #{\"Sussman\"} \"Sally\" #{\"Abelson\" \"Sussman\"}\n ", "end": 6433, "score": 0.9998188614845276, "start": 6426, "tag": "NAME", "value": "Sussman" }, { "context": "}}\n\n students->profs {\"John\" #{\"Sussman\"} \"Sally\" #{\"Abelson\" \"Sussman\"}\n ", "end": 6442, "score": 0.9998618960380554, "start": 6437, "tag": "NAME", "value": "Sally" }, { "context": " students->profs {\"John\" #{\"Sussman\"} \"Sally\" #{\"Abelson\" \"Sussman\"}\n \"Tom\" #{\"Abe", "end": 6454, "score": 0.9998355507850647, "start": 6447, "tag": "NAME", "value": "Abelson" }, { "context": "->profs {\"John\" #{\"Sussman\"} \"Sally\" #{\"Abelson\" \"Sussman\"}\n \"Tom\" #{\"Abelson\" \"Sus", "end": 6464, "score": 0.999789297580719, "start": 6457, "tag": "NAME", "value": "Sussman" }, { "context": " #{\"Abelson\" \"Sussman\"}\n \"Tom\" #{\"Abelson\" \"Sussman\"} \"Eva Lu Ator\" #{\"Abelson\"", "end": 6496, "score": 0.999866247177124, "start": 6493, "tag": "NAME", "value": "Tom" }, { "context": "son\" \"Sussman\"}\n \"Tom\" #{\"Abelson\" \"Sussman\"} \"Eva Lu Ator\" #{\"Abelson\"}\n ", "end": 6508, "score": 0.9998311400413513, "start": 6501, "tag": "NAME", "value": "Abelson" }, { "context": "man\"}\n \"Tom\" #{\"Abelson\" \"Sussman\"} \"Eva Lu Ator\" #{\"Abelson\"}\n ", "end": 6518, "score": 0.9998178482055664, "start": 6511, "tag": "NAME", "value": "Sussman" }, { "context": " \"Tom\" #{\"Abelson\" \"Sussman\"} \"Eva Lu Ator\" #{\"Abelson\"}\n \"Ben Bitdi", "end": 6533, "score": 0.999488353729248, "start": 6522, "tag": "NAME", "value": "Eva Lu Ator" }, { "context": " \"Tom\" #{\"Abelson\" \"Sussman\"} \"Eva Lu Ator\" #{\"Abelson\"}\n \"Ben Bitdiddle\" #{\"Abe", "end": 6545, "score": 0.9997852444648743, "start": 6538, "tag": "NAME", "value": "Abelson" }, { "context": "a Lu Ator\" #{\"Abelson\"}\n \"Ben Bitdiddle\" #{\"Abelson\"}}]\n\n ;; todo: fix\n (is (= (f/t", "end": 6587, "score": 0.9998793601989746, "start": 6574, "tag": "NAME", "value": "Ben Bitdiddle" }, { "context": "son\"}\n \"Ben Bitdiddle\" #{\"Abelson\"}}]\n\n ;; todo: fix\n (is (= (f/transform pro", "end": 6599, "score": 0.9997618794441223, "start": 6592, "tag": "NAME", "value": "Abelson" }, { "context": "94 -100}))))\n\n (let [pieces\n [{:composer \"Bartók\" :title \"Piano Concerto 1\" :year 1926}\n {", "end": 9174, "score": 0.9992004036903381, "start": 9168, "tag": "NAME", "value": "Bartók" }, { "context": "iano Concerto 1\" :year 1926}\n {:composer \"Bartók\" :title \"String Quartet 2\" :year 1917}\n {", "end": 9241, "score": 0.9990193843841553, "start": 9235, "tag": "NAME", "value": "Bartók" }, { "context": "ing Quartet 2\" :year 1917}\n {:composer \"Ligeti\" :title \"Etude 1\" :year 1985}\n {:compose", "end": 9307, "score": 0.5458052754402161, "start": 9304, "tag": "NAME", "value": "get" }, { "context": "itle \"Etude 1\" :year 1985}\n {:composer \"Ligeti\" :title \"Mysteries of the Macabre\" :year 1992}]\n", "end": 9365, "score": 0.7595260739326477, "start": 9362, "tag": "NAME", "value": "get" }, { "context": "ar 1992}]\n\n by-composer-and-year\n {\"Bartók\"\n {1926 [{:composer \"Bartók\", :title \"Pia", "end": 9461, "score": 0.9995442032814026, "start": 9455, "tag": "NAME", "value": "Bartók" }, { "context": "ear\n {\"Bartók\"\n {1926 [{:composer \"Bartók\", :title \"Piano Concerto 1\", :year 1926}],\n ", "end": 9497, "score": 0.9993561506271362, "start": 9491, "tag": "NAME", "value": "Bartók" }, { "context": "rto 1\", :year 1926}],\n 1917 [{:composer \"Bartók\", :title \"String Quartet 2\", :year 1917}]},\n ", "end": 9575, "score": 0.9990237951278687, "start": 9569, "tag": "NAME", "value": "Bartók" }, { "context": "itle \"String Quartet 2\", :year 1917}]},\n \"Ligeti\"\n {1985 [{:composer \"Ligeti\", :title \"Etu", "end": 9636, "score": 0.8187820315361023, "start": 9630, "tag": "NAME", "value": "Ligeti" }, { "context": ",\n \"Ligeti\"\n {1985 [{:composer \"Ligeti\", :title \"Etude 1\", :year 1985}],\n 1992", "end": 9671, "score": 0.7865433096885681, "start": 9668, "tag": "NAME", "value": "get" }, { "context": "ude 1\", :year 1985}],\n 1992 [{:composer \"Ligeti\", :title \"Mysteries of the Macabre\", :year 1992}]", "end": 9741, "score": 0.7042877078056335, "start": 9735, "tag": "NAME", "value": "Ligeti" }, { "context": "reducers\n (let [student-data\n [{:student \"john\", :grade1 97, :grade2 89, :course \"math\", :campus", "end": 14599, "score": 0.9993178248405457, "start": 14595, "tag": "NAME", "value": "john" }, { "context": "ourse \"math\", :campus \"east\"}\n {:student \"john\", :grade1 90, :grade2 70, :course \"english\", :cam", "end": 14682, "score": 0.9992604851722717, "start": 14678, "tag": "NAME", "value": "john" }, { "context": "se \"english\", :campus \"east\"}\n {:student \"john\", :grade1 70, :grade2 80, :course \"history\", :cam", "end": 14768, "score": 0.9994207620620728, "start": 14764, "tag": "NAME", "value": "john" }, { "context": "se \"history\", :campus \"east\"}\n {:student \"dave\", :grade1 80, :grade2 80, :course \"math\", :campus", "end": 14854, "score": 0.9995238780975342, "start": 14850, "tag": "NAME", "value": "dave" }, { "context": "ourse \"math\", :campus \"east\"}\n {:student \"dave\", :grade1 100, :grade2 90, :course \"english\", :ca", "end": 14937, "score": 0.9995790719985962, "start": 14933, "tag": "NAME", "value": "dave" }, { "context": "se \"english\", :campus \"east\"}\n {:student \"mary\", :grade1 90, :grade2 86, :course \"math\", :campus", "end": 15024, "score": 0.996417760848999, "start": 15020, "tag": "NAME", "value": "mary" }, { "context": "ourse \"math\", :campus \"west\"}\n {:student \"mary\", :grade1 92, :grade2 81, :course \"english\", :cam", "end": 15107, "score": 0.9932760000228882, "start": 15103, "tag": "NAME", "value": "mary" }, { "context": "se \"english\", :campus \"west\"}\n {:student \"mary\", :grade1 94, :grade2 83, :course \"history\", :cam", "end": 15193, "score": 0.9924423098564148, "start": 15189, "tag": "NAME", "value": "mary" }, { "context": "dent (apply max ^:expand [grade2])})\n {\"john\" 89, \"dave\" 90, \"mary\" 86}))\n\n (is (= (f/trans", "end": 15500, "score": 0.9995625019073486, "start": 15496, "tag": "NAME", "value": "john" }, { "context": " max ^:expand [grade2])})\n {\"john\" 89, \"dave\" 90, \"mary\" 86}))\n\n (is (= (f/transform studen", "end": 15511, "score": 0.9996858835220337, "start": 15507, "tag": "NAME", "value": "dave" }, { "context": "nd [grade2])})\n {\"john\" 89, \"dave\" 90, \"mary\" 86}))\n\n (is (= (f/transform student-data\n ", "end": 15522, "score": 0.9917826056480408, "start": 15518, "tag": "NAME", "value": "mary" }, { "context": " (apply max ^:expand [grade2]))})\n {\"john\" 97, \"dave\" 100, \"mary\" 94}))\n\n (is (= (f/tran", "end": 15789, "score": 0.9995802640914917, "start": 15785, "tag": "NAME", "value": "john" }, { "context": "max ^:expand [grade2]))})\n {\"john\" 97, \"dave\" 100, \"mary\" 94}))\n\n (is (= (f/transform stude", "end": 15800, "score": 0.9996271729469299, "start": 15796, "tag": "NAME", "value": "dave" }, { "context": " [grade2]))})\n {\"john\" 97, \"dave\" 100, \"mary\" 94}))\n\n (is (= (f/transform student-data\n ", "end": 15812, "score": 0.9951607584953308, "start": 15808, "tag": "NAME", "value": "mary" }, { "context": " :course course}]))})\n {\"john\" \"math\", \"dave\" \"english\", \"mary\" \"history\"}))\n\n ", "end": 16227, "score": 0.9993674159049988, "start": 16223, "tag": "NAME", "value": "john" }, { "context": " :course course}]))})\n {\"john\" \"math\", \"dave\" \"english\", \"mary\" \"history\"}))\n\n (is (= (f/tr", "end": 16242, "score": 0.9994258880615234, "start": 16238, "tag": "NAME", "value": "dave" }, { "context": " \"history\" 70},\n :student-stats {\"john\" {\"math\" 97,\n ", "end": 17130, "score": 0.9992606043815613, "start": 17126, "tag": "NAME", "value": "john" }, { "context": " \"history\" 70},\n \"dave\" {\"math\" 80,\n ", "end": 17281, "score": 0.9971944093704224, "start": 17277, "tag": "NAME", "value": "dave" } ]
test/faconne/test/core.clj
disalvjn/plum
108
(ns faconne.test.core (:require [faconne.core :as f]) (:use [clojure.test])) (def test-times 20) (defn gen-structure-from-domain "Create a function that when invoked will generate a random extension of `domain`." [domain] (let [max-size 10 get-size (fn [& args] (Math/floor (rand max-size))) exec (fn [f] (f))] (letfn [(create [domain] (cond (symbol? domain) rand (or (vector? domain) (set? domain)) (let [create-elems (map create domain) return (if (vector? domain) identity (partial into #{}))] (fn [& args] (->> (for [_ (range 0 (* (count domain) (get-size)))] (mapv exec create-elems)) (reduce into []) return))) (map? domain) (let [[k v] (first domain) create-key (create k) create-val (create v)] (fn [& args] (->> (for [_ (range 0 (get-size))] [(create-key) (create-val)]) (into {}))))))] (create domain)))) (defn test-trans [mkdata domain range' where hand-written] (let [data (mkdata) from-trans-fn (eval `(f/transformer ~domain ~range' :where ~where)) from-trans (from-trans-fn data) from-hand (hand-written data)] (testing (str "Testing transformer on " domain " " range' " " where ".\n Data = " data) (is (= from-trans from-hand))))) (defmacro test-transformer [domain range' where hand-written] `(let [mkdata# (gen-structure-from-domain (quote ~domain))] (doseq [_# (range 0 ~test-times)] (test-trans mkdata# (quote ~domain) (quote ~range') (quote ~where) ~hand-written)))) (deftest test-map-domains (let [swap-key-order ;; {k1 {k2 v}} -> {k2 {k1 v}} (fn [m] (or (apply merge-with merge (map (fn [[k1 inner]] (apply merge-with merge (map (fn [[k2 v]] {k2 {k1 v}}) inner))) m)) {})) remove-inner ;; {k1 {k2 v}} -> {k1 #{v}} (fn [m] (or (apply merge-with into (map (fn [[k inner]] (apply merge-with into (map (fn [[_ v]] {k #{v}}) inner))) m)) {})) flip (fn [m] (or (into {} (map (fn [[k v]] [v k]) m)) {})) ;; {k v} -> {v k} skipping-flatset (fn [m] ;; {k [v]} -> #{[k v]} (or (reduce into #{} (map (fn [[k vector]] (reduce into #{} (->> vector (partition 2) (map first) (map (fn [v] #{[k v]}))))) m)) {})) sums-of-all-pairs-of-vals (fn [m] (let [vs (vals m)] (reduce into #{} (map (fn [i] (into #{} (map (fn [j] (+ i j)) vs))) vs))))] (test-transformer {k1 {k2 v}} {k2 {k1 v}} [] swap-key-order) (test-transformer {k {_ v}} {k #{v}} [] remove-inner) (test-transformer {k v} {v k} [] flip) (test-transformer {k [v _]} #{[k v]} [] skipping-flatset) (test-transformer {k1 v1, k2 v2} #{(+ v1 v2)} [] sums-of-all-pairs-of-vals))) (deftest test-vector-domains (let [seconds (fn [v] (map second (partition 2 v))) sums-of-pairs-of-odds (fn [v] (map (fn [[a b c d]] (+ a c)) (partition 4 v))) sums-of-1-3-in-2 (fn [v] (->> v (partition 3) (map second) (map (partial partition 3)) (map (fn [v2] (into #{} (map (fn [[a _ c]] (+ a (or c 0))) v2)))) (reduce into #{}))) super-contrived (fn [v] (->> v (partition 2) (map first) (map #(->> % (map (fn [[k vector]] (into #{} (map (partial + k) vector)))) (reduce into #{}))) (reduce into #{})))] (test-transformer [_ b] [b] [] seconds) (test-transformer [a _ c _] [(+ a c)] [a c] sums-of-pairs-of-odds) (test-transformer [[a]] [a] [] (partial reduce into [])) (test-transformer [_ [a _ c] _] #{(+ a c)} [a c] sums-of-1-3-in-2) (test-transformer [{k [v]} _] #{(+ k v)} [] super-contrived))) (deftest test-set-domains (let [adj-sums (fn [s] (->> s (map (fn [v] (into #{} (map (partial apply +) (partition 2 v))))) (reduce into #{})))] (test-transformer #{[a b]} #{(+ a b)} [a b] adj-sums))) (deftest map->map (let [m {:a {:b 2 :c 5} :c {:b 3 :e 1}}] (is (= (f/transform m {k1 {k2 v}} {k2 {k1 v}}) {:b {:a 2 :c 3} :c {:a 5} :e {:c 1}})))) (deftest set-in-map (let [profs->classes->students {"Sussman" {"AI" [{:name "John" :grade "A"} {:name "Sally" :grade "B"}] "Compilers" [{:name "Tom" :grade "B"} {:name "John" :grade "B"}]} "Abelson" {"Machine Learning" [{:name "Sally" :grade "C"} {:name "Tom" :grade "B-"}] "Compilers" [{:name "Eva Lu Ator" :grade "B"} {:name "Ben Bitdiddle" :grade "A"}]}} students->profs {"John" #{"Sussman"} "Sally" #{"Abelson" "Sussman"} "Tom" #{"Abelson" "Sussman"} "Eva Lu Ator" #{"Abelson"} "Ben Bitdiddle" #{"Abelson"}}] ;; todo: fix (is (= (f/transform profs->classes->students {prof {_ [student]}} {(:name student) #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:keys [name]}]}} {name #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:name name}]}} {name #{prof}}) students->profs)))) (deftest simple-vector-partioning (is (-> [1 2 3 4 5 6] (f/transform [a _] [a]) (= [1 3 5]))) (is (-> [1 2 3 4 5 6] (f/transform [a _ c] [a c]) (= [1 3 4 6]))) (is (-> [1 2 3 4 5 6] (f/transform [_ b _] [b]) (= [2 5]))) (is (-> [1 2 3 4 5] (f/transform [_ b] [b] :where [b]) (= [2 4]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[a _]] [a]) (= [1 3 5]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[_ b]] [b]) (= [2 4 6]))) (is (-> [[1 2] [3 4]] (f/transform [[a]] [a]) (= [1 2 3 4])))) (deftest complex-vector-partitioning (is (-> {{:k :a} [1 2 3 4 5 6] {:k :b} [7 8 9 10 11 12]} (f/transform {{:keys [k]} [a _ c]} {(+ a c) k} :where [(even? a) (even? c)]) (= {10 :a, 22 :b}))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[_ b] _] [b] :where [b (even? b)]) (= [2 6]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [a _]] [a] :where [a (even? a)]) (= [4 98]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [_ b]] [b] :where [b (even? b)]) (= [14]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[a _] _] [a] :where [a (even? a)]) (= [8])))) (deftest key-literals (let [data [{:num 6 :coll [1 2]} {:num 7 :coll [-94 -100]} {:num 8 :coll [3 4]}]] (is (-> data (f/transform [{:num n :coll [x]}] #{x} :where [(even? n)]) (= #{1 2 3 4}))) (is (-> data (f/transform [{:keys [num] :coll [x]}] #{x} :where [(odd? num)]) (= #{-94 -100})))) (let [pieces [{:composer "Bartók" :title "Piano Concerto 1" :year 1926} {:composer "Bartók" :title "String Quartet 2" :year 1917} {:composer "Ligeti" :title "Etude 1" :year 1985} {:composer "Ligeti" :title "Mysteries of the Macabre" :year 1992}] by-composer-and-year {"Bartók" {1926 [{:composer "Bartók", :title "Piano Concerto 1", :year 1926}], 1917 [{:composer "Bartók", :title "String Quartet 2", :year 1917}]}, "Ligeti" {1985 [{:composer "Ligeti", :title "Etude 1", :year 1985}], 1992 [{:composer "Ligeti", :title "Mysteries of the Macabre", :year 1992}]}}] (is (-> pieces (f/transform [{:keys [composer year] :as piece}] {composer {year [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:keys [composer] :year y :as piece}] {composer {y [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:composer c :year y :as piece}] {c {y [piece]}}) (= by-composer-and-year)))) (let [data [{:a 1 "b" 2}, {:a 2 "b" 3}, {:a 3 "b" 5}, {:a 4 "b" 4}] result {1 2 2 3 4 4 3 5}] (is (-> data (f/transform [{:a a "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:keys [a] "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:strs [b] :a a}] {a b}) (= result)))) (let [data [{:keys 1 :strs 2 :syms 3 :as 4} {:keys 5 :strs 6 :syms 7 :as 8}]] (is (-> data (f/transform [{(:literal :keys) a (:literal :strs) b (:literal :syms) c (:literal :as) d}] #{(+ a b c d)}) (= #{10 26})))) (is (-> {[101 23] 4, [98] 2} (f/transform {(:literal [101 23]) x} #{x}) (= #{4})))) (deftest variable-key-literal (let [merge-key-vals (fn [m k1 k2] (f/transform m {(:literal k1) [v1] (:literal k2) [v2]} #{v1 v2}))] (is (-> {:a [1 2 3], :b [3 4 5], :c [5 6 7]} (merge-key-vals :a :b) (= #{1 2 3 4 5}))))) (deftest where (is (= {1 2, 3 4} (f/transform {1 (range), 2 [1, 2], 3 (range), 4 [3, 4]} {k [n]} {n k} :where [(even? k) (odd? n)])))) (deftest key-destructuring (let [pair-map {[1 2] 3 [4 5] 6} map-map {{:a 1 :b 2} 3 {:a 4 :b 5} 6}] (is (-> pair-map (f/transform {[n1 n2] v} #{(+ n1 n2 v)}) (= #{6 15}))) (is (-> map-map (f/transform {{:keys [a b]} v} #{(+ a b v)}) (= #{6 15}))))) (deftest combinations (is (= #{#{:c :d} #{:e :a} #{:b :a}} (f/transform {:a 7, :b 3, :c 5, :d 5, :e 3} {k v, k' v'} #{#{k k'}} :where [(not= k k') (= 10 (+ v v'))])))) (deftest higher-level-sanity-tests (let [json [{:store-name "Tom's Records" :location "1234 Main Street" :stock [{:artist "Bartók" :title "String Quartets" :quantity 5} {:artist "Ligeti" :title "Violin Concerto" :quantity 1}]} {:store-name "Roger's Records" :location "789 Secondary Street" :stock [{:artist "Ligeti" :title "Violin Concerto" :quantity 3} {:artist "Scriabin" :title "12 Etudes" :quantity 2}]}] transform (f/transformer [{:store-name store :location loc :stock [{:keys [artist title quantity]}]}] {artist {title [[(str store " @ " loc) quantity]]}}) result {"Bartók" {"String Quartets" [["Tom's Records @ 1234 Main Street" 5]]}, "Ligeti" {"Violin Concerto" [["Tom's Records @ 1234 Main Street" 1] ["Roger's Records @ 789 Secondary Street" 3]]}, "Scriabin" {"12 Etudes" [["Roger's Records @ 789 Secondary Street" 2]]}}] (is (= result (transform json))))) ;;;;;;;;;;;;;; ;; Reducers ;; ;;;;;;;;;;;;;; (deftest simple-reducers (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x])) 3)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (inc x)])) 4)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (count ^:expand [x])])) 6)) (is (= (f/transform [1 2 3 1 2 3] [x] (count ^:expand #{x})) 3)) (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} #{(apply max ^:expand [v])}) #{9})) ;; readme (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} (apply max ^:expand [v])) 9))) (deftest complicated-reducers (let [student-data [{:student "john", :grade1 97, :grade2 89, :course "math", :campus "east"} {:student "john", :grade1 90, :grade2 70, :course "english", :campus "east"} {:student "john", :grade1 70, :grade2 80, :course "history", :campus "east"} {:student "dave", :grade1 80, :grade2 80, :course "math", :campus "east"} {:student "dave", :grade1 100, :grade2 90, :course "english", :campus "east"} {:student "mary", :grade1 90, :grade2 86, :course "math", :campus "west"} {:student "mary", :grade1 92, :grade2 81, :course "english", :campus "west"} {:student "mary", :grade1 94, :grade2 83, :course "history", :campus "west"}] average (fn [xs] (/ (reduce + 0 xs) (count xs)))] (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (apply max ^:expand [grade2])}) {"john" 89, "dave" 90, "mary" 86})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (max (apply max ^:expand [grade1]) (apply max ^:expand [grade2]))}) {"john" 97, "dave" 100, "mary" 94})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course] :as tuple}] {student (:course (apply max-key :grade ^:expand [{:grade (/ (+ grade1 grade2) 2), :course course}]))}) {"john" "math", "dave" "english", "mary" "history"})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {course (count ^:expand [student])} :where [(> grade1 95)]) {"math" 1, "english" 1})) ;;readme (is (= (f/transform student-data [{:keys [student grade1 grade2 course campus]}] {campus {:number-students (count ^:expand #{student}) :avg-grade-per-course {course (average ^:expand [grade1])} :student-stats {student {course grade1}}}}) {"east" {:number-students 2, :avg-grade-per-course {"math" 177/2, "english" 95, "history" 70}, :student-stats {"john" {"math" 97, "english" 90, "history" 70}, "dave" {"math" 80, "english" 100}}} "west" {:number-students 1, :avg-grade-per-course {"math" 90, "english" 92, "history" 94}, :student-stats {"mary" {"math" 90, "english" 92, "history" 94}}}})))) ;; Issue #3 on Github. (deftest test-expression-collections (is (= (f/transform [1 2 3 4 5 6] [x] {(if (even? x) :even :odd) (if (even? x) [(* 2 x)] [(+ 1 x)])}) {:even [4 8 12] :odd [2 4 6]})))
69303
(ns faconne.test.core (:require [faconne.core :as f]) (:use [clojure.test])) (def test-times 20) (defn gen-structure-from-domain "Create a function that when invoked will generate a random extension of `domain`." [domain] (let [max-size 10 get-size (fn [& args] (Math/floor (rand max-size))) exec (fn [f] (f))] (letfn [(create [domain] (cond (symbol? domain) rand (or (vector? domain) (set? domain)) (let [create-elems (map create domain) return (if (vector? domain) identity (partial into #{}))] (fn [& args] (->> (for [_ (range 0 (* (count domain) (get-size)))] (mapv exec create-elems)) (reduce into []) return))) (map? domain) (let [[k v] (first domain) create-key (create k) create-val (create v)] (fn [& args] (->> (for [_ (range 0 (get-size))] [(create-key) (create-val)]) (into {}))))))] (create domain)))) (defn test-trans [mkdata domain range' where hand-written] (let [data (mkdata) from-trans-fn (eval `(f/transformer ~domain ~range' :where ~where)) from-trans (from-trans-fn data) from-hand (hand-written data)] (testing (str "Testing transformer on " domain " " range' " " where ".\n Data = " data) (is (= from-trans from-hand))))) (defmacro test-transformer [domain range' where hand-written] `(let [mkdata# (gen-structure-from-domain (quote ~domain))] (doseq [_# (range 0 ~test-times)] (test-trans mkdata# (quote ~domain) (quote ~range') (quote ~where) ~hand-written)))) (deftest test-map-domains (let [swap-key-order ;; {k1 {k2 v}} -> {k2 {k1 v}} (fn [m] (or (apply merge-with merge (map (fn [[k1 inner]] (apply merge-with merge (map (fn [[k2 v]] {k2 {k1 v}}) inner))) m)) {})) remove-inner ;; {k1 {k2 v}} -> {k1 #{v}} (fn [m] (or (apply merge-with into (map (fn [[k inner]] (apply merge-with into (map (fn [[_ v]] {k #{v}}) inner))) m)) {})) flip (fn [m] (or (into {} (map (fn [[k v]] [v k]) m)) {})) ;; {k v} -> {v k} skipping-flatset (fn [m] ;; {k [v]} -> #{[k v]} (or (reduce into #{} (map (fn [[k vector]] (reduce into #{} (->> vector (partition 2) (map first) (map (fn [v] #{[k v]}))))) m)) {})) sums-of-all-pairs-of-vals (fn [m] (let [vs (vals m)] (reduce into #{} (map (fn [i] (into #{} (map (fn [j] (+ i j)) vs))) vs))))] (test-transformer {k1 {k2 v}} {k2 {k1 v}} [] swap-key-order) (test-transformer {k {_ v}} {k #{v}} [] remove-inner) (test-transformer {k v} {v k} [] flip) (test-transformer {k [v _]} #{[k v]} [] skipping-flatset) (test-transformer {k1 v1, k2 v2} #{(+ v1 v2)} [] sums-of-all-pairs-of-vals))) (deftest test-vector-domains (let [seconds (fn [v] (map second (partition 2 v))) sums-of-pairs-of-odds (fn [v] (map (fn [[a b c d]] (+ a c)) (partition 4 v))) sums-of-1-3-in-2 (fn [v] (->> v (partition 3) (map second) (map (partial partition 3)) (map (fn [v2] (into #{} (map (fn [[a _ c]] (+ a (or c 0))) v2)))) (reduce into #{}))) super-contrived (fn [v] (->> v (partition 2) (map first) (map #(->> % (map (fn [[k vector]] (into #{} (map (partial + k) vector)))) (reduce into #{}))) (reduce into #{})))] (test-transformer [_ b] [b] [] seconds) (test-transformer [a _ c _] [(+ a c)] [a c] sums-of-pairs-of-odds) (test-transformer [[a]] [a] [] (partial reduce into [])) (test-transformer [_ [a _ c] _] #{(+ a c)} [a c] sums-of-1-3-in-2) (test-transformer [{k [v]} _] #{(+ k v)} [] super-contrived))) (deftest test-set-domains (let [adj-sums (fn [s] (->> s (map (fn [v] (into #{} (map (partial apply +) (partition 2 v))))) (reduce into #{})))] (test-transformer #{[a b]} #{(+ a b)} [a b] adj-sums))) (deftest map->map (let [m {:a {:b 2 :c 5} :c {:b 3 :e 1}}] (is (= (f/transform m {k1 {k2 v}} {k2 {k1 v}}) {:b {:a 2 :c 3} :c {:a 5} :e {:c 1}})))) (deftest set-in-map (let [profs->classes->students {"Sussman" {"AI" [{:name "<NAME>" :grade "A"} {:name "<NAME>" :grade "B"}] "Compilers" [{:name "<NAME>" :grade "B"} {:name "<NAME>" :grade "B"}]} "<NAME>" {"Machine Learning" [{:name "<NAME>" :grade "C"} {:name "<NAME>" :grade "B-"}] "Compilers" [{:name "<NAME>" :grade "B"} {:name "<NAME>" :grade "A"}]}} students->profs {"<NAME>" #{"<NAME>"} "<NAME>" #{"<NAME>" "<NAME>"} "<NAME>" #{"<NAME>" "<NAME>"} "<NAME>" #{"<NAME>"} "<NAME>" #{"<NAME>"}}] ;; todo: fix (is (= (f/transform profs->classes->students {prof {_ [student]}} {(:name student) #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:keys [name]}]}} {name #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:name name}]}} {name #{prof}}) students->profs)))) (deftest simple-vector-partioning (is (-> [1 2 3 4 5 6] (f/transform [a _] [a]) (= [1 3 5]))) (is (-> [1 2 3 4 5 6] (f/transform [a _ c] [a c]) (= [1 3 4 6]))) (is (-> [1 2 3 4 5 6] (f/transform [_ b _] [b]) (= [2 5]))) (is (-> [1 2 3 4 5] (f/transform [_ b] [b] :where [b]) (= [2 4]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[a _]] [a]) (= [1 3 5]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[_ b]] [b]) (= [2 4 6]))) (is (-> [[1 2] [3 4]] (f/transform [[a]] [a]) (= [1 2 3 4])))) (deftest complex-vector-partitioning (is (-> {{:k :a} [1 2 3 4 5 6] {:k :b} [7 8 9 10 11 12]} (f/transform {{:keys [k]} [a _ c]} {(+ a c) k} :where [(even? a) (even? c)]) (= {10 :a, 22 :b}))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[_ b] _] [b] :where [b (even? b)]) (= [2 6]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [a _]] [a] :where [a (even? a)]) (= [4 98]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [_ b]] [b] :where [b (even? b)]) (= [14]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[a _] _] [a] :where [a (even? a)]) (= [8])))) (deftest key-literals (let [data [{:num 6 :coll [1 2]} {:num 7 :coll [-94 -100]} {:num 8 :coll [3 4]}]] (is (-> data (f/transform [{:num n :coll [x]}] #{x} :where [(even? n)]) (= #{1 2 3 4}))) (is (-> data (f/transform [{:keys [num] :coll [x]}] #{x} :where [(odd? num)]) (= #{-94 -100})))) (let [pieces [{:composer "<NAME>" :title "Piano Concerto 1" :year 1926} {:composer "<NAME>" :title "String Quartet 2" :year 1917} {:composer "Li<NAME>i" :title "Etude 1" :year 1985} {:composer "Li<NAME>i" :title "Mysteries of the Macabre" :year 1992}] by-composer-and-year {"<NAME>" {1926 [{:composer "<NAME>", :title "Piano Concerto 1", :year 1926}], 1917 [{:composer "<NAME>", :title "String Quartet 2", :year 1917}]}, "<NAME>" {1985 [{:composer "Li<NAME>i", :title "Etude 1", :year 1985}], 1992 [{:composer "<NAME>", :title "Mysteries of the Macabre", :year 1992}]}}] (is (-> pieces (f/transform [{:keys [composer year] :as piece}] {composer {year [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:keys [composer] :year y :as piece}] {composer {y [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:composer c :year y :as piece}] {c {y [piece]}}) (= by-composer-and-year)))) (let [data [{:a 1 "b" 2}, {:a 2 "b" 3}, {:a 3 "b" 5}, {:a 4 "b" 4}] result {1 2 2 3 4 4 3 5}] (is (-> data (f/transform [{:a a "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:keys [a] "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:strs [b] :a a}] {a b}) (= result)))) (let [data [{:keys 1 :strs 2 :syms 3 :as 4} {:keys 5 :strs 6 :syms 7 :as 8}]] (is (-> data (f/transform [{(:literal :keys) a (:literal :strs) b (:literal :syms) c (:literal :as) d}] #{(+ a b c d)}) (= #{10 26})))) (is (-> {[101 23] 4, [98] 2} (f/transform {(:literal [101 23]) x} #{x}) (= #{4})))) (deftest variable-key-literal (let [merge-key-vals (fn [m k1 k2] (f/transform m {(:literal k1) [v1] (:literal k2) [v2]} #{v1 v2}))] (is (-> {:a [1 2 3], :b [3 4 5], :c [5 6 7]} (merge-key-vals :a :b) (= #{1 2 3 4 5}))))) (deftest where (is (= {1 2, 3 4} (f/transform {1 (range), 2 [1, 2], 3 (range), 4 [3, 4]} {k [n]} {n k} :where [(even? k) (odd? n)])))) (deftest key-destructuring (let [pair-map {[1 2] 3 [4 5] 6} map-map {{:a 1 :b 2} 3 {:a 4 :b 5} 6}] (is (-> pair-map (f/transform {[n1 n2] v} #{(+ n1 n2 v)}) (= #{6 15}))) (is (-> map-map (f/transform {{:keys [a b]} v} #{(+ a b v)}) (= #{6 15}))))) (deftest combinations (is (= #{#{:c :d} #{:e :a} #{:b :a}} (f/transform {:a 7, :b 3, :c 5, :d 5, :e 3} {k v, k' v'} #{#{k k'}} :where [(not= k k') (= 10 (+ v v'))])))) (deftest higher-level-sanity-tests (let [json [{:store-name "Tom's Records" :location "1234 Main Street" :stock [{:artist "Bartók" :title "String Quartets" :quantity 5} {:artist "Ligeti" :title "Violin Concerto" :quantity 1}]} {:store-name "Roger's Records" :location "789 Secondary Street" :stock [{:artist "Ligeti" :title "Violin Concerto" :quantity 3} {:artist "Scriabin" :title "12 Etudes" :quantity 2}]}] transform (f/transformer [{:store-name store :location loc :stock [{:keys [artist title quantity]}]}] {artist {title [[(str store " @ " loc) quantity]]}}) result {"Bartók" {"String Quartets" [["Tom's Records @ 1234 Main Street" 5]]}, "Ligeti" {"Violin Concerto" [["Tom's Records @ 1234 Main Street" 1] ["Roger's Records @ 789 Secondary Street" 3]]}, "Scriabin" {"12 Etudes" [["Roger's Records @ 789 Secondary Street" 2]]}}] (is (= result (transform json))))) ;;;;;;;;;;;;;; ;; Reducers ;; ;;;;;;;;;;;;;; (deftest simple-reducers (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x])) 3)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (inc x)])) 4)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (count ^:expand [x])])) 6)) (is (= (f/transform [1 2 3 1 2 3] [x] (count ^:expand #{x})) 3)) (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} #{(apply max ^:expand [v])}) #{9})) ;; readme (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} (apply max ^:expand [v])) 9))) (deftest complicated-reducers (let [student-data [{:student "<NAME>", :grade1 97, :grade2 89, :course "math", :campus "east"} {:student "<NAME>", :grade1 90, :grade2 70, :course "english", :campus "east"} {:student "<NAME>", :grade1 70, :grade2 80, :course "history", :campus "east"} {:student "<NAME>", :grade1 80, :grade2 80, :course "math", :campus "east"} {:student "<NAME>", :grade1 100, :grade2 90, :course "english", :campus "east"} {:student "<NAME>", :grade1 90, :grade2 86, :course "math", :campus "west"} {:student "<NAME>", :grade1 92, :grade2 81, :course "english", :campus "west"} {:student "<NAME>", :grade1 94, :grade2 83, :course "history", :campus "west"}] average (fn [xs] (/ (reduce + 0 xs) (count xs)))] (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (apply max ^:expand [grade2])}) {"<NAME>" 89, "<NAME>" 90, "<NAME>" 86})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (max (apply max ^:expand [grade1]) (apply max ^:expand [grade2]))}) {"<NAME>" 97, "<NAME>" 100, "<NAME>" 94})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course] :as tuple}] {student (:course (apply max-key :grade ^:expand [{:grade (/ (+ grade1 grade2) 2), :course course}]))}) {"<NAME>" "math", "<NAME>" "english", "mary" "history"})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {course (count ^:expand [student])} :where [(> grade1 95)]) {"math" 1, "english" 1})) ;;readme (is (= (f/transform student-data [{:keys [student grade1 grade2 course campus]}] {campus {:number-students (count ^:expand #{student}) :avg-grade-per-course {course (average ^:expand [grade1])} :student-stats {student {course grade1}}}}) {"east" {:number-students 2, :avg-grade-per-course {"math" 177/2, "english" 95, "history" 70}, :student-stats {"<NAME>" {"math" 97, "english" 90, "history" 70}, "<NAME>" {"math" 80, "english" 100}}} "west" {:number-students 1, :avg-grade-per-course {"math" 90, "english" 92, "history" 94}, :student-stats {"mary" {"math" 90, "english" 92, "history" 94}}}})))) ;; Issue #3 on Github. (deftest test-expression-collections (is (= (f/transform [1 2 3 4 5 6] [x] {(if (even? x) :even :odd) (if (even? x) [(* 2 x)] [(+ 1 x)])}) {:even [4 8 12] :odd [2 4 6]})))
true
(ns faconne.test.core (:require [faconne.core :as f]) (:use [clojure.test])) (def test-times 20) (defn gen-structure-from-domain "Create a function that when invoked will generate a random extension of `domain`." [domain] (let [max-size 10 get-size (fn [& args] (Math/floor (rand max-size))) exec (fn [f] (f))] (letfn [(create [domain] (cond (symbol? domain) rand (or (vector? domain) (set? domain)) (let [create-elems (map create domain) return (if (vector? domain) identity (partial into #{}))] (fn [& args] (->> (for [_ (range 0 (* (count domain) (get-size)))] (mapv exec create-elems)) (reduce into []) return))) (map? domain) (let [[k v] (first domain) create-key (create k) create-val (create v)] (fn [& args] (->> (for [_ (range 0 (get-size))] [(create-key) (create-val)]) (into {}))))))] (create domain)))) (defn test-trans [mkdata domain range' where hand-written] (let [data (mkdata) from-trans-fn (eval `(f/transformer ~domain ~range' :where ~where)) from-trans (from-trans-fn data) from-hand (hand-written data)] (testing (str "Testing transformer on " domain " " range' " " where ".\n Data = " data) (is (= from-trans from-hand))))) (defmacro test-transformer [domain range' where hand-written] `(let [mkdata# (gen-structure-from-domain (quote ~domain))] (doseq [_# (range 0 ~test-times)] (test-trans mkdata# (quote ~domain) (quote ~range') (quote ~where) ~hand-written)))) (deftest test-map-domains (let [swap-key-order ;; {k1 {k2 v}} -> {k2 {k1 v}} (fn [m] (or (apply merge-with merge (map (fn [[k1 inner]] (apply merge-with merge (map (fn [[k2 v]] {k2 {k1 v}}) inner))) m)) {})) remove-inner ;; {k1 {k2 v}} -> {k1 #{v}} (fn [m] (or (apply merge-with into (map (fn [[k inner]] (apply merge-with into (map (fn [[_ v]] {k #{v}}) inner))) m)) {})) flip (fn [m] (or (into {} (map (fn [[k v]] [v k]) m)) {})) ;; {k v} -> {v k} skipping-flatset (fn [m] ;; {k [v]} -> #{[k v]} (or (reduce into #{} (map (fn [[k vector]] (reduce into #{} (->> vector (partition 2) (map first) (map (fn [v] #{[k v]}))))) m)) {})) sums-of-all-pairs-of-vals (fn [m] (let [vs (vals m)] (reduce into #{} (map (fn [i] (into #{} (map (fn [j] (+ i j)) vs))) vs))))] (test-transformer {k1 {k2 v}} {k2 {k1 v}} [] swap-key-order) (test-transformer {k {_ v}} {k #{v}} [] remove-inner) (test-transformer {k v} {v k} [] flip) (test-transformer {k [v _]} #{[k v]} [] skipping-flatset) (test-transformer {k1 v1, k2 v2} #{(+ v1 v2)} [] sums-of-all-pairs-of-vals))) (deftest test-vector-domains (let [seconds (fn [v] (map second (partition 2 v))) sums-of-pairs-of-odds (fn [v] (map (fn [[a b c d]] (+ a c)) (partition 4 v))) sums-of-1-3-in-2 (fn [v] (->> v (partition 3) (map second) (map (partial partition 3)) (map (fn [v2] (into #{} (map (fn [[a _ c]] (+ a (or c 0))) v2)))) (reduce into #{}))) super-contrived (fn [v] (->> v (partition 2) (map first) (map #(->> % (map (fn [[k vector]] (into #{} (map (partial + k) vector)))) (reduce into #{}))) (reduce into #{})))] (test-transformer [_ b] [b] [] seconds) (test-transformer [a _ c _] [(+ a c)] [a c] sums-of-pairs-of-odds) (test-transformer [[a]] [a] [] (partial reduce into [])) (test-transformer [_ [a _ c] _] #{(+ a c)} [a c] sums-of-1-3-in-2) (test-transformer [{k [v]} _] #{(+ k v)} [] super-contrived))) (deftest test-set-domains (let [adj-sums (fn [s] (->> s (map (fn [v] (into #{} (map (partial apply +) (partition 2 v))))) (reduce into #{})))] (test-transformer #{[a b]} #{(+ a b)} [a b] adj-sums))) (deftest map->map (let [m {:a {:b 2 :c 5} :c {:b 3 :e 1}}] (is (= (f/transform m {k1 {k2 v}} {k2 {k1 v}}) {:b {:a 2 :c 3} :c {:a 5} :e {:c 1}})))) (deftest set-in-map (let [profs->classes->students {"Sussman" {"AI" [{:name "PI:NAME:<NAME>END_PI" :grade "A"} {:name "PI:NAME:<NAME>END_PI" :grade "B"}] "Compilers" [{:name "PI:NAME:<NAME>END_PI" :grade "B"} {:name "PI:NAME:<NAME>END_PI" :grade "B"}]} "PI:NAME:<NAME>END_PI" {"Machine Learning" [{:name "PI:NAME:<NAME>END_PI" :grade "C"} {:name "PI:NAME:<NAME>END_PI" :grade "B-"}] "Compilers" [{:name "PI:NAME:<NAME>END_PI" :grade "B"} {:name "PI:NAME:<NAME>END_PI" :grade "A"}]}} students->profs {"PI:NAME:<NAME>END_PI" #{"PI:NAME:<NAME>END_PI"} "PI:NAME:<NAME>END_PI" #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"} "PI:NAME:<NAME>END_PI" #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"} "PI:NAME:<NAME>END_PI" #{"PI:NAME:<NAME>END_PI"} "PI:NAME:<NAME>END_PI" #{"PI:NAME:<NAME>END_PI"}}] ;; todo: fix (is (= (f/transform profs->classes->students {prof {_ [student]}} {(:name student) #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:keys [name]}]}} {name #{prof}}) students->profs)) (is (= (f/transform profs->classes->students {prof {_ [{:name name}]}} {name #{prof}}) students->profs)))) (deftest simple-vector-partioning (is (-> [1 2 3 4 5 6] (f/transform [a _] [a]) (= [1 3 5]))) (is (-> [1 2 3 4 5 6] (f/transform [a _ c] [a c]) (= [1 3 4 6]))) (is (-> [1 2 3 4 5 6] (f/transform [_ b _] [b]) (= [2 5]))) (is (-> [1 2 3 4 5] (f/transform [_ b] [b] :where [b]) (= [2 4]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[a _]] [a]) (= [1 3 5]))) (is (-> [[1 2] [3 4] [5 6]] (f/transform [[_ b]] [b]) (= [2 4 6]))) (is (-> [[1 2] [3 4]] (f/transform [[a]] [a]) (= [1 2 3 4])))) (deftest complex-vector-partitioning (is (-> {{:k :a} [1 2 3 4 5 6] {:k :b} [7 8 9 10 11 12]} (f/transform {{:keys [k]} [a _ c]} {(+ a c) k} :where [(even? a) (even? c)]) (= {10 :a, 22 :b}))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[_ b] _] [b] :where [b (even? b)]) (= [2 6]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [a _]] [a] :where [a (even? a)]) (= [4 98]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [_ [_ b]] [b] :where [b (even? b)]) (= [14]))) (is (-> [[1 2 3] [4 5 98 7] [5 6 8 17] [13 14 15]] (f/transform [[a _] _] [a] :where [a (even? a)]) (= [8])))) (deftest key-literals (let [data [{:num 6 :coll [1 2]} {:num 7 :coll [-94 -100]} {:num 8 :coll [3 4]}]] (is (-> data (f/transform [{:num n :coll [x]}] #{x} :where [(even? n)]) (= #{1 2 3 4}))) (is (-> data (f/transform [{:keys [num] :coll [x]}] #{x} :where [(odd? num)]) (= #{-94 -100})))) (let [pieces [{:composer "PI:NAME:<NAME>END_PI" :title "Piano Concerto 1" :year 1926} {:composer "PI:NAME:<NAME>END_PI" :title "String Quartet 2" :year 1917} {:composer "LiPI:NAME:<NAME>END_PIi" :title "Etude 1" :year 1985} {:composer "LiPI:NAME:<NAME>END_PIi" :title "Mysteries of the Macabre" :year 1992}] by-composer-and-year {"PI:NAME:<NAME>END_PI" {1926 [{:composer "PI:NAME:<NAME>END_PI", :title "Piano Concerto 1", :year 1926}], 1917 [{:composer "PI:NAME:<NAME>END_PI", :title "String Quartet 2", :year 1917}]}, "PI:NAME:<NAME>END_PI" {1985 [{:composer "LiPI:NAME:<NAME>END_PIi", :title "Etude 1", :year 1985}], 1992 [{:composer "PI:NAME:<NAME>END_PI", :title "Mysteries of the Macabre", :year 1992}]}}] (is (-> pieces (f/transform [{:keys [composer year] :as piece}] {composer {year [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:keys [composer] :year y :as piece}] {composer {y [piece]}}) (= by-composer-and-year))) (is (-> pieces (f/transform [{:composer c :year y :as piece}] {c {y [piece]}}) (= by-composer-and-year)))) (let [data [{:a 1 "b" 2}, {:a 2 "b" 3}, {:a 3 "b" 5}, {:a 4 "b" 4}] result {1 2 2 3 4 4 3 5}] (is (-> data (f/transform [{:a a "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:keys [a] "b" b}] {a b}) (= result))) (is (-> data (f/transform [{:strs [b] :a a}] {a b}) (= result)))) (let [data [{:keys 1 :strs 2 :syms 3 :as 4} {:keys 5 :strs 6 :syms 7 :as 8}]] (is (-> data (f/transform [{(:literal :keys) a (:literal :strs) b (:literal :syms) c (:literal :as) d}] #{(+ a b c d)}) (= #{10 26})))) (is (-> {[101 23] 4, [98] 2} (f/transform {(:literal [101 23]) x} #{x}) (= #{4})))) (deftest variable-key-literal (let [merge-key-vals (fn [m k1 k2] (f/transform m {(:literal k1) [v1] (:literal k2) [v2]} #{v1 v2}))] (is (-> {:a [1 2 3], :b [3 4 5], :c [5 6 7]} (merge-key-vals :a :b) (= #{1 2 3 4 5}))))) (deftest where (is (= {1 2, 3 4} (f/transform {1 (range), 2 [1, 2], 3 (range), 4 [3, 4]} {k [n]} {n k} :where [(even? k) (odd? n)])))) (deftest key-destructuring (let [pair-map {[1 2] 3 [4 5] 6} map-map {{:a 1 :b 2} 3 {:a 4 :b 5} 6}] (is (-> pair-map (f/transform {[n1 n2] v} #{(+ n1 n2 v)}) (= #{6 15}))) (is (-> map-map (f/transform {{:keys [a b]} v} #{(+ a b v)}) (= #{6 15}))))) (deftest combinations (is (= #{#{:c :d} #{:e :a} #{:b :a}} (f/transform {:a 7, :b 3, :c 5, :d 5, :e 3} {k v, k' v'} #{#{k k'}} :where [(not= k k') (= 10 (+ v v'))])))) (deftest higher-level-sanity-tests (let [json [{:store-name "Tom's Records" :location "1234 Main Street" :stock [{:artist "Bartók" :title "String Quartets" :quantity 5} {:artist "Ligeti" :title "Violin Concerto" :quantity 1}]} {:store-name "Roger's Records" :location "789 Secondary Street" :stock [{:artist "Ligeti" :title "Violin Concerto" :quantity 3} {:artist "Scriabin" :title "12 Etudes" :quantity 2}]}] transform (f/transformer [{:store-name store :location loc :stock [{:keys [artist title quantity]}]}] {artist {title [[(str store " @ " loc) quantity]]}}) result {"Bartók" {"String Quartets" [["Tom's Records @ 1234 Main Street" 5]]}, "Ligeti" {"Violin Concerto" [["Tom's Records @ 1234 Main Street" 1] ["Roger's Records @ 789 Secondary Street" 3]]}, "Scriabin" {"12 Etudes" [["Roger's Records @ 789 Secondary Street" 2]]}}] (is (= result (transform json))))) ;;;;;;;;;;;;;; ;; Reducers ;; ;;;;;;;;;;;;;; (deftest simple-reducers (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x])) 3)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (inc x)])) 4)) (is (= (f/transform [1 2 3 1 2 3] [x] (apply max ^:expand [x (count ^:expand [x])])) 6)) (is (= (f/transform [1 2 3 1 2 3] [x] (count ^:expand #{x})) 3)) (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} #{(apply max ^:expand [v])}) #{9})) ;; readme (is (= (f/transform {:a [1 2 3], :b [8 9 5], :d [4 5 6]} {k [v]} (apply max ^:expand [v])) 9))) (deftest complicated-reducers (let [student-data [{:student "PI:NAME:<NAME>END_PI", :grade1 97, :grade2 89, :course "math", :campus "east"} {:student "PI:NAME:<NAME>END_PI", :grade1 90, :grade2 70, :course "english", :campus "east"} {:student "PI:NAME:<NAME>END_PI", :grade1 70, :grade2 80, :course "history", :campus "east"} {:student "PI:NAME:<NAME>END_PI", :grade1 80, :grade2 80, :course "math", :campus "east"} {:student "PI:NAME:<NAME>END_PI", :grade1 100, :grade2 90, :course "english", :campus "east"} {:student "PI:NAME:<NAME>END_PI", :grade1 90, :grade2 86, :course "math", :campus "west"} {:student "PI:NAME:<NAME>END_PI", :grade1 92, :grade2 81, :course "english", :campus "west"} {:student "PI:NAME:<NAME>END_PI", :grade1 94, :grade2 83, :course "history", :campus "west"}] average (fn [xs] (/ (reduce + 0 xs) (count xs)))] (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (apply max ^:expand [grade2])}) {"PI:NAME:<NAME>END_PI" 89, "PI:NAME:<NAME>END_PI" 90, "PI:NAME:<NAME>END_PI" 86})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {student (max (apply max ^:expand [grade1]) (apply max ^:expand [grade2]))}) {"PI:NAME:<NAME>END_PI" 97, "PI:NAME:<NAME>END_PI" 100, "PI:NAME:<NAME>END_PI" 94})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course] :as tuple}] {student (:course (apply max-key :grade ^:expand [{:grade (/ (+ grade1 grade2) 2), :course course}]))}) {"PI:NAME:<NAME>END_PI" "math", "PI:NAME:<NAME>END_PI" "english", "mary" "history"})) (is (= (f/transform student-data [{:keys [student grade1 grade2 course]}] {course (count ^:expand [student])} :where [(> grade1 95)]) {"math" 1, "english" 1})) ;;readme (is (= (f/transform student-data [{:keys [student grade1 grade2 course campus]}] {campus {:number-students (count ^:expand #{student}) :avg-grade-per-course {course (average ^:expand [grade1])} :student-stats {student {course grade1}}}}) {"east" {:number-students 2, :avg-grade-per-course {"math" 177/2, "english" 95, "history" 70}, :student-stats {"PI:NAME:<NAME>END_PI" {"math" 97, "english" 90, "history" 70}, "PI:NAME:<NAME>END_PI" {"math" 80, "english" 100}}} "west" {:number-students 1, :avg-grade-per-course {"math" 90, "english" 92, "history" 94}, :student-stats {"mary" {"math" 90, "english" 92, "history" 94}}}})))) ;; Issue #3 on Github. (deftest test-expression-collections (is (= (f/transform [1 2 3 4 5 6] [x] {(if (even? x) :even :odd) (if (even? x) [(* 2 x)] [(+ 1 x)])}) {:even [4 8 12] :odd [2 4 6]})))
[ { "context": " sh/*sh-env* {\"GIT_AUTHOR_NAME\" \"chrondb\"\n \"GIT_AUTHOR_EMAIL", "end": 1914, "score": 0.9996577501296997, "start": 1907, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_AUTHOR_EMAIL\" \"chrondb@localhost\"\n \"GIT_AUTHOR_DATE\"", "end": 1987, "score": 0.9936323165893555, "start": 1970, "tag": "EMAIL", "value": "chrondb@localhost" }, { "context": " \"GIT_COMMITTER_NAME\" \"chrondb\"\n \"GIT_COMMITTER_EM", "end": 2121, "score": 0.9996539354324341, "start": 2114, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_COMMITTER_EMAIL\" \"chrondb@localhost\"\n \"GIT_COMMITTER_DA", "end": 2194, "score": 0.995752215385437, "start": 2177, "tag": "EMAIL", "value": "chrondb@localhost" }, { "context": " sh/*sh-env* {\"GIT_AUTHOR_NAME\" \"chrondb\"\n \"GIT_AUTHOR_EMAIL", "end": 5064, "score": 0.9996250867843628, "start": 5057, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_AUTHOR_EMAIL\" \"chrondb@localhost\"\n \"GIT_AUTHOR_DATE\"", "end": 5137, "score": 0.9950365424156189, "start": 5120, "tag": "EMAIL", "value": "chrondb@localhost" }, { "context": " \"GIT_COMMITTER_NAME\" \"chrondb\"\n \"GIT_COMMITTER_EM", "end": 5271, "score": 0.9996570348739624, "start": 5264, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_COMMITTER_EMAIL\" \"chrondb@localhost\"\n \"GIT_COMMITTER_DA", "end": 5344, "score": 0.9955664873123169, "start": 5327, "tag": "EMAIL", "value": "chrondb@localhost" }, { "context": " sh/*sh-env* {\"GIT_AUTHOR_NAME\" \"chrondb\"\n \"GIT_AUTHOR_EMAIL", "end": 8156, "score": 0.9994935989379883, "start": 8149, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_AUTHOR_EMAIL\" \"chrondb@localhost\"\n \"GIT_AUTHOR_DATE\"", "end": 8229, "score": 0.9959254264831543, "start": 8212, "tag": "EMAIL", "value": "chrondb@localhost" }, { "context": " \"GIT_COMMITTER_NAME\" \"chrondb\"\n \"GIT_COMMITTER_EM", "end": 8363, "score": 0.9995073080062866, "start": 8356, "tag": "USERNAME", "value": "chrondb" }, { "context": " \"GIT_COMMITTER_EMAIL\" \"chrondb@localhost\"\n \"GIT_COMMITTER_DA", "end": 8436, "score": 0.9935134649276733, "start": 8419, "tag": "EMAIL", "value": "chrondb@localhost" } ]
test/chrondb/api_v1_test.clj
chrondb/chrondb
11
(ns chrondb.api-v1-test (:require [chrondb.api-v1 :as api-v1] [clojure.data.json :as json] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :as pp] [clojure.test :refer [deftest is]]) (:import (java.io File) (java.time Clock))) (deftest tree-structure-initial (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}] :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}}] :id "a94d21dae8119225c328cf695d146e1bc508a3b4"}}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-api" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "chrondb@localhost" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "chrondb@localhost" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit")) (sh/sh "git" "clone" "--bare" "tree-structure-cli" "tree-structure-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-one-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree :id "da8827b2ac89361970b216f063281dcd36754436" :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n" :file-mode "100644" :node {:mode :blob :id "c227083464fb9af8955c90d2924774ee50abb547"}}],}, :parents [{:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-one-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-one-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "chrondb@localhost" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "chrondb@localhost" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-one-commit-cli" "tree-structure-one-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-one-commit-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-two-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "b27a5ddb587294b578136293087cefda502bc4dc", :tree {:mode :tree, :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob, :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n", :file-mode "100644", :node {:mode :blob, :id "56a6051ca2b02b04ef92d5150c9ef600403cb1de"}}], :id "b2fafedd676bed8b9aa0ea018f7e2e58ebb16222"}, :parents [{:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-two-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (api-v1/save chronn "n" 1) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-two-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "chrondb@localhost" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "chrondb@localhost" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!") (spit (io/file dir "n") (json/write-str 1)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-two-commit-cli" "tree-structure-two-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-two-commit-cli-bare")) #_(doto pp/pprint)))))))) (deftest hello #_(doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/counter-v1" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/save chronn "n" 42) :db-after (api-v1/select-keys ["n"]) #_(doto pp/pprint)))) (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/select-keys (api-v1/db chronn) ["n"]) #_(doto pp/pprint)))))))
105976
(ns chrondb.api-v1-test (:require [chrondb.api-v1 :as api-v1] [clojure.data.json :as json] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :as pp] [clojure.test :refer [deftest is]]) (:import (java.io File) (java.time Clock))) (deftest tree-structure-initial (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}] :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}}] :id "a94d21dae8119225c328cf695d146e1bc508a3b4"}}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-api" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "<EMAIL>" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "<EMAIL>" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit")) (sh/sh "git" "clone" "--bare" "tree-structure-cli" "tree-structure-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-one-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree :id "da8827b2ac89361970b216f063281dcd36754436" :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n" :file-mode "100644" :node {:mode :blob :id "c227083464fb9af8955c90d2924774ee50abb547"}}],}, :parents [{:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-one-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-one-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "<EMAIL>" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "<EMAIL>" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-one-commit-cli" "tree-structure-one-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-one-commit-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-two-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "b27a5ddb587294b578136293087cefda502bc4dc", :tree {:mode :tree, :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob, :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n", :file-mode "100644", :node {:mode :blob, :id "56a6051ca2b02b04ef92d5150c9ef600403cb1de"}}], :id "b2fafedd676bed8b9aa0ea018f7e2e58ebb16222"}, :parents [{:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-two-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (api-v1/save chronn "n" 1) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-two-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "<EMAIL>" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "<EMAIL>" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!") (spit (io/file dir "n") (json/write-str 1)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-two-commit-cli" "tree-structure-two-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-two-commit-cli-bare")) #_(doto pp/pprint)))))))) (deftest hello #_(doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/counter-v1" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/save chronn "n" 42) :db-after (api-v1/select-keys ["n"]) #_(doto pp/pprint)))) (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/select-keys (api-v1/db chronn) ["n"]) #_(doto pp/pprint)))))))
true
(ns chrondb.api-v1-test (:require [chrondb.api-v1 :as api-v1] [clojure.data.json :as json] [clojure.java.io :as io] [clojure.java.shell :as sh] [clojure.pprint :as pp] [clojure.test :refer [deftest is]]) (:import (java.io File) (java.time Clock))) (deftest tree-structure-initial (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}] :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}}] :id "a94d21dae8119225c328cf695d146e1bc508a3b4"}}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-api" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit")) (sh/sh "git" "clone" "--bare" "tree-structure-cli" "tree-structure-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-one-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree :id "da8827b2ac89361970b216f063281dcd36754436" :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n" :file-mode "100644" :node {:mode :blob :id "c227083464fb9af8955c90d2924774ee50abb547"}}],}, :parents [{:mode :commit, :id "8032734087759f0f070110508bfb5121ec0953ea", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-one-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-one-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-one-commit-cli" "tree-structure-one-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-one-commit-cli-bare")) (doto pp/pprint)))))))) (deftest tree-structure-two-commit (doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (let [target-tree {:mode :commit, :id "b27a5ddb587294b578136293087cefda502bc4dc", :tree {:mode :tree, :nodes [{:path "db", :file-mode "40000", :node {:mode :tree, :nodes [{:path "created-at", :file-mode "100644", :node {:mode :blob, :id "ac9ca5ace6edc38c42358de2ddf86a63e01d73c7"}}], :id "0c1f142900173cf36350f9d2b72a5ad4f42244cf"}} {:path "n", :file-mode "100644", :node {:mode :blob, :id "56a6051ca2b02b04ef92d5150c9ef600403cb1de"}}], :id "b2fafedd676bed8b9aa0ea018f7e2e58ebb16222"}, :parents [{:mode :commit, :id "2bb88ab180c2007177b7b177ce443bff1dfb4b6b", :tree {:mode :tree}}]}] (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/tree-structure-two-commit" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (api-v1/save chronn "n" 0) (api-v1/save chronn "n" 1) (is (= target-tree (-> (api-v1/repo->clj chronn) (doto pp/pprint))))) (let [dir (io/file "data" "tree-structure-two-commit-cli")] (binding [sh/*sh-dir* dir sh/*sh-env* {"GIT_AUTHOR_NAME" "chrondb" "GIT_AUTHOR_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_AUTHOR_DATE" "946684800 +0000" "GIT_COMMITTER_NAME" "chrondb" "GIT_COMMITTER_EMAIL" "PI:EMAIL:<EMAIL>END_PI" "GIT_COMMITTER_DATE" "946684800 +0000"}] (.mkdirs dir) (sh/sh "git" "init" "--initial-branch=main" ".") (sh/sh "mkdir" "db") (spit (io/file dir "db" "created-at") (json/write-str (str (.toInstant #inst"2000")))) (sh/sh "git" "add" "db/created-at") (sh/sh "git" "commit" "-aminit") (spit (io/file dir "n") (json/write-str 0)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!") (spit (io/file dir "n") (json/write-str 1)) (sh/sh "git" "add" "n") (sh/sh "git" "commit" "-amHello!")) (sh/sh "git" "clone" "--bare" "tree-structure-two-commit-cli" "tree-structure-two-commit-cli-bare" :dir (io/file "data")) (is (= target-tree (-> (api-v1/repo->clj (api-v1/connect "chrondb:file://data/tree-structure-two-commit-cli-bare")) #_(doto pp/pprint)))))))) (deftest hello #_(doseq [^File f (reverse (file-seq (io/file "data")))] (.delete f)) (binding [api-v1/*clock* (proxy [Clock] [] (instant [] (.toInstant #inst"2000")))] (let [chronn (-> "chrondb:file://data/counter-v1" (doto api-v1/delete-database api-v1/create-database) api-v1/connect)] (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/save chronn "n" 42) :db-after (api-v1/select-keys ["n"]) #_(doto pp/pprint)))) (is (= {"db/created-at" "2000-01-01T00:00:00Z"} (-> (api-v1/select-keys (api-v1/db chronn) ["db/created-at"]) #_(doto pp/pprint)))) (is (= {"n" 42} (-> (api-v1/select-keys (api-v1/db chronn) ["n"]) #_(doto pp/pprint)))))))
[ { "context": " with adjusted scores for the other nations as per Abel, Payne\n and Barclay but calculated by Alex Parso", "end": 2021, "score": 0.9719228744506836, "start": 2017, "tag": "NAME", "value": "Abel" }, { "context": "adjusted scores for the other nations as per Abel, Payne\n and Barclay but calculated by Alex Parsons on b", "end": 2028, "score": 0.9374374151229858, "start": 2023, "tag": "NAME", "value": "Payne" }, { "context": "for the other nations as per Abel, Payne\n and Barclay but calculated by Alex Parsons on behalf of MySoc", "end": 2042, "score": 0.732721209526062, "start": 2038, "tag": "NAME", "value": "clay" }, { "context": "as per Abel, Payne\n and Barclay but calculated by Alex Parsons on behalf of MySociety.\"\n \"https://github.com/my", "end": 2073, "score": 0.9998438358306885, "start": 2061, "tag": "NAME", "value": "Alex Parsons" }, { "context": "\"with adjusted scores for the other nations as per Abel, Payne and Barclay but\"\n ", "end": 5722, "score": 0.9749380946159363, "start": 5718, "tag": "NAME", "value": "Abel" }, { "context": "adjusted scores for the other nations as per Abel, Payne and Barclay but\"\n ", "end": 5729, "score": 0.9192118644714355, "start": 5724, "tag": "NAME", "value": "Payne" }, { "context": "cores for the other nations as per Abel, Payne and Barclay but\"\n ", "end": 5741, "score": 0.7848585247993469, "start": 5734, "tag": "NAME", "value": "Barclay" }, { "context": " \"calculated by Alex Parsons on behalf of MySociety.\"])\n ", "end": 5836, "score": 0.9996291399002075, "start": 5824, "tag": "NAME", "value": "Alex Parsons" } ]
src/com/eldrix/deprivare/datasets.clj
eatyourpeas/deprivare
0
(ns com.eldrix.deprivare.datasets (:require [clj-http.client :as client] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.core.async :as a] [com.eldrix.deprivare.odf :as odf] [clojure.data.csv :as csv] [clojure.edn :as edn]) (:import [java.io File])) (defn parse-double-as-long [s] (long (parse-double s))) (def property-parsers {:uk-composite-imd-2020-mysoc/income_score parse-double :uk-composite-imd-2020-mysoc/E_expanded_decile parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_score parse-double :uk-composite-imd-2020-mysoc/overall_local_score parse-double :uk-composite-imd-2020-mysoc/original_decile parse-long :uk-composite-imd-2020-mysoc/UK_IMD_E_rank parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_quintile parse-long :uk-composite-imd-2020-mysoc/employment_score parse-double :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile parse-long}) (defn parse [m] (reduce-kv (fn [acc k v] (if-let [parser (get property-parsers k)] (assoc acc k (try (parser v) (catch Exception e (throw (ex-info "failed to parse" {:k k :v v}))))) (assoc acc k v))) {} m)) (defn- download-file "Downloads a file from a URL to a temporary file, which is returned. Sets the user agent header appropriately; some URLs return a 403 if there is no defined user agent, including gov.wales." [url prefix suffix] (let [f (File/createTempFile prefix suffix)] (with-open [is (:body (client/get url {:headers {"User-Agent" "deprivare v0.1"} :as :stream})) os (io/output-stream f)] (io/copy is os) f))) (def uk-composite-imd-2020-mysoc-url "URL to download a composite UK score for deprivation indices for 2020 - based on England with adjusted scores for the other nations as per Abel, Payne and Barclay but calculated by Alex Parsons on behalf of MySociety." "https://github.com/mysociety/composite_uk_imd/blob/e7a14d3317d9462890c28513866687a3a35adc8d/uk_index/UK_IMD_E.csv?raw=true") (def headers-uk-composite-2020-mysoc ["nation" "lsoa" "overall_local_score" "income_score" "employment_score" "UK_IMD_E_score" "original_decile" "E_expanded_decile" "UK_IMD_E_rank" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile"]) (defn stream-uk-composite-imd-2020 "Streams the uk-composite-imd-2020-mysoc data to the channel specified." [ch] (with-open [reader (io/reader uk-composite-imd-2020-mysoc-url)] (let [lines (csv/read-csv reader)] (if-not (= headers-uk-composite-2020-mysoc (first lines)) (throw (ex-info "invalid CSV headers" {:expected headers-uk-composite-2020-mysoc :actual (first lines)})) (doall (->> (map zipmap (->> (first lines) (map #(keyword "uk-composite-imd-2020-mysoc" %)) repeat) (rest lines)) (map parse) (map #(assoc % :uk.gov.ons/lsoa (:uk-composite-imd-2020-mysoc/lsoa %) :dataset :uk-composite-imd-2020-mysoc)) (map #(dissoc % :uk-composite-imd-2020-mysoc/lsoa)) (map #(a/>!! ch %)))))))) (defn stream-wales-imd-2019-ranks [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "WIMD_2019_ranks" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :income :employment :health :education :access_to_services :housing :community_safety :physical_environment]) :pred #(and (= (count %) 12) (.startsWith (first %) "W")))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-ranks)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (defn stream-wales-imd-2019-quantiles [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "Deciles_quintiles_quartiles" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :wimd_2019_decile :wimd_2019_quintile :wimd_2019_quartile]) :pred (fn [row] (and (= (count row) 7) (.startsWith ^String (first row) "W"))))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-quantiles)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (def available-data {:uk-composite-imd-2020-mysoc {:title "UK composite index of multiple deprivation, 2020 (MySociety)" :year 2020 :description (str/join "\n" ["A composite UK score for deprivation indices for 2020 - based on England" "with adjusted scores for the other nations as per Abel, Payne and Barclay but" "calculated by Alex Parsons on behalf of MySociety."]) :properties ["E_expanded_decile" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile" "UK_IMD_E_rank" "UK_IMD_E_score" "employment_score" "income_score" "nation" "original_decile" "overall_local_score"] :stream-fn stream-uk-composite-imd-2020} :wales-imd-2019-ranks {:title "Welsh Index of Deprivation - ranks, 2019" :year 2019 :description "Welsh Index of Deprivation - raw ranks for each domain, by LSOA." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "access_to_services" "community_safety" "education" "employment" "health" "housing" "income" "physical_environment" "wimd_2019"] :stream-fn stream-wales-imd-2019-ranks} :wales-imd-2019-quantiles {:title "Welsh Index of Deprivation - quantiles, 2019" :year 2019 :description "Welsh Index of Deprivation - with composite rank with decile, quintile and quartile." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "wimd_2019" "wimd_2019_decile" "wimd_2019_quintile" "wimd_2019_quartile"] :stream-fn stream-wales-imd-2019-quantiles}}) (defn properties-for-dataset [dataset] (let [dataset' (get available-data (keyword dataset)) nspace (or (:namespace dataset') (name dataset))] (set (map #(keyword nspace (name %)) (:properties dataset'))))) (defn properties-for-datasets [datasets] (apply set/union (map properties-for-dataset datasets))) (comment (properties-for-dataset :uk-composite-imd-2020-mysoc) (properties-for-datasets [:uk-composite-imd-2020-mysoc :wales-imd-2019-quantiles]) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-wales-imd-2019-ranks ch)) (a/<!! ch) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-uk-composite-imd-2020 ch)) (a/<!! ch))
47538
(ns com.eldrix.deprivare.datasets (:require [clj-http.client :as client] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.core.async :as a] [com.eldrix.deprivare.odf :as odf] [clojure.data.csv :as csv] [clojure.edn :as edn]) (:import [java.io File])) (defn parse-double-as-long [s] (long (parse-double s))) (def property-parsers {:uk-composite-imd-2020-mysoc/income_score parse-double :uk-composite-imd-2020-mysoc/E_expanded_decile parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_score parse-double :uk-composite-imd-2020-mysoc/overall_local_score parse-double :uk-composite-imd-2020-mysoc/original_decile parse-long :uk-composite-imd-2020-mysoc/UK_IMD_E_rank parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_quintile parse-long :uk-composite-imd-2020-mysoc/employment_score parse-double :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile parse-long}) (defn parse [m] (reduce-kv (fn [acc k v] (if-let [parser (get property-parsers k)] (assoc acc k (try (parser v) (catch Exception e (throw (ex-info "failed to parse" {:k k :v v}))))) (assoc acc k v))) {} m)) (defn- download-file "Downloads a file from a URL to a temporary file, which is returned. Sets the user agent header appropriately; some URLs return a 403 if there is no defined user agent, including gov.wales." [url prefix suffix] (let [f (File/createTempFile prefix suffix)] (with-open [is (:body (client/get url {:headers {"User-Agent" "deprivare v0.1"} :as :stream})) os (io/output-stream f)] (io/copy is os) f))) (def uk-composite-imd-2020-mysoc-url "URL to download a composite UK score for deprivation indices for 2020 - based on England with adjusted scores for the other nations as per <NAME>, <NAME> and Bar<NAME> but calculated by <NAME> on behalf of MySociety." "https://github.com/mysociety/composite_uk_imd/blob/e7a14d3317d9462890c28513866687a3a35adc8d/uk_index/UK_IMD_E.csv?raw=true") (def headers-uk-composite-2020-mysoc ["nation" "lsoa" "overall_local_score" "income_score" "employment_score" "UK_IMD_E_score" "original_decile" "E_expanded_decile" "UK_IMD_E_rank" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile"]) (defn stream-uk-composite-imd-2020 "Streams the uk-composite-imd-2020-mysoc data to the channel specified." [ch] (with-open [reader (io/reader uk-composite-imd-2020-mysoc-url)] (let [lines (csv/read-csv reader)] (if-not (= headers-uk-composite-2020-mysoc (first lines)) (throw (ex-info "invalid CSV headers" {:expected headers-uk-composite-2020-mysoc :actual (first lines)})) (doall (->> (map zipmap (->> (first lines) (map #(keyword "uk-composite-imd-2020-mysoc" %)) repeat) (rest lines)) (map parse) (map #(assoc % :uk.gov.ons/lsoa (:uk-composite-imd-2020-mysoc/lsoa %) :dataset :uk-composite-imd-2020-mysoc)) (map #(dissoc % :uk-composite-imd-2020-mysoc/lsoa)) (map #(a/>!! ch %)))))))) (defn stream-wales-imd-2019-ranks [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "WIMD_2019_ranks" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :income :employment :health :education :access_to_services :housing :community_safety :physical_environment]) :pred #(and (= (count %) 12) (.startsWith (first %) "W")))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-ranks)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (defn stream-wales-imd-2019-quantiles [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "Deciles_quintiles_quartiles" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :wimd_2019_decile :wimd_2019_quintile :wimd_2019_quartile]) :pred (fn [row] (and (= (count row) 7) (.startsWith ^String (first row) "W"))))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-quantiles)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (def available-data {:uk-composite-imd-2020-mysoc {:title "UK composite index of multiple deprivation, 2020 (MySociety)" :year 2020 :description (str/join "\n" ["A composite UK score for deprivation indices for 2020 - based on England" "with adjusted scores for the other nations as per <NAME>, <NAME> and <NAME> but" "calculated by <NAME> on behalf of MySociety."]) :properties ["E_expanded_decile" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile" "UK_IMD_E_rank" "UK_IMD_E_score" "employment_score" "income_score" "nation" "original_decile" "overall_local_score"] :stream-fn stream-uk-composite-imd-2020} :wales-imd-2019-ranks {:title "Welsh Index of Deprivation - ranks, 2019" :year 2019 :description "Welsh Index of Deprivation - raw ranks for each domain, by LSOA." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "access_to_services" "community_safety" "education" "employment" "health" "housing" "income" "physical_environment" "wimd_2019"] :stream-fn stream-wales-imd-2019-ranks} :wales-imd-2019-quantiles {:title "Welsh Index of Deprivation - quantiles, 2019" :year 2019 :description "Welsh Index of Deprivation - with composite rank with decile, quintile and quartile." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "wimd_2019" "wimd_2019_decile" "wimd_2019_quintile" "wimd_2019_quartile"] :stream-fn stream-wales-imd-2019-quantiles}}) (defn properties-for-dataset [dataset] (let [dataset' (get available-data (keyword dataset)) nspace (or (:namespace dataset') (name dataset))] (set (map #(keyword nspace (name %)) (:properties dataset'))))) (defn properties-for-datasets [datasets] (apply set/union (map properties-for-dataset datasets))) (comment (properties-for-dataset :uk-composite-imd-2020-mysoc) (properties-for-datasets [:uk-composite-imd-2020-mysoc :wales-imd-2019-quantiles]) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-wales-imd-2019-ranks ch)) (a/<!! ch) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-uk-composite-imd-2020 ch)) (a/<!! ch))
true
(ns com.eldrix.deprivare.datasets (:require [clj-http.client :as client] [clojure.java.io :as io] [clojure.set :as set] [clojure.string :as str] [clojure.core.async :as a] [com.eldrix.deprivare.odf :as odf] [clojure.data.csv :as csv] [clojure.edn :as edn]) (:import [java.io File])) (defn parse-double-as-long [s] (long (parse-double s))) (def property-parsers {:uk-composite-imd-2020-mysoc/income_score parse-double :uk-composite-imd-2020-mysoc/E_expanded_decile parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_score parse-double :uk-composite-imd-2020-mysoc/overall_local_score parse-double :uk-composite-imd-2020-mysoc/original_decile parse-long :uk-composite-imd-2020-mysoc/UK_IMD_E_rank parse-double-as-long :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_quintile parse-long :uk-composite-imd-2020-mysoc/employment_score parse-double :uk-composite-imd-2020-mysoc/UK_IMD_E_pop_decile parse-long}) (defn parse [m] (reduce-kv (fn [acc k v] (if-let [parser (get property-parsers k)] (assoc acc k (try (parser v) (catch Exception e (throw (ex-info "failed to parse" {:k k :v v}))))) (assoc acc k v))) {} m)) (defn- download-file "Downloads a file from a URL to a temporary file, which is returned. Sets the user agent header appropriately; some URLs return a 403 if there is no defined user agent, including gov.wales." [url prefix suffix] (let [f (File/createTempFile prefix suffix)] (with-open [is (:body (client/get url {:headers {"User-Agent" "deprivare v0.1"} :as :stream})) os (io/output-stream f)] (io/copy is os) f))) (def uk-composite-imd-2020-mysoc-url "URL to download a composite UK score for deprivation indices for 2020 - based on England with adjusted scores for the other nations as per PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and BarPI:NAME:<NAME>END_PI but calculated by PI:NAME:<NAME>END_PI on behalf of MySociety." "https://github.com/mysociety/composite_uk_imd/blob/e7a14d3317d9462890c28513866687a3a35adc8d/uk_index/UK_IMD_E.csv?raw=true") (def headers-uk-composite-2020-mysoc ["nation" "lsoa" "overall_local_score" "income_score" "employment_score" "UK_IMD_E_score" "original_decile" "E_expanded_decile" "UK_IMD_E_rank" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile"]) (defn stream-uk-composite-imd-2020 "Streams the uk-composite-imd-2020-mysoc data to the channel specified." [ch] (with-open [reader (io/reader uk-composite-imd-2020-mysoc-url)] (let [lines (csv/read-csv reader)] (if-not (= headers-uk-composite-2020-mysoc (first lines)) (throw (ex-info "invalid CSV headers" {:expected headers-uk-composite-2020-mysoc :actual (first lines)})) (doall (->> (map zipmap (->> (first lines) (map #(keyword "uk-composite-imd-2020-mysoc" %)) repeat) (rest lines)) (map parse) (map #(assoc % :uk.gov.ons/lsoa (:uk-composite-imd-2020-mysoc/lsoa %) :dataset :uk-composite-imd-2020-mysoc)) (map #(dissoc % :uk-composite-imd-2020-mysoc/lsoa)) (map #(a/>!! ch %)))))))) (defn stream-wales-imd-2019-ranks [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "WIMD_2019_ranks" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :income :employment :health :education :access_to_services :housing :community_safety :physical_environment]) :pred #(and (= (count %) 12) (.startsWith (first %) "W")))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-ranks)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (defn stream-wales-imd-2019-quantiles [ch] (let [f (download-file "https://gov.wales/sites/default/files/statistics-and-research/2019-11/welsh-index-multiple-deprivation-2019-index-and-domain-ranks-by-small-area.ods" "wimd-2019-" ".ods") data (odf/sheet-data f "Deciles_quintiles_quartiles" :headings (map #(keyword "wales-imd-2019" (name %)) [:lsoa :lsoa_name :authority_name :wimd_2019 :wimd_2019_decile :wimd_2019_quintile :wimd_2019_quartile]) :pred (fn [row] (and (= (count row) 7) (.startsWith ^String (first row) "W"))))] (doall (->> data (map #(assoc % :uk.gov.ons/lsoa (:wales-imd-2019/lsoa %) :dataset :wales-imd-2019-quantiles)) (map #(dissoc % :wales-imd-2019/lsoa)) (map #(a/>!! ch %)))))) (def available-data {:uk-composite-imd-2020-mysoc {:title "UK composite index of multiple deprivation, 2020 (MySociety)" :year 2020 :description (str/join "\n" ["A composite UK score for deprivation indices for 2020 - based on England" "with adjusted scores for the other nations as per PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI but" "calculated by PI:NAME:<NAME>END_PI on behalf of MySociety."]) :properties ["E_expanded_decile" "UK_IMD_E_pop_decile" "UK_IMD_E_pop_quintile" "UK_IMD_E_rank" "UK_IMD_E_score" "employment_score" "income_score" "nation" "original_decile" "overall_local_score"] :stream-fn stream-uk-composite-imd-2020} :wales-imd-2019-ranks {:title "Welsh Index of Deprivation - ranks, 2019" :year 2019 :description "Welsh Index of Deprivation - raw ranks for each domain, by LSOA." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "access_to_services" "community_safety" "education" "employment" "health" "housing" "income" "physical_environment" "wimd_2019"] :stream-fn stream-wales-imd-2019-ranks} :wales-imd-2019-quantiles {:title "Welsh Index of Deprivation - quantiles, 2019" :year 2019 :description "Welsh Index of Deprivation - with composite rank with decile, quintile and quartile." :namespace "wales-imd-2019" :properties ["lsoa_name" "authority_name" "wimd_2019" "wimd_2019_decile" "wimd_2019_quintile" "wimd_2019_quartile"] :stream-fn stream-wales-imd-2019-quantiles}}) (defn properties-for-dataset [dataset] (let [dataset' (get available-data (keyword dataset)) nspace (or (:namespace dataset') (name dataset))] (set (map #(keyword nspace (name %)) (:properties dataset'))))) (defn properties-for-datasets [datasets] (apply set/union (map properties-for-dataset datasets))) (comment (properties-for-dataset :uk-composite-imd-2020-mysoc) (properties-for-datasets [:uk-composite-imd-2020-mysoc :wales-imd-2019-quantiles]) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-wales-imd-2019-ranks ch)) (a/<!! ch) (def ch (a/chan 16 (partition-all 5))) (a/thread (stream-uk-composite-imd-2020 ch)) (a/<!! ch))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.99985671043396, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "any other, from this software.\n\n(ns \n ^{:author \"Stuart Sierra, Chas Emerick, Stuart Halloway\",\n :doc \"This ", "end": 495, "score": 0.9998709559440613, "start": 482, "tag": "NAME", "value": "Stuart Sierra" }, { "context": "m this software.\n\n(ns \n ^{:author \"Stuart Sierra, Chas Emerick, Stuart Halloway\",\n :doc \"This file defines p", "end": 509, "score": 0.999869167804718, "start": 497, "tag": "NAME", "value": "Chas Emerick" }, { "context": "e.\n\n(ns \n ^{:author \"Stuart Sierra, Chas Emerick, Stuart Halloway\",\n :doc \"This file defines polymorphic I/O ut", "end": 526, "score": 0.9998518228530884, "start": 511, "tag": "NAME", "value": "Stuart Halloway" } ]
data/clojure/0b9bd7c970739b57cfda8aa785dde86a_io.clj
maxim5/code-inspector
5
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "Stuart Sierra, Chas Emerick, Stuart Halloway", :doc "This file defines polymorphic I/O utility functions for Clojure."} clojure.java.io (:require clojure.string) (:import (java.io Reader InputStream InputStreamReader PushbackReader BufferedReader File OutputStream OutputStreamWriter BufferedWriter Writer FileInputStream FileOutputStream ByteArrayOutputStream StringReader ByteArrayInputStream BufferedInputStream BufferedOutputStream CharArrayReader Closeable) (java.net URI URL MalformedURLException Socket))) (def ^{:doc "Type object for a Java primitive byte array." :private true } byte-array-type (class (make-array Byte/TYPE 0))) (def ^{:doc "Type object for a Java primitive char array." :private true} char-array-type (class (make-array Character/TYPE 0))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag java.io.File, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag java.net.URL, :added "1.2"} as-url [x] "Coerce argument to a URL.")) (extend-protocol Coercions nil (as-file [_] nil) (as-url [_] nil) String (as-file [s] (File. s)) (as-url [s] (URL. s)) File (as-file [f] f) (as-url [f] (.toURL (.toURI f))) URL (as-url [u] u) (as-file [u] (if (= "file" (.getProtocol u)) (as-file (clojure.string/replace (.replace (.getFile u) \/ File/separatorChar) #"%.." (fn [escape] (-> escape (.substring 1 3) (Integer/parseInt 16) (char) (str))))) (throw (IllegalArgumentException. (str "Not a file: " u))))) URI (as-url [u] (.toURL u)) (as-file [u] (as-file (as-url u)))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :append true to open stream in append mode :encoding string name of encoding to use, e.g. \"UTF-8\". Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-reader [x opts] "Creates a BufferedReader. See also IOFactory docs.") (^{:added "1.2"} make-writer [x opts] "Creates a BufferedWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a BufferedInputStream. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a BufferedOutputStream. See also IOFactory docs.")) (defn ^Reader reader "Attempts to coerce its argument into an open java.io.Reader. Default implementations always return a java.io.BufferedReader. Default implementations are provided for Reader, BufferedReader, InputStream, File, URI, URL, Socket, byte arrays, character arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Reader is properly closed." {:added "1.2"} [x & opts] (make-reader x (when opts (apply hash-map opts)))) (defn ^Writer writer "Attempts to coerce its argument into an open java.io.Writer. Default implementations always return a java.io.BufferedWriter. Default implementations are provided for Writer, BufferedWriter, OutputStream, File, URI, URL, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Writer is properly closed." {:added "1.2"} [x & opts] (make-writer x (when opts (apply hash-map opts)))) (defn ^InputStream input-stream "Attempts to coerce its argument into an open java.io.InputStream. Default implementations always return a java.io.BufferedInputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the InputStream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^OutputStream output-stream "Attempts to coerce its argument into an open java.io.OutputStream. Default implementations always return a java.io.BufferedOutputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn- ^Boolean append? [opts] (boolean (:append opts))) (defn- ^String encoding [opts] (or (:encoding opts) "UTF-8")) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (def default-streams-impl {:make-reader (fn [x opts] (make-reader (make-input-stream x opts) opts)) :make-writer (fn [x opts] (make-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an InputStream.")))) :make-output-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an OutputStream."))))}) (defn- inputstream->reader [^InputStream is opts] (make-reader (InputStreamReader. is (encoding opts)) opts)) (defn- outputstream->writer [^OutputStream os opts] (make-writer (OutputStreamWriter. os (encoding opts)) opts)) (extend BufferedInputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] x) :make-reader inputstream->reader)) (extend InputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (BufferedInputStream. x)) :make-reader inputstream->reader)) (extend Reader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (BufferedReader. x)))) (extend BufferedReader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] x))) (extend Writer IOFactory (assoc default-streams-impl :make-writer (fn [x opts] (BufferedWriter. x)))) (extend BufferedWriter IOFactory (assoc default-streams-impl :make-writer (fn [x opts] x))) (extend OutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] (BufferedOutputStream. x)) :make-writer outputstream->writer)) (extend BufferedOutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] x) :make-writer outputstream->writer)) (extend File IOFactory (assoc default-streams-impl :make-input-stream (fn [^File x opts] (make-input-stream (FileInputStream. x) opts)) :make-output-stream (fn [^File x opts] (make-output-stream (FileOutputStream. x (append? opts)) opts)))) (extend URL IOFactory (assoc default-streams-impl :make-input-stream (fn [^URL x opts] (make-input-stream (if (= "file" (.getProtocol x)) (FileInputStream. (as-file x)) (.openStream x)) opts)) :make-output-stream (fn [^URL x opts] (if (= "file" (.getProtocol x)) (make-output-stream (as-file x) opts) (throw (IllegalArgumentException. (str "Can not write to non-file URL <" x ">"))))))) (extend URI IOFactory (assoc default-streams-impl :make-input-stream (fn [^URI x opts] (make-input-stream (.toURL x) opts)) :make-output-stream (fn [^URI x opts] (make-output-stream (.toURL x) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (URL. x) opts) (catch MalformedURLException e (make-input-stream (File. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (URL. x) opts) (catch MalformedURLException err (make-output-stream (File. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (make-input-stream (.getInputStream x) opts)) :make-output-stream (fn [^Socket x opts] (make-output-stream (.getOutputStream x) opts)))) (extend byte-array-type IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (make-input-stream (ByteArrayInputStream. x) opts)))) (extend char-array-type IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (make-reader (CharArrayReader. x) opts)))) (extend Object IOFactory default-streams-impl) (defmulti #^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [InputStream OutputStream] [#^InputStream input #^OutputStream output opts] (let [buffer (make-array Byte/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream Writer] [#^InputStream input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) in (InputStreamReader. input (encoding opts))] (loop [] (let [size (.read in buffer 0 (alength buffer))] (if (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream File] [#^InputStream input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [Reader OutputStream] [#^Reader input #^OutputStream output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) out (OutputStreamWriter. output (encoding opts))] (loop [] (let [size (.read input buffer)] (if (pos? size) (do (.write out buffer 0 size) (recur)) (.flush out)))))) (defmethod do-copy [Reader Writer] [#^Reader input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [Reader File] [#^Reader input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [File OutputStream] [#^File input #^OutputStream output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File Writer] [#^File input #^Writer output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File File] [#^File input #^File output opts] (with-open [in (FileInputStream. input) out (FileOutputStream. output)] (do-copy in out opts))) (defmethod do-copy [String OutputStream] [#^String input #^OutputStream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String Writer] [#^String input #^Writer output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String File] [#^String input #^File output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [char-array-type OutputStream] [input #^OutputStream output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type Writer] [input #^Writer output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type File] [input #^File output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [byte-array-type OutputStream] [#^"[B" input #^OutputStream output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type Writer] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type File] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts)))) (defn ^String as-relative-path "Take an as-file-able thing and return a string if it is a relative path, else IllegalArgumentException." {:added "1.2"} [x] (let [^File f (as-file x)] (if (.isAbsolute f) (throw (IllegalArgumentException. (str f " is not a relative path"))) (.getPath f)))) (defn ^File file "Returns a java.io.File, passing each arg to as-file. Multiple-arg versions treat the first argument as parent and subsequent args as children relative to the parent." {:added "1.2"} ([arg] (as-file arg)) ([parent child] (File. ^File (as-file parent) ^String (as-relative-path child))) ([parent child & more] (reduce file (file parent child) more))) (defn delete-file "Delete file f. Raise an exception if it fails unless silently is true." {:added "1.2"} [f & [silently]] (or (.delete (file f)) silently (throw (java.io.IOException. (str "Couldn't delete " f))))) (defn make-parents "Given the same arg(s) as for file, creates all parent directories of the file they represent." {:added "1.2"} [f & more] (when-let [parent (.getParentFile ^File (apply file f more))] (.mkdirs parent))) (defn ^URL resource "Returns the URL for a named resource. Use the context class loader if no loader is specified." {:added "1.2"} ([n] (resource n (.getContextClassLoader (Thread/currentThread)))) ([n ^ClassLoader loader] (.getResource loader n)))
44565
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "<NAME>, <NAME>, <NAME>", :doc "This file defines polymorphic I/O utility functions for Clojure."} clojure.java.io (:require clojure.string) (:import (java.io Reader InputStream InputStreamReader PushbackReader BufferedReader File OutputStream OutputStreamWriter BufferedWriter Writer FileInputStream FileOutputStream ByteArrayOutputStream StringReader ByteArrayInputStream BufferedInputStream BufferedOutputStream CharArrayReader Closeable) (java.net URI URL MalformedURLException Socket))) (def ^{:doc "Type object for a Java primitive byte array." :private true } byte-array-type (class (make-array Byte/TYPE 0))) (def ^{:doc "Type object for a Java primitive char array." :private true} char-array-type (class (make-array Character/TYPE 0))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag java.io.File, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag java.net.URL, :added "1.2"} as-url [x] "Coerce argument to a URL.")) (extend-protocol Coercions nil (as-file [_] nil) (as-url [_] nil) String (as-file [s] (File. s)) (as-url [s] (URL. s)) File (as-file [f] f) (as-url [f] (.toURL (.toURI f))) URL (as-url [u] u) (as-file [u] (if (= "file" (.getProtocol u)) (as-file (clojure.string/replace (.replace (.getFile u) \/ File/separatorChar) #"%.." (fn [escape] (-> escape (.substring 1 3) (Integer/parseInt 16) (char) (str))))) (throw (IllegalArgumentException. (str "Not a file: " u))))) URI (as-url [u] (.toURL u)) (as-file [u] (as-file (as-url u)))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :append true to open stream in append mode :encoding string name of encoding to use, e.g. \"UTF-8\". Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-reader [x opts] "Creates a BufferedReader. See also IOFactory docs.") (^{:added "1.2"} make-writer [x opts] "Creates a BufferedWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a BufferedInputStream. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a BufferedOutputStream. See also IOFactory docs.")) (defn ^Reader reader "Attempts to coerce its argument into an open java.io.Reader. Default implementations always return a java.io.BufferedReader. Default implementations are provided for Reader, BufferedReader, InputStream, File, URI, URL, Socket, byte arrays, character arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Reader is properly closed." {:added "1.2"} [x & opts] (make-reader x (when opts (apply hash-map opts)))) (defn ^Writer writer "Attempts to coerce its argument into an open java.io.Writer. Default implementations always return a java.io.BufferedWriter. Default implementations are provided for Writer, BufferedWriter, OutputStream, File, URI, URL, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Writer is properly closed." {:added "1.2"} [x & opts] (make-writer x (when opts (apply hash-map opts)))) (defn ^InputStream input-stream "Attempts to coerce its argument into an open java.io.InputStream. Default implementations always return a java.io.BufferedInputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the InputStream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^OutputStream output-stream "Attempts to coerce its argument into an open java.io.OutputStream. Default implementations always return a java.io.BufferedOutputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn- ^Boolean append? [opts] (boolean (:append opts))) (defn- ^String encoding [opts] (or (:encoding opts) "UTF-8")) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (def default-streams-impl {:make-reader (fn [x opts] (make-reader (make-input-stream x opts) opts)) :make-writer (fn [x opts] (make-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an InputStream.")))) :make-output-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an OutputStream."))))}) (defn- inputstream->reader [^InputStream is opts] (make-reader (InputStreamReader. is (encoding opts)) opts)) (defn- outputstream->writer [^OutputStream os opts] (make-writer (OutputStreamWriter. os (encoding opts)) opts)) (extend BufferedInputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] x) :make-reader inputstream->reader)) (extend InputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (BufferedInputStream. x)) :make-reader inputstream->reader)) (extend Reader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (BufferedReader. x)))) (extend BufferedReader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] x))) (extend Writer IOFactory (assoc default-streams-impl :make-writer (fn [x opts] (BufferedWriter. x)))) (extend BufferedWriter IOFactory (assoc default-streams-impl :make-writer (fn [x opts] x))) (extend OutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] (BufferedOutputStream. x)) :make-writer outputstream->writer)) (extend BufferedOutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] x) :make-writer outputstream->writer)) (extend File IOFactory (assoc default-streams-impl :make-input-stream (fn [^File x opts] (make-input-stream (FileInputStream. x) opts)) :make-output-stream (fn [^File x opts] (make-output-stream (FileOutputStream. x (append? opts)) opts)))) (extend URL IOFactory (assoc default-streams-impl :make-input-stream (fn [^URL x opts] (make-input-stream (if (= "file" (.getProtocol x)) (FileInputStream. (as-file x)) (.openStream x)) opts)) :make-output-stream (fn [^URL x opts] (if (= "file" (.getProtocol x)) (make-output-stream (as-file x) opts) (throw (IllegalArgumentException. (str "Can not write to non-file URL <" x ">"))))))) (extend URI IOFactory (assoc default-streams-impl :make-input-stream (fn [^URI x opts] (make-input-stream (.toURL x) opts)) :make-output-stream (fn [^URI x opts] (make-output-stream (.toURL x) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (URL. x) opts) (catch MalformedURLException e (make-input-stream (File. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (URL. x) opts) (catch MalformedURLException err (make-output-stream (File. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (make-input-stream (.getInputStream x) opts)) :make-output-stream (fn [^Socket x opts] (make-output-stream (.getOutputStream x) opts)))) (extend byte-array-type IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (make-input-stream (ByteArrayInputStream. x) opts)))) (extend char-array-type IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (make-reader (CharArrayReader. x) opts)))) (extend Object IOFactory default-streams-impl) (defmulti #^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [InputStream OutputStream] [#^InputStream input #^OutputStream output opts] (let [buffer (make-array Byte/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream Writer] [#^InputStream input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) in (InputStreamReader. input (encoding opts))] (loop [] (let [size (.read in buffer 0 (alength buffer))] (if (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream File] [#^InputStream input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [Reader OutputStream] [#^Reader input #^OutputStream output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) out (OutputStreamWriter. output (encoding opts))] (loop [] (let [size (.read input buffer)] (if (pos? size) (do (.write out buffer 0 size) (recur)) (.flush out)))))) (defmethod do-copy [Reader Writer] [#^Reader input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [Reader File] [#^Reader input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [File OutputStream] [#^File input #^OutputStream output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File Writer] [#^File input #^Writer output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File File] [#^File input #^File output opts] (with-open [in (FileInputStream. input) out (FileOutputStream. output)] (do-copy in out opts))) (defmethod do-copy [String OutputStream] [#^String input #^OutputStream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String Writer] [#^String input #^Writer output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String File] [#^String input #^File output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [char-array-type OutputStream] [input #^OutputStream output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type Writer] [input #^Writer output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type File] [input #^File output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [byte-array-type OutputStream] [#^"[B" input #^OutputStream output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type Writer] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type File] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts)))) (defn ^String as-relative-path "Take an as-file-able thing and return a string if it is a relative path, else IllegalArgumentException." {:added "1.2"} [x] (let [^File f (as-file x)] (if (.isAbsolute f) (throw (IllegalArgumentException. (str f " is not a relative path"))) (.getPath f)))) (defn ^File file "Returns a java.io.File, passing each arg to as-file. Multiple-arg versions treat the first argument as parent and subsequent args as children relative to the parent." {:added "1.2"} ([arg] (as-file arg)) ([parent child] (File. ^File (as-file parent) ^String (as-relative-path child))) ([parent child & more] (reduce file (file parent child) more))) (defn delete-file "Delete file f. Raise an exception if it fails unless silently is true." {:added "1.2"} [f & [silently]] (or (.delete (file f)) silently (throw (java.io.IOException. (str "Couldn't delete " f))))) (defn make-parents "Given the same arg(s) as for file, creates all parent directories of the file they represent." {:added "1.2"} [f & more] (when-let [parent (.getParentFile ^File (apply file f more))] (.mkdirs parent))) (defn ^URL resource "Returns the URL for a named resource. Use the context class loader if no loader is specified." {:added "1.2"} ([n] (resource n (.getContextClassLoader (Thread/currentThread)))) ([n ^ClassLoader loader] (.getResource loader n)))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:author "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :doc "This file defines polymorphic I/O utility functions for Clojure."} clojure.java.io (:require clojure.string) (:import (java.io Reader InputStream InputStreamReader PushbackReader BufferedReader File OutputStream OutputStreamWriter BufferedWriter Writer FileInputStream FileOutputStream ByteArrayOutputStream StringReader ByteArrayInputStream BufferedInputStream BufferedOutputStream CharArrayReader Closeable) (java.net URI URL MalformedURLException Socket))) (def ^{:doc "Type object for a Java primitive byte array." :private true } byte-array-type (class (make-array Byte/TYPE 0))) (def ^{:doc "Type object for a Java primitive char array." :private true} char-array-type (class (make-array Character/TYPE 0))) (defprotocol ^{:added "1.2"} Coercions "Coerce between various 'resource-namish' things." (^{:tag java.io.File, :added "1.2"} as-file [x] "Coerce argument to a file.") (^{:tag java.net.URL, :added "1.2"} as-url [x] "Coerce argument to a URL.")) (extend-protocol Coercions nil (as-file [_] nil) (as-url [_] nil) String (as-file [s] (File. s)) (as-url [s] (URL. s)) File (as-file [f] f) (as-url [f] (.toURL (.toURI f))) URL (as-url [u] u) (as-file [u] (if (= "file" (.getProtocol u)) (as-file (clojure.string/replace (.replace (.getFile u) \/ File/separatorChar) #"%.." (fn [escape] (-> escape (.substring 1 3) (Integer/parseInt 16) (char) (str))))) (throw (IllegalArgumentException. (str "Not a file: " u))))) URI (as-url [u] (.toURL u)) (as-file [u] (as-file (as-url u)))) (defprotocol ^{:added "1.2"} IOFactory "Factory functions that create ready-to-use, buffered versions of the various Java I/O stream types, on top of anything that can be unequivocally converted to the requested kind of stream. Common options include :append true to open stream in append mode :encoding string name of encoding to use, e.g. \"UTF-8\". Callers should generally prefer the higher level API provided by reader, writer, input-stream, and output-stream." (^{:added "1.2"} make-reader [x opts] "Creates a BufferedReader. See also IOFactory docs.") (^{:added "1.2"} make-writer [x opts] "Creates a BufferedWriter. See also IOFactory docs.") (^{:added "1.2"} make-input-stream [x opts] "Creates a BufferedInputStream. See also IOFactory docs.") (^{:added "1.2"} make-output-stream [x opts] "Creates a BufferedOutputStream. See also IOFactory docs.")) (defn ^Reader reader "Attempts to coerce its argument into an open java.io.Reader. Default implementations always return a java.io.BufferedReader. Default implementations are provided for Reader, BufferedReader, InputStream, File, URI, URL, Socket, byte arrays, character arrays, and String. If argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Reader is properly closed." {:added "1.2"} [x & opts] (make-reader x (when opts (apply hash-map opts)))) (defn ^Writer writer "Attempts to coerce its argument into an open java.io.Writer. Default implementations always return a java.io.BufferedWriter. Default implementations are provided for Writer, BufferedWriter, OutputStream, File, URI, URL, Socket, and String. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the Writer is properly closed." {:added "1.2"} [x & opts] (make-writer x (when opts (apply hash-map opts)))) (defn ^InputStream input-stream "Attempts to coerce its argument into an open java.io.InputStream. Default implementations always return a java.io.BufferedInputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, byte array, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the InputStream is properly closed." {:added "1.2"} [x & opts] (make-input-stream x (when opts (apply hash-map opts)))) (defn ^OutputStream output-stream "Attempts to coerce its argument into an open java.io.OutputStream. Default implementations always return a java.io.BufferedOutputStream. Default implementations are defined for OutputStream, File, URI, URL, Socket, and String arguments. If the argument is a String, it tries to resolve it first as a URI, then as a local file name. URIs with a 'file' protocol are converted to local file names. Should be used inside with-open to ensure the OutputStream is properly closed." {:added "1.2"} [x & opts] (make-output-stream x (when opts (apply hash-map opts)))) (defn- ^Boolean append? [opts] (boolean (:append opts))) (defn- ^String encoding [opts] (or (:encoding opts) "UTF-8")) (defn- buffer-size [opts] (or (:buffer-size opts) 1024)) (def default-streams-impl {:make-reader (fn [x opts] (make-reader (make-input-stream x opts) opts)) :make-writer (fn [x opts] (make-writer (make-output-stream x opts) opts)) :make-input-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an InputStream.")))) :make-output-stream (fn [x opts] (throw (IllegalArgumentException. (str "Cannot open <" (pr-str x) "> as an OutputStream."))))}) (defn- inputstream->reader [^InputStream is opts] (make-reader (InputStreamReader. is (encoding opts)) opts)) (defn- outputstream->writer [^OutputStream os opts] (make-writer (OutputStreamWriter. os (encoding opts)) opts)) (extend BufferedInputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] x) :make-reader inputstream->reader)) (extend InputStream IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (BufferedInputStream. x)) :make-reader inputstream->reader)) (extend Reader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (BufferedReader. x)))) (extend BufferedReader IOFactory (assoc default-streams-impl :make-reader (fn [x opts] x))) (extend Writer IOFactory (assoc default-streams-impl :make-writer (fn [x opts] (BufferedWriter. x)))) (extend BufferedWriter IOFactory (assoc default-streams-impl :make-writer (fn [x opts] x))) (extend OutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] (BufferedOutputStream. x)) :make-writer outputstream->writer)) (extend BufferedOutputStream IOFactory (assoc default-streams-impl :make-output-stream (fn [x opts] x) :make-writer outputstream->writer)) (extend File IOFactory (assoc default-streams-impl :make-input-stream (fn [^File x opts] (make-input-stream (FileInputStream. x) opts)) :make-output-stream (fn [^File x opts] (make-output-stream (FileOutputStream. x (append? opts)) opts)))) (extend URL IOFactory (assoc default-streams-impl :make-input-stream (fn [^URL x opts] (make-input-stream (if (= "file" (.getProtocol x)) (FileInputStream. (as-file x)) (.openStream x)) opts)) :make-output-stream (fn [^URL x opts] (if (= "file" (.getProtocol x)) (make-output-stream (as-file x) opts) (throw (IllegalArgumentException. (str "Can not write to non-file URL <" x ">"))))))) (extend URI IOFactory (assoc default-streams-impl :make-input-stream (fn [^URI x opts] (make-input-stream (.toURL x) opts)) :make-output-stream (fn [^URI x opts] (make-output-stream (.toURL x) opts)))) (extend String IOFactory (assoc default-streams-impl :make-input-stream (fn [^String x opts] (try (make-input-stream (URL. x) opts) (catch MalformedURLException e (make-input-stream (File. x) opts)))) :make-output-stream (fn [^String x opts] (try (make-output-stream (URL. x) opts) (catch MalformedURLException err (make-output-stream (File. x) opts)))))) (extend Socket IOFactory (assoc default-streams-impl :make-input-stream (fn [^Socket x opts] (make-input-stream (.getInputStream x) opts)) :make-output-stream (fn [^Socket x opts] (make-output-stream (.getOutputStream x) opts)))) (extend byte-array-type IOFactory (assoc default-streams-impl :make-input-stream (fn [x opts] (make-input-stream (ByteArrayInputStream. x) opts)))) (extend char-array-type IOFactory (assoc default-streams-impl :make-reader (fn [x opts] (make-reader (CharArrayReader. x) opts)))) (extend Object IOFactory default-streams-impl) (defmulti #^{:doc "Internal helper for copy" :private true :arglists '([input output opts])} do-copy (fn [input output opts] [(type input) (type output)])) (defmethod do-copy [InputStream OutputStream] [#^InputStream input #^OutputStream output opts] (let [buffer (make-array Byte/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream Writer] [#^InputStream input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) in (InputStreamReader. input (encoding opts))] (loop [] (let [size (.read in buffer 0 (alength buffer))] (if (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [InputStream File] [#^InputStream input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [Reader OutputStream] [#^Reader input #^OutputStream output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts)) out (OutputStreamWriter. output (encoding opts))] (loop [] (let [size (.read input buffer)] (if (pos? size) (do (.write out buffer 0 size) (recur)) (.flush out)))))) (defmethod do-copy [Reader Writer] [#^Reader input #^Writer output opts] (let [#^"[C" buffer (make-array Character/TYPE (buffer-size opts))] (loop [] (let [size (.read input buffer)] (when (pos? size) (do (.write output buffer 0 size) (recur))))))) (defmethod do-copy [Reader File] [#^Reader input #^File output opts] (with-open [out (FileOutputStream. output)] (do-copy input out opts))) (defmethod do-copy [File OutputStream] [#^File input #^OutputStream output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File Writer] [#^File input #^Writer output opts] (with-open [in (FileInputStream. input)] (do-copy in output opts))) (defmethod do-copy [File File] [#^File input #^File output opts] (with-open [in (FileInputStream. input) out (FileOutputStream. output)] (do-copy in out opts))) (defmethod do-copy [String OutputStream] [#^String input #^OutputStream output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String Writer] [#^String input #^Writer output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [String File] [#^String input #^File output opts] (do-copy (StringReader. input) output opts)) (defmethod do-copy [char-array-type OutputStream] [input #^OutputStream output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type Writer] [input #^Writer output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [char-array-type File] [input #^File output opts] (do-copy (CharArrayReader. input) output opts)) (defmethod do-copy [byte-array-type OutputStream] [#^"[B" input #^OutputStream output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type Writer] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defmethod do-copy [byte-array-type File] [#^"[B" input #^Writer output opts] (do-copy (ByteArrayInputStream. input) output opts)) (defn copy "Copies input to output. Returns nil or throws IOException. Input may be an InputStream, Reader, File, byte[], or String. Output may be an OutputStream, Writer, or File. Options are key/value pairs and may be one of :buffer-size buffer size to use, default is 1024. :encoding encoding to use if converting between byte and char streams. Does not close any streams except those it opens itself (on a File)." {:added "1.2"} [input output & opts] (do-copy input output (when opts (apply hash-map opts)))) (defn ^String as-relative-path "Take an as-file-able thing and return a string if it is a relative path, else IllegalArgumentException." {:added "1.2"} [x] (let [^File f (as-file x)] (if (.isAbsolute f) (throw (IllegalArgumentException. (str f " is not a relative path"))) (.getPath f)))) (defn ^File file "Returns a java.io.File, passing each arg to as-file. Multiple-arg versions treat the first argument as parent and subsequent args as children relative to the parent." {:added "1.2"} ([arg] (as-file arg)) ([parent child] (File. ^File (as-file parent) ^String (as-relative-path child))) ([parent child & more] (reduce file (file parent child) more))) (defn delete-file "Delete file f. Raise an exception if it fails unless silently is true." {:added "1.2"} [f & [silently]] (or (.delete (file f)) silently (throw (java.io.IOException. (str "Couldn't delete " f))))) (defn make-parents "Given the same arg(s) as for file, creates all parent directories of the file they represent." {:added "1.2"} [f & more] (when-let [parent (.getParentFile ^File (apply file f more))] (.mkdirs parent))) (defn ^URL resource "Returns the URL for a named resource. Use the context class loader if no loader is specified." {:added "1.2"} ([n] (resource n (.getContextClassLoader (Thread/currentThread)))) ([n ^ClassLoader loader] (.getResource loader n)))
[ { "context": " :subprotocol \"oracle\"\n :subname \"thin:@bdoradev4.in.asso-cocktail.org:5221:btagfc01\" ; If that does not work try: th", "end": 271, "score": 0.977694571018219, "start": 241, "tag": "EMAIL", "value": "bdoradev4.in.asso-cocktail.org" }, { "context": "1:btagfc01\" ; If that does not work try: thin:@172.27.1.7:1521/SID\n :user \"GRHUM\"\n :passwor", "end": 335, "score": 0.9997310638427734, "start": 325, "tag": "IP_ADDRESS", "value": "172.27.1.7" }, { "context": "21/SID\n :user \"GRHUM\"\n :password \"pwd\"})\n\n\n(defn membreDeStructure [subj struct]\n (let", "end": 391, "score": 0.9995633363723755, "start": 388, "tag": "PASSWORD", "value": "pwd" } ]
src/hyauth/grhum.clj
rsclison/hyauth
0
(ns hyauth.grhum (:require [clojure.java.jdbc :as jdbc] [hyauth.personne :as pers] ) ) (def db {:classname "oracle.jdbc.OracleDriver" ; must be in classpath :subprotocol "oracle" :subname "thin:@bdoradev4.in.asso-cocktail.org:5221:btagfc01" ; If that does not work try: thin:@172.27.1.7:1521/SID :user "GRHUM" :password "pwd"}) (defn membreDeStructure [subj struct] (let [res (jdbc/query db [(str "SELECT * FROM STRUCTURE_ULR,REPART_STRUCTURE WHERE STRUCTURE_ULR.LL_STRUCTURE=" struct " AND REPART_STRUCTURE.PERS_ID=" subj " AND REPORT_STRUCTURE.c_structure=STRUCTURE_ULR.C_STRUCTURE")]) ] ) ) (defrecord GrhumPersonneRepository [dbconn] pers/PersonneRepository (getById [id] (let [res (jdbc/query db [(str "SELECT * FROM INDIVIDU_ULR WHERE PERS_ID='" id "'")])]) ) )
93978
(ns hyauth.grhum (:require [clojure.java.jdbc :as jdbc] [hyauth.personne :as pers] ) ) (def db {:classname "oracle.jdbc.OracleDriver" ; must be in classpath :subprotocol "oracle" :subname "thin:@<EMAIL>:5221:btagfc01" ; If that does not work try: thin:@172.27.1.7:1521/SID :user "GRHUM" :password "<PASSWORD>"}) (defn membreDeStructure [subj struct] (let [res (jdbc/query db [(str "SELECT * FROM STRUCTURE_ULR,REPART_STRUCTURE WHERE STRUCTURE_ULR.LL_STRUCTURE=" struct " AND REPART_STRUCTURE.PERS_ID=" subj " AND REPORT_STRUCTURE.c_structure=STRUCTURE_ULR.C_STRUCTURE")]) ] ) ) (defrecord GrhumPersonneRepository [dbconn] pers/PersonneRepository (getById [id] (let [res (jdbc/query db [(str "SELECT * FROM INDIVIDU_ULR WHERE PERS_ID='" id "'")])]) ) )
true
(ns hyauth.grhum (:require [clojure.java.jdbc :as jdbc] [hyauth.personne :as pers] ) ) (def db {:classname "oracle.jdbc.OracleDriver" ; must be in classpath :subprotocol "oracle" :subname "thin:@PI:EMAIL:<EMAIL>END_PI:5221:btagfc01" ; If that does not work try: thin:@172.27.1.7:1521/SID :user "GRHUM" :password "PI:PASSWORD:<PASSWORD>END_PI"}) (defn membreDeStructure [subj struct] (let [res (jdbc/query db [(str "SELECT * FROM STRUCTURE_ULR,REPART_STRUCTURE WHERE STRUCTURE_ULR.LL_STRUCTURE=" struct " AND REPART_STRUCTURE.PERS_ID=" subj " AND REPORT_STRUCTURE.c_structure=STRUCTURE_ULR.C_STRUCTURE")]) ] ) ) (defrecord GrhumPersonneRepository [dbconn] pers/PersonneRepository (getById [id] (let [res (jdbc/query db [(str "SELECT * FROM INDIVIDU_ULR WHERE PERS_ID='" id "'")])]) ) )
[ { "context": " :firstname \"Fred\"\n :surna", "end": 1065, "score": 0.9997397065162659, "start": 1061, "tag": "NAME", "value": "Fred" }, { "context": " :surname \"Smith\"}]])\n (with-open [db (c/open-db node)]\n (", "end": 1124, "score": 0.9994906187057495, "start": 1119, "tag": "NAME", "value": "Smith" }, { "context": "lucene-text-search \"firstname:%s AND surname:%s\" \"Fred\" \"Smith\" {:lucene-store-k :multi}) [[?e]]]]})))))", "end": 1395, "score": 0.99974524974823, "start": 1391, "tag": "NAME", "value": "Fred" }, { "context": "text-search \"firstname:%s AND surname:%s\" \"Fred\" \"Smith\" {:lucene-store-k :multi}) [[?e]]]]}))))))\n", "end": 1403, "score": 0.9995204210281372, "start": 1398, "tag": "NAME", "value": "Smith" } ]
crux-lucene/test/crux/lucene/extension_test.clj
remyrd/crux
0
(ns crux.lucene.extension-test (:require [clojure.test :as t] [clojure.spec.alpha :as s] [crux.api :as c] [crux.checkpoint :as cp] [crux.db :as db] [crux.fixtures :as fix :refer [*api* submit+await-tx]] [crux.fixtures.lucene :as lf] [crux.lucene :as l])) (require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols (t/deftest test-multiple-lucene-stores (with-open [node (c/start-node {:ave {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene/->indexer} :multi {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene.multi-field/->indexer}})] (submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :firstname "Fred" :surname "Smith"}]]) (with-open [db (c/open-db node)] (t/is (seq (c/q db '{:find [?e] :where [[(text-search :firstname "Fre*" {:lucene-store-k :ave}) [[?e]]] [(lucene-text-search "firstname:%s AND surname:%s" "Fred" "Smith" {:lucene-store-k :multi}) [[?e]]]]}))))))
70378
(ns crux.lucene.extension-test (:require [clojure.test :as t] [clojure.spec.alpha :as s] [crux.api :as c] [crux.checkpoint :as cp] [crux.db :as db] [crux.fixtures :as fix :refer [*api* submit+await-tx]] [crux.fixtures.lucene :as lf] [crux.lucene :as l])) (require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols (t/deftest test-multiple-lucene-stores (with-open [node (c/start-node {:ave {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene/->indexer} :multi {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene.multi-field/->indexer}})] (submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :firstname "<NAME>" :surname "<NAME>"}]]) (with-open [db (c/open-db node)] (t/is (seq (c/q db '{:find [?e] :where [[(text-search :firstname "Fre*" {:lucene-store-k :ave}) [[?e]]] [(lucene-text-search "firstname:%s AND surname:%s" "<NAME>" "<NAME>" {:lucene-store-k :multi}) [[?e]]]]}))))))
true
(ns crux.lucene.extension-test (:require [clojure.test :as t] [clojure.spec.alpha :as s] [crux.api :as c] [crux.checkpoint :as cp] [crux.db :as db] [crux.fixtures :as fix :refer [*api* submit+await-tx]] [crux.fixtures.lucene :as lf] [crux.lucene :as l])) (require 'crux.lucene.multi-field :reload) ; for dev, due to changing protocols (t/deftest test-multiple-lucene-stores (with-open [node (c/start-node {:ave {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene/->indexer} :multi {:crux/module 'crux.lucene/->lucene-store :analyzer 'crux.lucene/->analyzer :indexer 'crux.lucene.multi-field/->indexer}})] (submit+await-tx node [[:crux.tx/put {:crux.db/id :ivan :firstname "PI:NAME:<NAME>END_PI" :surname "PI:NAME:<NAME>END_PI"}]]) (with-open [db (c/open-db node)] (t/is (seq (c/q db '{:find [?e] :where [[(text-search :firstname "Fre*" {:lucene-store-k :ave}) [[?e]]] [(lucene-text-search "firstname:%s AND surname:%s" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" {:lucene-store-k :multi}) [[?e]]]]}))))))
[ { "context": " {:id \"1\"\n :pass \"pass\"})))\n (is (= {:id \"1\"\n :las", "end": 710, "score": 0.9990968704223633, "start": 706, "tag": "PASSWORD", "value": "pass" }, { "context": " :is_active nil\n :pass \"pass\"}\n (db/get-org t-conn {:id \"1\"})))\n ", "end": 854, "score": 0.9994386434555054, "start": 850, "tag": "PASSWORD", "value": "pass" }, { "context": " :name \"test\"\n :fcc_username \"test\"})))\n (is (= [{:name \"test\"\n :fcc_", "end": 1279, "score": 0.9984514713287354, "start": 1275, "tag": "USERNAME", "value": "test" }, { "context": "(is (= [{:name \"test\"\n :fcc_username \"test\"}]\n (db/list-members\n t-conn", "end": 1343, "score": 0.9945769309997559, "start": 1339, "tag": "USERNAME", "value": "test" }, { "context": " {:organization \"1\"\n :fcc_username \"test\"})))\n (is (= [] (db/list-members\n ", "end": 1549, "score": 0.9960854053497314, "start": 1545, "tag": "USERNAME", "value": "test" } ]
test/clj/fcc_tracker/test/db/core.clj
achernyak/fcc-tracker
2
(ns fcc-tracker.test.db.core (:require [fcc-tracker.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [fcc-tracker.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'fcc-tracker.config/env #'fcc-tracker.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-org! t-conn {:id "1" :pass "pass"}))) (is (= {:id "1" :last_login nil :org_name nil :is_active nil :pass "pass"} (db/get-org t-conn {:id "1"}))) (is (= 1 (db/delete-org! t-conn {:id "1"}))) (is (= nil (db/get-org t-conn {:id "1"}))))) (deftest test-members (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-member! t-conn {:organization "1" :name "test" :fcc_username "test"}))) (is (= [{:name "test" :fcc_username "test"}] (db/list-members t-conn {:organization "1"}))) (is (= 1 (db/delete-member! t-conn {:organization "1" :fcc_username "test"}))) (is (= [] (db/list-members t-conn {:organization "1"})))))
2793
(ns fcc-tracker.test.db.core (:require [fcc-tracker.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [fcc-tracker.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'fcc-tracker.config/env #'fcc-tracker.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-org! t-conn {:id "1" :pass "<PASSWORD>"}))) (is (= {:id "1" :last_login nil :org_name nil :is_active nil :pass "<PASSWORD>"} (db/get-org t-conn {:id "1"}))) (is (= 1 (db/delete-org! t-conn {:id "1"}))) (is (= nil (db/get-org t-conn {:id "1"}))))) (deftest test-members (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-member! t-conn {:organization "1" :name "test" :fcc_username "test"}))) (is (= [{:name "test" :fcc_username "test"}] (db/list-members t-conn {:organization "1"}))) (is (= 1 (db/delete-member! t-conn {:organization "1" :fcc_username "test"}))) (is (= [] (db/list-members t-conn {:organization "1"})))))
true
(ns fcc-tracker.test.db.core (:require [fcc-tracker.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [fcc-tracker.config :refer [env]] [mount.core :as mount])) (use-fixtures :once (fn [f] (mount/start #'fcc-tracker.config/env #'fcc-tracker.db.core/*db*) (migrations/migrate ["migrate"] (select-keys env [:database-url])) (f))) (deftest test-users (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-org! t-conn {:id "1" :pass "PI:PASSWORD:<PASSWORD>END_PI"}))) (is (= {:id "1" :last_login nil :org_name nil :is_active nil :pass "PI:PASSWORD:<PASSWORD>END_PI"} (db/get-org t-conn {:id "1"}))) (is (= 1 (db/delete-org! t-conn {:id "1"}))) (is (= nil (db/get-org t-conn {:id "1"}))))) (deftest test-members (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (is (= 1 (db/create-member! t-conn {:organization "1" :name "test" :fcc_username "test"}))) (is (= [{:name "test" :fcc_username "test"}] (db/list-members t-conn {:organization "1"}))) (is (= 1 (db/delete-member! t-conn {:organization "1" :fcc_username "test"}))) (is (= [] (db/list-members t-conn {:organization "1"})))))
[ { "context": "on \"A Clojure library wrapping https://github.com/Unleash/unleash-client-java\"\n :url \"https://github.com/A", "end": 112, "score": 0.9635221362113953, "start": 105, "tag": "USERNAME", "value": "Unleash" }, { "context": "h/unleash-client-java\"\n :url \"https://github.com/AppsFlyer/unleash-client-clojure\"\n :license {:name \"EPL-2.", "end": 170, "score": 0.9308448433876038, "start": 161, "tag": "USERNAME", "value": "AppsFlyer" }, { "context": "\n :password :env/clojars_password\n :sign-relea", "end": 809, "score": 0.988858699798584, "start": 789, "tag": "PASSWORD", "value": "env/clojars_password" } ]
project.clj
vincentjames501/unleash-client-clojure
7
(defproject unleash-client-clojure "0.4.0" :description "A Clojure library wrapping https://github.com/Unleash/unleash-client-java" :url "https://github.com/AppsFlyer/unleash-client-clojure" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "https://www.eclipse.org/legal/epl-2.0/"} :deploy-repositories [["releases" {:url "https://repo.clojars.org" :username :env/clojars_username :password :env/clojars_password :sign-releases false}] ["snapshots" {:url "https://repo.clojars.org" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]] :dependencies [[no.finn.unleash/unleash-client-java "4.4.1"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [clj-kondo "RELEASE"] [org.apache.logging.log4j/log4j-core "2.17.0"] [org.apache.logging.log4j/log4j-api "2.17.0"] [org.slf4j/slf4j-log4j12 "1.7.32"]] :aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"] "lint" ["run" "-m" "clj-kondo.main" "--lint" "src" "test"]} :plugins [[lein-ancient "1.0.0-RC3"] [lein-cloverage "1.2.2"] [lein-eftest "0.5.9"]] :global-vars {*warn-on-reflection* true}}})
124735
(defproject unleash-client-clojure "0.4.0" :description "A Clojure library wrapping https://github.com/Unleash/unleash-client-java" :url "https://github.com/AppsFlyer/unleash-client-clojure" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "https://www.eclipse.org/legal/epl-2.0/"} :deploy-repositories [["releases" {:url "https://repo.clojars.org" :username :env/clojars_username :password :env/clojars_password :sign-releases false}] ["snapshots" {:url "https://repo.clojars.org" :username :env/clojars_username :password :<PASSWORD> :sign-releases false}]] :dependencies [[no.finn.unleash/unleash-client-java "4.4.1"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [clj-kondo "RELEASE"] [org.apache.logging.log4j/log4j-core "2.17.0"] [org.apache.logging.log4j/log4j-api "2.17.0"] [org.slf4j/slf4j-log4j12 "1.7.32"]] :aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"] "lint" ["run" "-m" "clj-kondo.main" "--lint" "src" "test"]} :plugins [[lein-ancient "1.0.0-RC3"] [lein-cloverage "1.2.2"] [lein-eftest "0.5.9"]] :global-vars {*warn-on-reflection* true}}})
true
(defproject unleash-client-clojure "0.4.0" :description "A Clojure library wrapping https://github.com/Unleash/unleash-client-java" :url "https://github.com/AppsFlyer/unleash-client-clojure" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "https://www.eclipse.org/legal/epl-2.0/"} :deploy-repositories [["releases" {:url "https://repo.clojars.org" :username :env/clojars_username :password :env/clojars_password :sign-releases false}] ["snapshots" {:url "https://repo.clojars.org" :username :env/clojars_username :password :PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]] :dependencies [[no.finn.unleash/unleash-client-java "4.4.1"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.3"] [clj-kondo "RELEASE"] [org.apache.logging.log4j/log4j-core "2.17.0"] [org.apache.logging.log4j/log4j-api "2.17.0"] [org.slf4j/slf4j-log4j12 "1.7.32"]] :aliases {"clj-kondo" ["run" "-m" "clj-kondo.main"] "lint" ["run" "-m" "clj-kondo.main" "--lint" "src" "test"]} :plugins [[lein-ancient "1.0.0-RC3"] [lein-cloverage "1.2.2"] [lein-eftest "0.5.9"]] :global-vars {*warn-on-reflection* true}}})
[ { "context": "(ns repliclj.log\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Switch log on ", "end": 41, "score": 0.9998728036880493, "start": 30, "tag": "NAME", "value": "Thomas Bock" }, { "context": "(ns repliclj.log\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Switch log on and off. Uses [µlog](", "end": 62, "score": 0.9999318718910217, "start": 43, "tag": "EMAIL", "value": "wactbprot@gmail.com" }, { "context": "ch log on and off. Uses [µlog](https://github.com/BrunoBonacci/mulog). \n Writes direct to elastic sea", "end": 143, "score": 0.9866212606430054, "start": 131, "tag": "USERNAME", "value": "BrunoBonacci" } ]
src/repliclj/log.clj
wactbprot/repliclj
0
(ns repliclj.log ^{:author "Thomas Bock <wactbprot@gmail.com>" :doc "Switch log on and off. Uses [µlog](https://github.com/BrunoBonacci/mulog). Writes direct to elastic search."} (:require [repliclj.conf :as conf] [com.brunobonacci.mulog :as µ])) (defonce logger (atom nil)) (defn stop ([] (stop conf/conf)) ([c] (µ/log ::stop) (@logger) (reset! logger nil))) (defn start ([] (start conf/conf)) ([{mulog :mulog log-context :log-context app-name :app-name}] (µ/set-global-context! (assoc log-context :app-name app-name)) (reset! logger (µ/start-publisher! mulog))))
27
(ns repliclj.log ^{:author "<NAME> <<EMAIL>>" :doc "Switch log on and off. Uses [µlog](https://github.com/BrunoBonacci/mulog). Writes direct to elastic search."} (:require [repliclj.conf :as conf] [com.brunobonacci.mulog :as µ])) (defonce logger (atom nil)) (defn stop ([] (stop conf/conf)) ([c] (µ/log ::stop) (@logger) (reset! logger nil))) (defn start ([] (start conf/conf)) ([{mulog :mulog log-context :log-context app-name :app-name}] (µ/set-global-context! (assoc log-context :app-name app-name)) (reset! logger (µ/start-publisher! mulog))))
true
(ns repliclj.log ^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" :doc "Switch log on and off. Uses [µlog](https://github.com/BrunoBonacci/mulog). Writes direct to elastic search."} (:require [repliclj.conf :as conf] [com.brunobonacci.mulog :as µ])) (defonce logger (atom nil)) (defn stop ([] (stop conf/conf)) ([c] (µ/log ::stop) (@logger) (reset! logger nil))) (defn start ([] (start conf/conf)) ([{mulog :mulog log-context :log-context app-name :app-name}] (µ/set-global-context! (assoc log-context :app-name app-name)) (reset! logger (µ/start-publisher! mulog))))
[ { "context": "> 418))))\n\n(let [api-users {\"api-key\" {:username \"api-key\"\n :password (creds/has", "end": 2485, "score": 0.9915396571159363, "start": 2478, "tag": "USERNAME", "value": "api-key" }, { "context": " :password (creds/hash-bcrypt \"api-pass\")\n :roles #{:api}}\n ", "end": 2553, "score": 0.9941710829734802, "start": 2545, "tag": "PASSWORD", "value": "api-pass" }, { "context": "les #{:api}}\n \"admin\" {:username \"admin\"\n :password (creds/hash-", "end": 2642, "score": 0.9679187536239624, "start": 2637, "tag": "USERNAME", "value": "admin" }, { "context": " :password (creds/hash-bcrypt \"admin-pass\")\n :roles #{:admin}}}\n ", "end": 2710, "score": 0.9991999268531799, "start": 2700, "tag": "PASSWORD", "value": "admin-pass" } ]
test/ring/middleware/ratelimit_test.clj
DeLaGuardo/ring-ratelimit
1
(ns ring.middleware.ratelimit-test (:import [java.util Date]) (:require [clojure.string :as string] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds] [openid :as openid]) [ring.middleware.ratelimit :as ratelimit] (ring.middleware.ratelimit [util :as util] [backend :as backend] [local-atom :as local-atom] [redis :as redis] [limits :as limits]) [ring.mock.request :as request] [midje.sweet :as midje])) (defn rsp-limit [rsp] (get-in rsp [:headers "X-RateLimit-Limit"])) (defn remaining [rsp] (get-in rsp [:headers "X-RateLimit-Remaining"])) (doseq [backend [(local-atom/local-atom-backend) (redis/redis-backend)]] (let [app (-> (fn [req] {:status 418 :headers {"Content-Type" "air/plane"} :body "Hello"}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/ip-limit 5)] :backend backend}))] (midje/facts (str "ratelimit <" (last (string/split (str (type backend)) #"\.")) ">") (backend/reset-limits! backend (util/current-hour)) (midje/fact "shows the rate limit" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 418 (rsp-limit rsp) => "5" (remaining rsp) => "4")) (midje/fact "returns 429 when there are no requests left" (dotimes [_ 5] (-> (request/request :get "/") app)) (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 429 (remaining rsp) => "0")) (midje/fact "resets the limit every hour" (with-redefs [util/current-hour (fn [] (- (.getHours (Date.)) 1))] (dotimes [_ 5] (-> (request/request :get "/") app)) (-> (request/request :get "/") app :status) => 429) (-> (request/request :get "/") app :status) => 418)))) (let [api-users {"api-key" {:username "api-key" :password (creds/hash-bcrypt "api-pass") :roles #{:api}} "admin" {:username "admin" :password (creds/hash-bcrypt "admin-pass") :roles #{:admin}}} app (-> (fn [req] {:status 200 :headers {"Content-Type" "text/plain"} :body (with-out-str (pr req))}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/role-limit :admin 20) (-> 10 limits/limit limits/wrap-limit-user limits/wrap-limit-ip) (ratelimit/ip-limit 5)] :backend (local-atom/local-atom-backend)}) (friend/authenticate {:allow-anon? true :workflows [(workflows/http-basic :credential-fn (partial creds/bcrypt-credential-fn api-users) :realm "test-realm")]}))] (midje/facts "ratelimit with 3 limiters" (midje/fact "uses the admin limit for admins" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YWRtaW46YWRtaW4tcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "19")) (midje/fact "uses the user limit for authenticated requests" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "9")) (midje/fact "uses the composed limit for user-ip" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-one") app)] (remaining rsp) => "9") (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-two") app)] (remaining rsp) => "9")) (midje/fact "uses the ip limit for unauthenticated requests" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 200 (remaining rsp) => "3"))))
61913
(ns ring.middleware.ratelimit-test (:import [java.util Date]) (:require [clojure.string :as string] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds] [openid :as openid]) [ring.middleware.ratelimit :as ratelimit] (ring.middleware.ratelimit [util :as util] [backend :as backend] [local-atom :as local-atom] [redis :as redis] [limits :as limits]) [ring.mock.request :as request] [midje.sweet :as midje])) (defn rsp-limit [rsp] (get-in rsp [:headers "X-RateLimit-Limit"])) (defn remaining [rsp] (get-in rsp [:headers "X-RateLimit-Remaining"])) (doseq [backend [(local-atom/local-atom-backend) (redis/redis-backend)]] (let [app (-> (fn [req] {:status 418 :headers {"Content-Type" "air/plane"} :body "Hello"}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/ip-limit 5)] :backend backend}))] (midje/facts (str "ratelimit <" (last (string/split (str (type backend)) #"\.")) ">") (backend/reset-limits! backend (util/current-hour)) (midje/fact "shows the rate limit" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 418 (rsp-limit rsp) => "5" (remaining rsp) => "4")) (midje/fact "returns 429 when there are no requests left" (dotimes [_ 5] (-> (request/request :get "/") app)) (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 429 (remaining rsp) => "0")) (midje/fact "resets the limit every hour" (with-redefs [util/current-hour (fn [] (- (.getHours (Date.)) 1))] (dotimes [_ 5] (-> (request/request :get "/") app)) (-> (request/request :get "/") app :status) => 429) (-> (request/request :get "/") app :status) => 418)))) (let [api-users {"api-key" {:username "api-key" :password (creds/hash-bcrypt "<PASSWORD>") :roles #{:api}} "admin" {:username "admin" :password (creds/hash-bcrypt "<PASSWORD>") :roles #{:admin}}} app (-> (fn [req] {:status 200 :headers {"Content-Type" "text/plain"} :body (with-out-str (pr req))}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/role-limit :admin 20) (-> 10 limits/limit limits/wrap-limit-user limits/wrap-limit-ip) (ratelimit/ip-limit 5)] :backend (local-atom/local-atom-backend)}) (friend/authenticate {:allow-anon? true :workflows [(workflows/http-basic :credential-fn (partial creds/bcrypt-credential-fn api-users) :realm "test-realm")]}))] (midje/facts "ratelimit with 3 limiters" (midje/fact "uses the admin limit for admins" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YWRtaW46YWRtaW4tcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "19")) (midje/fact "uses the user limit for authenticated requests" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "9")) (midje/fact "uses the composed limit for user-ip" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-one") app)] (remaining rsp) => "9") (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-two") app)] (remaining rsp) => "9")) (midje/fact "uses the ip limit for unauthenticated requests" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 200 (remaining rsp) => "3"))))
true
(ns ring.middleware.ratelimit-test (:import [java.util Date]) (:require [clojure.string :as string] [cemerick.friend :as friend] (cemerick.friend [workflows :as workflows] [credentials :as creds] [openid :as openid]) [ring.middleware.ratelimit :as ratelimit] (ring.middleware.ratelimit [util :as util] [backend :as backend] [local-atom :as local-atom] [redis :as redis] [limits :as limits]) [ring.mock.request :as request] [midje.sweet :as midje])) (defn rsp-limit [rsp] (get-in rsp [:headers "X-RateLimit-Limit"])) (defn remaining [rsp] (get-in rsp [:headers "X-RateLimit-Remaining"])) (doseq [backend [(local-atom/local-atom-backend) (redis/redis-backend)]] (let [app (-> (fn [req] {:status 418 :headers {"Content-Type" "air/plane"} :body "Hello"}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/ip-limit 5)] :backend backend}))] (midje/facts (str "ratelimit <" (last (string/split (str (type backend)) #"\.")) ">") (backend/reset-limits! backend (util/current-hour)) (midje/fact "shows the rate limit" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 418 (rsp-limit rsp) => "5" (remaining rsp) => "4")) (midje/fact "returns 429 when there are no requests left" (dotimes [_ 5] (-> (request/request :get "/") app)) (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 429 (remaining rsp) => "0")) (midje/fact "resets the limit every hour" (with-redefs [util/current-hour (fn [] (- (.getHours (Date.)) 1))] (dotimes [_ 5] (-> (request/request :get "/") app)) (-> (request/request :get "/") app :status) => 429) (-> (request/request :get "/") app :status) => 418)))) (let [api-users {"api-key" {:username "api-key" :password (creds/hash-bcrypt "PI:PASSWORD:<PASSWORD>END_PI") :roles #{:api}} "admin" {:username "admin" :password (creds/hash-bcrypt "PI:PASSWORD:<PASSWORD>END_PI") :roles #{:admin}}} app (-> (fn [req] {:status 200 :headers {"Content-Type" "text/plain"} :body (with-out-str (pr req))}) (ratelimit/wrap-ratelimit {:limits [(ratelimit/role-limit :admin 20) (-> 10 limits/limit limits/wrap-limit-user limits/wrap-limit-ip) (ratelimit/ip-limit 5)] :backend (local-atom/local-atom-backend)}) (friend/authenticate {:allow-anon? true :workflows [(workflows/http-basic :credential-fn (partial creds/bcrypt-credential-fn api-users) :realm "test-realm")]}))] (midje/facts "ratelimit with 3 limiters" (midje/fact "uses the admin limit for admins" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YWRtaW46YWRtaW4tcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "19")) (midje/fact "uses the user limit for authenticated requests" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") app)] (:status rsp) => 200 (remaining rsp) => "9")) (midje/fact "uses the composed limit for user-ip" (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-one") app)] (remaining rsp) => "9") (let [rsp (-> (request/request :get "/") (request/header "Authorization" "Basic YXBpLWtleTphcGktcGFzcw==") (assoc :remote-addr "host-two") app)] (remaining rsp) => "9")) (midje/fact "uses the ip limit for unauthenticated requests" (let [rsp (-> (request/request :get "/") app)] (:status rsp) => 200 (remaining rsp) => "3"))))
[ { "context": "ipt web audio wrapper\"\n :url \"https://github.com/minasmart/squelch\"\n :license {:name \"MIT\"\n :url", "end": 133, "score": 0.9996857047080994, "start": 124, "tag": "USERNAME", "value": "minasmart" }, { "context": "scm {:name \"git\"\n :url \"https://github.com/minaminamina/squelch\"}\n\n :signing {:gpg-key \"F6DC191D7745EF83", "end": 1002, "score": 0.9985694289207458, "start": 990, "tag": "USERNAME", "value": "minaminamina" }, { "context": "com/minaminamina/squelch\"}\n\n :signing {:gpg-key \"F6DC191D7745EF83\"}\n :deploy-repositories [[\"clojars\" {:creds :gpg", "end": 1052, "score": 0.9990325570106506, "start": 1036, "tag": "KEY", "value": "F6DC191D7745EF83" }, { "context": "[:developer\n [:name \"Mina Smart\"]\n [:url \"http://git", "end": 1196, "score": 0.9903462529182434, "start": 1186, "tag": "NAME", "value": "Mina Smart" }, { "context": " [:url \"http://github.com/minasmart\"]\n [:email \"m.d.smar", "end": 1263, "score": 0.9996821880340576, "start": 1254, "tag": "USERNAME", "value": "minasmart" }, { "context": "inasmart\"]\n [:email \"m.d.smart@gmail.com\"]\n [:timezone \"-5\"]]", "end": 1324, "score": 0.9999298453330994, "start": 1305, "tag": "EMAIL", "value": "m.d.smart@gmail.com" } ]
project.clj
minasmart/squelch
3
(defproject squelch "0.1.3-SNAPSHOT" :description "Squelch: A clojurescript web audio wrapper" :url "https://github.com/minasmart/squelch" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/clojurescript "0.0-2371"] [com.cemerick/piggieback "0.1.3"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-cljsbuild "1.0.6-SNAPSHOT"] [codox "0.8.10"]] :source-paths ["--cljs-only--"] :codox {:language :clojurescript :sources ["src"]} :cljsbuild { :builds [{:id "squelch" :source-paths ["src"] :jar true :compiler { :output-to "squelch.js" :output-dir "out" :optimizations :none :source-map true}}]} :hooks [leiningen.cljsbuild] :scm {:name "git" :url "https://github.com/minaminamina/squelch"} :signing {:gpg-key "F6DC191D7745EF83"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "Mina Smart"] [:url "http://github.com/minasmart"] [:email "m.d.smart@gmail.com"] [:timezone "-5"]]])
16317
(defproject squelch "0.1.3-SNAPSHOT" :description "Squelch: A clojurescript web audio wrapper" :url "https://github.com/minasmart/squelch" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/clojurescript "0.0-2371"] [com.cemerick/piggieback "0.1.3"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-cljsbuild "1.0.6-SNAPSHOT"] [codox "0.8.10"]] :source-paths ["--cljs-only--"] :codox {:language :clojurescript :sources ["src"]} :cljsbuild { :builds [{:id "squelch" :source-paths ["src"] :jar true :compiler { :output-to "squelch.js" :output-dir "out" :optimizations :none :source-map true}}]} :hooks [leiningen.cljsbuild] :scm {:name "git" :url "https://github.com/minaminamina/squelch"} :signing {:gpg-key "<KEY>"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "<NAME>"] [:url "http://github.com/minasmart"] [:email "<EMAIL>"] [:timezone "-5"]]])
true
(defproject squelch "0.1.3-SNAPSHOT" :description "Squelch: A clojurescript web audio wrapper" :url "https://github.com/minasmart/squelch" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/clojurescript "0.0-2371"] [com.cemerick/piggieback "0.1.3"]] :repl-options {:nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} :plugins [[lein-cljsbuild "1.0.6-SNAPSHOT"] [codox "0.8.10"]] :source-paths ["--cljs-only--"] :codox {:language :clojurescript :sources ["src"]} :cljsbuild { :builds [{:id "squelch" :source-paths ["src"] :jar true :compiler { :output-to "squelch.js" :output-dir "out" :optimizations :none :source-map true}}]} :hooks [leiningen.cljsbuild] :scm {:name "git" :url "https://github.com/minaminamina/squelch"} :signing {:gpg-key "PI:KEY:<KEY>END_PI"} :deploy-repositories [["clojars" {:creds :gpg}]] :pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"] [:url "http://github.com/minasmart"] [:email "PI:EMAIL:<EMAIL>END_PI"] [:timezone "-5"]]])
[ { "context": "(\n ; Context map\n {}\n\n \"miili\"\n \"miil\"\n (metric :length 1609.34)\n\n \"km\"\n \"k", "end": 32, "score": 0.9428784847259521, "start": 27, "tag": "NAME", "value": "miili" }, { "context": "(\n ; Context map\n {}\n\n \"miili\"\n \"miil\"\n (metric :length 1609.34)\n\n \"km\"\n \"kilomeeter", "end": 41, "score": 0.9546657204627991, "start": 37, "tag": "NAME", "value": "miil" }, { "context": "\"kms\"\n \"kilomeetrit\"\n (metric :length 1000)\n\n \"meetrit\"\n \"meeter\"\n (metric :length 1)\n\n \"4 miili\"\n \"", "end": 152, "score": 0.6722347140312195, "start": 145, "tag": "NAME", "value": "meetrit" }, { "context": "omeetrit\"\n (metric :length 1000)\n\n \"meetrit\"\n \"meeter\"\n (metric :length 1)\n\n \"4 miili\"\n \"4 miili pik", "end": 163, "score": 0.7865824699401855, "start": 157, "tag": "NAME", "value": "meeter" } ]
resources/duckling/corpus/et.metrics.clj
siddharthg/duckling
0
( ; Context map {} "miili" "miil" (metric :length 1609.34) "km" "kilomeeter" "kms" "kilomeetrit" (metric :length 1000) "meetrit" "meeter" (metric :length 1) "4 miili" "4 miili pikkune" (metric :length 6437.36) )
23696
( ; Context map {} "<NAME>" "<NAME>" (metric :length 1609.34) "km" "kilomeeter" "kms" "kilomeetrit" (metric :length 1000) "<NAME>" "<NAME>" (metric :length 1) "4 miili" "4 miili pikkune" (metric :length 6437.36) )
true
( ; Context map {} "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" (metric :length 1609.34) "km" "kilomeeter" "kms" "kilomeetrit" (metric :length 1000) "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" (metric :length 1) "4 miili" "4 miili pikkune" (metric :length 6437.36) )
[ { "context": "ping\" \"whopping\" \"mindless\"]\n scientists [\"Curie\" \"Lovelace\" \"von Neumann\" \"Einstein\" \"Schroedinge", "end": 235, "score": 0.999803364276886, "start": 230, "tag": "NAME", "value": "Curie" }, { "context": "hopping\" \"mindless\"]\n scientists [\"Curie\" \"Lovelace\" \"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\"", "end": 246, "score": 0.9997577667236328, "start": 238, "tag": "NAME", "value": "Lovelace" }, { "context": "indless\"]\n scientists [\"Curie\" \"Lovelace\" \"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hil", "end": 260, "score": 0.9997150301933289, "start": 249, "tag": "NAME", "value": "von Neumann" }, { "context": " scientists [\"Curie\" \"Lovelace\" \"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hilbert\"]]\n ", "end": 271, "score": 0.9997684955596924, "start": 263, "tag": "NAME", "value": "Einstein" }, { "context": "sts [\"Curie\" \"Lovelace\" \"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hilbert\"]]\n (join \" \" (map", "end": 286, "score": 0.9997680187225342, "start": 274, "tag": "NAME", "value": "Schroedinger" }, { "context": "ovelace\" \"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hilbert\"]]\n (join \" \" (map rand-nth", "end": 295, "score": 0.9996492862701416, "start": 289, "tag": "NAME", "value": "Turing" }, { "context": "\"von Neumann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hilbert\"]]\n (join \" \" (map rand-nth [adjecti", "end": 304, "score": 0.999777615070343, "start": 298, "tag": "NAME", "value": "Goedel" }, { "context": "ann\" \"Einstein\" \"Schroedinger\" \"Turing\" \"Goedel\" \"Hilbert\"]]\n (join \" \" (map rand-nth [adjectives scient", "end": 314, "score": 0.9997575879096985, "start": 307, "tag": "NAME", "value": "Hilbert" } ]
version-name.cljs
kolja/instant-rocket-fuel-cljs
0
#!/usr/local/bin/planck (ns version-name.core (:require [clojure.string :refer [join]])) (defn version-name [] (let [adjectives ["awkward" "happy" "joyful" "jealous" "tiny" "jumping" "whopping" "mindless"] scientists ["Curie" "Lovelace" "von Neumann" "Einstein" "Schroedinger" "Turing" "Goedel" "Hilbert"]] (join " " (map rand-nth [adjectives scientists])))) (print (version-name))
113264
#!/usr/local/bin/planck (ns version-name.core (:require [clojure.string :refer [join]])) (defn version-name [] (let [adjectives ["awkward" "happy" "joyful" "jealous" "tiny" "jumping" "whopping" "mindless"] scientists ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]] (join " " (map rand-nth [adjectives scientists])))) (print (version-name))
true
#!/usr/local/bin/planck (ns version-name.core (:require [clojure.string :refer [join]])) (defn version-name [] (let [adjectives ["awkward" "happy" "joyful" "jealous" "tiny" "jumping" "whopping" "mindless"] scientists ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]] (join " " (map rand-nth [adjectives scientists])))) (print (version-name))
[ { "context": "id\n We defined a default resolver that gives us Darth Sideous's :sith/id. Pathom will then use sith-resolver to", "end": 2010, "score": 0.7398779988288879, "start": 1998, "tag": "NAME", "value": "arth Sideous" } ]
submissions/theianjones/src/main/app/proxy.cljs
theianjones/flux-challenge
0
(ns app.proxy (:require [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.diplomat.http :as http] [clojure.core.async :as async] [clojure.string :as string])) (defn fetch "this function takes the pathom env and adds HTTP headers and then sends HTTP request." [{:keys [_ api-url] :as env} {::keys [path method body] :or {method "GET"}}] (let [url (str api-url path)] (cond-> (assoc env ::http/as ::http/json ::http/url url ::http/content-type ::http/json ::http/method (keyword "com.wsscode.pathom.diplomat.http" (string/lower-case method))) body (assoc ::http/body body) :always http/request))) (def sith-output "helper that defines the output of both the sith resolvers." [:sith/name :sith/id :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]} ]) (defn qualify-homeworld [sith-response] "this function takes a sith http response and constructs the homeworld" {:homeWorld/name (-> sith-response :homeworld :name) :homeWorld/id (-> sith-response :homeworld :id)}) (defn get-sith [env {:sith/keys [id] :as params}] "async function that fetches a /dark-jedi/:id and returns the transformed result" (async/go (let [{::http/keys [body]} (async/<! (fetch env {::path (str "/dark-jedis/" id)})) sith {:sith/homeWorld (qualify-homeworld body) :sith/id (:id body) :sith/name (:name body) :sith/master (-> body :master :id) :sith/apprentice (-> body :apprentice :id)}] sith))) (def default-sith "Darth Sideous is the default sith." {:sith/id 3616}) (def register " resolvers we use to reach out to our jedi server. fetch a sith from the api given their :sith/id We defined a default resolver that gives us Darth Sideous's :sith/id. Pathom will then use sith-resolver to resolve the other requested fields " [(pc/defresolver sith-resolver [env params] {::pc/input #{:sith/id} ::pc/output sith-output} (get-sith env params)) (pc/defresolver first-sith [env _] {::pc/output [:default-sith [:sith/id]]} {:default-sith default-sith})])
42215
(ns app.proxy (:require [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.diplomat.http :as http] [clojure.core.async :as async] [clojure.string :as string])) (defn fetch "this function takes the pathom env and adds HTTP headers and then sends HTTP request." [{:keys [_ api-url] :as env} {::keys [path method body] :or {method "GET"}}] (let [url (str api-url path)] (cond-> (assoc env ::http/as ::http/json ::http/url url ::http/content-type ::http/json ::http/method (keyword "com.wsscode.pathom.diplomat.http" (string/lower-case method))) body (assoc ::http/body body) :always http/request))) (def sith-output "helper that defines the output of both the sith resolvers." [:sith/name :sith/id :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]} ]) (defn qualify-homeworld [sith-response] "this function takes a sith http response and constructs the homeworld" {:homeWorld/name (-> sith-response :homeworld :name) :homeWorld/id (-> sith-response :homeworld :id)}) (defn get-sith [env {:sith/keys [id] :as params}] "async function that fetches a /dark-jedi/:id and returns the transformed result" (async/go (let [{::http/keys [body]} (async/<! (fetch env {::path (str "/dark-jedis/" id)})) sith {:sith/homeWorld (qualify-homeworld body) :sith/id (:id body) :sith/name (:name body) :sith/master (-> body :master :id) :sith/apprentice (-> body :apprentice :id)}] sith))) (def default-sith "Darth Sideous is the default sith." {:sith/id 3616}) (def register " resolvers we use to reach out to our jedi server. fetch a sith from the api given their :sith/id We defined a default resolver that gives us D<NAME>'s :sith/id. Pathom will then use sith-resolver to resolve the other requested fields " [(pc/defresolver sith-resolver [env params] {::pc/input #{:sith/id} ::pc/output sith-output} (get-sith env params)) (pc/defresolver first-sith [env _] {::pc/output [:default-sith [:sith/id]]} {:default-sith default-sith})])
true
(ns app.proxy (:require [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.diplomat.http :as http] [clojure.core.async :as async] [clojure.string :as string])) (defn fetch "this function takes the pathom env and adds HTTP headers and then sends HTTP request." [{:keys [_ api-url] :as env} {::keys [path method body] :or {method "GET"}}] (let [url (str api-url path)] (cond-> (assoc env ::http/as ::http/json ::http/url url ::http/content-type ::http/json ::http/method (keyword "com.wsscode.pathom.diplomat.http" (string/lower-case method))) body (assoc ::http/body body) :always http/request))) (def sith-output "helper that defines the output of both the sith resolvers." [:sith/name :sith/id :sith/master :sith/apprentice {:sith/homeWorld [:homeWorld/name :homeWorld/id]} ]) (defn qualify-homeworld [sith-response] "this function takes a sith http response and constructs the homeworld" {:homeWorld/name (-> sith-response :homeworld :name) :homeWorld/id (-> sith-response :homeworld :id)}) (defn get-sith [env {:sith/keys [id] :as params}] "async function that fetches a /dark-jedi/:id and returns the transformed result" (async/go (let [{::http/keys [body]} (async/<! (fetch env {::path (str "/dark-jedis/" id)})) sith {:sith/homeWorld (qualify-homeworld body) :sith/id (:id body) :sith/name (:name body) :sith/master (-> body :master :id) :sith/apprentice (-> body :apprentice :id)}] sith))) (def default-sith "Darth Sideous is the default sith." {:sith/id 3616}) (def register " resolvers we use to reach out to our jedi server. fetch a sith from the api given their :sith/id We defined a default resolver that gives us DPI:NAME:<NAME>END_PI's :sith/id. Pathom will then use sith-resolver to resolve the other requested fields " [(pc/defresolver sith-resolver [env params] {::pc/input #{:sith/id} ::pc/output sith-output} (get-sith env params)) (pc/defresolver first-sith [env _] {::pc/output [:default-sith [:sith/id]]} {:default-sith default-sith})])
[ { "context": " {:key :password\n :type ", "end": 876, "score": 0.5338698625564575, "start": 868, "tag": "PASSWORD", "value": "password" }, { "context": "e}\n {:key :password\n :type \"pa", "end": 1952, "score": 0.5022946000099182, "start": 1944, "tag": "PASSWORD", "value": "password" }, { "context": "t]\n :fields [{:key :password\n :type \"pa", "end": 5223, "score": 0.9539873003959656, "start": 5215, "tag": "PASSWORD", "value": "password" } ]
priv/ui/src/holiday_ping_ui/auth/views.cljs
lambdaclass/holiday_ping
72
(ns holiday-ping-ui.auth.views (:require [holiday-ping-ui.routes :as routes] [holiday-ping-ui.common.views :as views] [holiday-ping-ui.common.forms :as forms])) ;;; AUTH VIEWS (defn login-view [] [:div [views/section-size "is-one-third-desktop is-half-tablet" [:div.card [:div.card-content (views/provider-login-button "GitHub" [:i.fa.fa-github]) [:br] (views/provider-login-button "Google" [:i.fa.fa-google]) [:hr] [views/message-view] [forms/form-view {:submit-text "Login" :submit-class "is-fullwidth" :on-submit [:auth-submit] :fields [{:key :email :type "email" :required true} {:key :password :type "password" :required true}]}] [:br] [:p.has-text-centered [:a {:href (routes/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (routes/url-for :register)} "Don't have an account?"]]]]]]) (defn register-view [] [views/section-size :is-half [:p.subtitle "Please fill your profile information."] [views/message-view] [forms/form-view {:submit-text "Register" :on-submit [:register-submit] :fields [{:key :email :type "email" :validate :valid-email? :required true} {:key :name :label "Full name" :type "text" :required true} {:key :password :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}] [:br] [:p.has-text-centered "Already registered? " [:a {:href (routes/url-for :login)} "Click here to login."]]]) (defn auth-message-view [subtitle & views] [views/section-size :is-two-thirds [:p.subtitle subtitle] (apply vector :div.container views)]) ;; EMAIL VERIFICATION VIEWS (defn email-sent-view [] [auth-message-view "Email verification sent." [:p "We just sent a confirmation link to the address you provided, please check your email to finish the registration process."]]) (defn register-confirm [] [auth-message-view "Email verified." [:p "Your account has been verified, " [:a {:href (routes/url-for :login)} "click here to login."]]]) (defn register-confirm-error [] [auth-message-view "Verification error." [:p "This verification link is wrong or expired, " [:a {:href (routes/url-for :resend-confirmation)} "click here to send the verification again."]]]) (defn not-verified-view [] [auth-message-view "Email not verified." [:p "You need to verify your email address before signing in. Check the verification link sent to your email."] [:br] [:p "If you didn't receive a verification email, " [:a {:href (routes/url-for :resend-confirmation)} "Click here to send it again."]]]) (defn resend-confirmation-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your address for email verification."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:resend-confirmation-submit] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) ;; PASSWORD RESET VIEWS (defn request-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your email to receive a password reset link."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:password-reset-request] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) (defn password-reset-sent-view [] [auth-message-view "Password reset sent." [:p "We just sent a password reset link to your email."]]) (defn submit-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your new password."] [views/message-view] [forms/form-view {:submit-text "Reset" :on-submit [:password-reset-submit] :fields [{:key :password :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}]]) (defn password-reset-error [] [auth-message-view "Password reset error." [:p "This password reset link is wrong or expired, " [:a {:href (routes/url-for :request-password-reset)} "click here to send it again."]]])
97022
(ns holiday-ping-ui.auth.views (:require [holiday-ping-ui.routes :as routes] [holiday-ping-ui.common.views :as views] [holiday-ping-ui.common.forms :as forms])) ;;; AUTH VIEWS (defn login-view [] [:div [views/section-size "is-one-third-desktop is-half-tablet" [:div.card [:div.card-content (views/provider-login-button "GitHub" [:i.fa.fa-github]) [:br] (views/provider-login-button "Google" [:i.fa.fa-google]) [:hr] [views/message-view] [forms/form-view {:submit-text "Login" :submit-class "is-fullwidth" :on-submit [:auth-submit] :fields [{:key :email :type "email" :required true} {:key :<PASSWORD> :type "password" :required true}]}] [:br] [:p.has-text-centered [:a {:href (routes/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (routes/url-for :register)} "Don't have an account?"]]]]]]) (defn register-view [] [views/section-size :is-half [:p.subtitle "Please fill your profile information."] [views/message-view] [forms/form-view {:submit-text "Register" :on-submit [:register-submit] :fields [{:key :email :type "email" :validate :valid-email? :required true} {:key :name :label "Full name" :type "text" :required true} {:key :<PASSWORD> :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}] [:br] [:p.has-text-centered "Already registered? " [:a {:href (routes/url-for :login)} "Click here to login."]]]) (defn auth-message-view [subtitle & views] [views/section-size :is-two-thirds [:p.subtitle subtitle] (apply vector :div.container views)]) ;; EMAIL VERIFICATION VIEWS (defn email-sent-view [] [auth-message-view "Email verification sent." [:p "We just sent a confirmation link to the address you provided, please check your email to finish the registration process."]]) (defn register-confirm [] [auth-message-view "Email verified." [:p "Your account has been verified, " [:a {:href (routes/url-for :login)} "click here to login."]]]) (defn register-confirm-error [] [auth-message-view "Verification error." [:p "This verification link is wrong or expired, " [:a {:href (routes/url-for :resend-confirmation)} "click here to send the verification again."]]]) (defn not-verified-view [] [auth-message-view "Email not verified." [:p "You need to verify your email address before signing in. Check the verification link sent to your email."] [:br] [:p "If you didn't receive a verification email, " [:a {:href (routes/url-for :resend-confirmation)} "Click here to send it again."]]]) (defn resend-confirmation-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your address for email verification."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:resend-confirmation-submit] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) ;; PASSWORD RESET VIEWS (defn request-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your email to receive a password reset link."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:password-reset-request] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) (defn password-reset-sent-view [] [auth-message-view "Password reset sent." [:p "We just sent a password reset link to your email."]]) (defn submit-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your new password."] [views/message-view] [forms/form-view {:submit-text "Reset" :on-submit [:password-reset-submit] :fields [{:key :<PASSWORD> :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}]]) (defn password-reset-error [] [auth-message-view "Password reset error." [:p "This password reset link is wrong or expired, " [:a {:href (routes/url-for :request-password-reset)} "click here to send it again."]]])
true
(ns holiday-ping-ui.auth.views (:require [holiday-ping-ui.routes :as routes] [holiday-ping-ui.common.views :as views] [holiday-ping-ui.common.forms :as forms])) ;;; AUTH VIEWS (defn login-view [] [:div [views/section-size "is-one-third-desktop is-half-tablet" [:div.card [:div.card-content (views/provider-login-button "GitHub" [:i.fa.fa-github]) [:br] (views/provider-login-button "Google" [:i.fa.fa-google]) [:hr] [views/message-view] [forms/form-view {:submit-text "Login" :submit-class "is-fullwidth" :on-submit [:auth-submit] :fields [{:key :email :type "email" :required true} {:key :PI:PASSWORD:<PASSWORD>END_PI :type "password" :required true}]}] [:br] [:p.has-text-centered [:a {:href (routes/url-for :request-password-reset)} "Forgot your password?"]] [:p.has-text-centered [:a {:href (routes/url-for :register)} "Don't have an account?"]]]]]]) (defn register-view [] [views/section-size :is-half [:p.subtitle "Please fill your profile information."] [views/message-view] [forms/form-view {:submit-text "Register" :on-submit [:register-submit] :fields [{:key :email :type "email" :validate :valid-email? :required true} {:key :name :label "Full name" :type "text" :required true} {:key :PI:PASSWORD:<PASSWORD>END_PI :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}] [:br] [:p.has-text-centered "Already registered? " [:a {:href (routes/url-for :login)} "Click here to login."]]]) (defn auth-message-view [subtitle & views] [views/section-size :is-two-thirds [:p.subtitle subtitle] (apply vector :div.container views)]) ;; EMAIL VERIFICATION VIEWS (defn email-sent-view [] [auth-message-view "Email verification sent." [:p "We just sent a confirmation link to the address you provided, please check your email to finish the registration process."]]) (defn register-confirm [] [auth-message-view "Email verified." [:p "Your account has been verified, " [:a {:href (routes/url-for :login)} "click here to login."]]]) (defn register-confirm-error [] [auth-message-view "Verification error." [:p "This verification link is wrong or expired, " [:a {:href (routes/url-for :resend-confirmation)} "click here to send the verification again."]]]) (defn not-verified-view [] [auth-message-view "Email not verified." [:p "You need to verify your email address before signing in. Check the verification link sent to your email."] [:br] [:p "If you didn't receive a verification email, " [:a {:href (routes/url-for :resend-confirmation)} "Click here to send it again."]]]) (defn resend-confirmation-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your address for email verification."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:resend-confirmation-submit] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) ;; PASSWORD RESET VIEWS (defn request-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your email to receive a password reset link."] [views/message-view] [forms/form-view {:submit-text "Send" :on-submit [:password-reset-request] :fields [{:key :email :type "email" :label "" :validate :valid-email? :required true}]}]]) (defn password-reset-sent-view [] [auth-message-view "Password reset sent." [:p "We just sent a password reset link to your email."]]) (defn submit-password-reset-view [] [views/section-size :is-half [:p.subtitle.has-text-centered "Enter your new password."] [views/message-view] [forms/form-view {:submit-text "Reset" :on-submit [:password-reset-submit] :fields [{:key :PI:PASSWORD:<PASSWORD>END_PI :type "password" :required true} {:key :password-repeat :type "password" :label "Repeat password" :validate :matching-passwords? :required true}]}]]) (defn password-reset-error [] [auth-message-view "Password reset error." [:p "This password reset link is wrong or expired, " [:a {:href (routes/url-for :request-password-reset)} "click here to send it again."]]])
[ { "context": "change (get doc :change)\n })\n\n(def index-key :yetipad)\n(def index-format :object)\n\n(defn <read-index []", "end": 607, "score": 0.9909793734550476, "start": 600, "tag": "KEY", "value": "yetipad" } ]
src/app/localstore.cljs
milelo/yetipad-app
2
(ns app.localstore (:require [lib.log :as log :refer [trace debug info warn fatal]] [lib.local-db :as ldb :refer [<put-data <get-data]] [cljs.core.async :as async :refer [<! >! chan put! take! close!] :refer-macros [go go-loop]] [lib.asyncutils :refer-macros [<? go?]] [lib.utils :as utils] [cljs.pprint :refer [pprint]] )) (def log (log/logger 'app.localstore)) (defn doc-meta [doc] {:id (get doc :doc-id) :title (get-in doc [:options :doc-title]) :subtitle (get-in doc [:options :doc-subtitle]) :change (get doc :change) }) (def index-key :yetipad) (def index-format :object) (defn <read-index [] (<get-data index-key {:format index-format :default {}})) #_(defn <read-doc [{doc-key :id doc-format :format :as doc-meta}] (<get-data doc-key {:format (or doc-format :object)})) (defn <read-doc [doc-id] (go (let [{doc-format :format :as doc-meta} (get (<? (<read-index)) doc-id)] (<! (<get-data doc-id {:format (or doc-format :object) :default {}})) ))) (defn <write-doc [doc] (go? (let [{doc-key :id doc-format :format :as doc-meta} (doc-meta doc) index (<! (<read-index)) index (dissoc (assoc index doc-key doc-meta) nil) ] (<? (<put-data index-key index {:format index-format})) (<? (<put-data doc-key (dissoc doc nil) {:format (or doc-format :object)})) ;(println "index:") ;(pprint index) index )))
28214
(ns app.localstore (:require [lib.log :as log :refer [trace debug info warn fatal]] [lib.local-db :as ldb :refer [<put-data <get-data]] [cljs.core.async :as async :refer [<! >! chan put! take! close!] :refer-macros [go go-loop]] [lib.asyncutils :refer-macros [<? go?]] [lib.utils :as utils] [cljs.pprint :refer [pprint]] )) (def log (log/logger 'app.localstore)) (defn doc-meta [doc] {:id (get doc :doc-id) :title (get-in doc [:options :doc-title]) :subtitle (get-in doc [:options :doc-subtitle]) :change (get doc :change) }) (def index-key :<KEY>) (def index-format :object) (defn <read-index [] (<get-data index-key {:format index-format :default {}})) #_(defn <read-doc [{doc-key :id doc-format :format :as doc-meta}] (<get-data doc-key {:format (or doc-format :object)})) (defn <read-doc [doc-id] (go (let [{doc-format :format :as doc-meta} (get (<? (<read-index)) doc-id)] (<! (<get-data doc-id {:format (or doc-format :object) :default {}})) ))) (defn <write-doc [doc] (go? (let [{doc-key :id doc-format :format :as doc-meta} (doc-meta doc) index (<! (<read-index)) index (dissoc (assoc index doc-key doc-meta) nil) ] (<? (<put-data index-key index {:format index-format})) (<? (<put-data doc-key (dissoc doc nil) {:format (or doc-format :object)})) ;(println "index:") ;(pprint index) index )))
true
(ns app.localstore (:require [lib.log :as log :refer [trace debug info warn fatal]] [lib.local-db :as ldb :refer [<put-data <get-data]] [cljs.core.async :as async :refer [<! >! chan put! take! close!] :refer-macros [go go-loop]] [lib.asyncutils :refer-macros [<? go?]] [lib.utils :as utils] [cljs.pprint :refer [pprint]] )) (def log (log/logger 'app.localstore)) (defn doc-meta [doc] {:id (get doc :doc-id) :title (get-in doc [:options :doc-title]) :subtitle (get-in doc [:options :doc-subtitle]) :change (get doc :change) }) (def index-key :PI:KEY:<KEY>END_PI) (def index-format :object) (defn <read-index [] (<get-data index-key {:format index-format :default {}})) #_(defn <read-doc [{doc-key :id doc-format :format :as doc-meta}] (<get-data doc-key {:format (or doc-format :object)})) (defn <read-doc [doc-id] (go (let [{doc-format :format :as doc-meta} (get (<? (<read-index)) doc-id)] (<! (<get-data doc-id {:format (or doc-format :object) :default {}})) ))) (defn <write-doc [doc] (go? (let [{doc-key :id doc-format :format :as doc-meta} (doc-meta doc) index (<! (<read-index)) index (dissoc (assoc index doc-key doc-meta) nil) ] (<? (<put-data index-key index {:format index-format})) (<? (<put-data doc-key (dissoc doc nil) {:format (or doc-format :object)})) ;(println "index:") ;(pprint index) index )))
[ { "context": "ttach-context\n {:users [(factory :user, {:email \"john@doe.com\"})]\n :entities [{:name \"Personal\"}]\n :commodi", "end": 712, "score": 0.9999145269393921, "start": 700, "tag": "EMAIL", "value": "john@doe.com" } ]
test/clj_money/models/attachments_test.clj
dgknght/clj-money
5
(ns clj-money.models.attachments-test (:require [clojure.test :refer [deftest use-fixtures is]] [clj-time.core :as t] [clj-factory.core :refer [factory]] [dgknght.app-lib.test] [clj-money.models.attachments :as attachments] [clj-money.models.transactions :as transactions] [clj-money.factories.user-factory] [clj-money.factories.entity-factory] [clj-money.test-context :refer [realize find-attachment]] [clj-money.test-helpers :refer [reset-db]])) (use-fixtures :each reset-db) (def ^:private attach-context {:users [(factory :user, {:email "john@doe.com"})] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :items [{:action :debit :account-id "Checking" :quantity 1000M} {:action :credit :account-id "Salary" :quantity 1000M}]}] :images [{:original-filename "sample_receipt.jpg" :body "resources/fixtures/sample_receipt.jpg" :content-type "image/jpeg"}]}) (defn- attributes [{[transaction] :transactions :as context}] {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction) :image-id (-> context :images first :id) :caption "receipt"}) (deftest create-an-attachment (let [context (realize attach-context) result (attachments/create (attributes context)) transaction (-> context :transactions first) retrieved (attachments/find-by {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction)}) retrieved-trans (transactions/find transaction)] (is (valid? result)) (is retrieved "The value can be retreived from the database") (is (= "receipt" (:caption retrieved)) "The caption is retrieved correctly") (is (= 1 (:attachment-count retrieved-trans)) "The number of attachments in the transaction is updated"))) (deftest transaction-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :transaction-id))] (is (invalid? result [:transaction-id] "Transaction is required")))) (deftest image-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :image-id))] (is (invalid? result [:image-id] "Image is required")))) (def ^:private update-context (assoc attach-context :attachments [{:transaction-id {:transaction-date (t/local-date 2017 1 1) :description "Paycheck"} :image-id "sample_receipt.jpg" :caption "receipt"}])) (deftest update-an-attachment (let [ctx (realize update-context) attachment (find-attachment ctx "receipt") result (attachments/update (assoc attachment :caption "Updated caption")) retrieved (attachments/find attachment)] (is (valid? result)) (is (= "Updated caption" (:caption result)) "The updated value is returned") (is (= "Updated caption" (:caption retrieved)) "The correct value is retrieved"))) (deftest delete-an-attachment (let [context (realize update-context) attachment (-> context :attachments first) _ (attachments/delete attachment) retrieved (attachments/find attachment) retrieved-trans (transactions/find attachment)] (is (nil? retrieved) "The value cannot be retrieved after delete") (is (= 0 (:attachment-count retrieved-trans)) "The attachment count is updated in the transaction")))
9332
(ns clj-money.models.attachments-test (:require [clojure.test :refer [deftest use-fixtures is]] [clj-time.core :as t] [clj-factory.core :refer [factory]] [dgknght.app-lib.test] [clj-money.models.attachments :as attachments] [clj-money.models.transactions :as transactions] [clj-money.factories.user-factory] [clj-money.factories.entity-factory] [clj-money.test-context :refer [realize find-attachment]] [clj-money.test-helpers :refer [reset-db]])) (use-fixtures :each reset-db) (def ^:private attach-context {:users [(factory :user, {:email "<EMAIL>"})] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :items [{:action :debit :account-id "Checking" :quantity 1000M} {:action :credit :account-id "Salary" :quantity 1000M}]}] :images [{:original-filename "sample_receipt.jpg" :body "resources/fixtures/sample_receipt.jpg" :content-type "image/jpeg"}]}) (defn- attributes [{[transaction] :transactions :as context}] {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction) :image-id (-> context :images first :id) :caption "receipt"}) (deftest create-an-attachment (let [context (realize attach-context) result (attachments/create (attributes context)) transaction (-> context :transactions first) retrieved (attachments/find-by {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction)}) retrieved-trans (transactions/find transaction)] (is (valid? result)) (is retrieved "The value can be retreived from the database") (is (= "receipt" (:caption retrieved)) "The caption is retrieved correctly") (is (= 1 (:attachment-count retrieved-trans)) "The number of attachments in the transaction is updated"))) (deftest transaction-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :transaction-id))] (is (invalid? result [:transaction-id] "Transaction is required")))) (deftest image-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :image-id))] (is (invalid? result [:image-id] "Image is required")))) (def ^:private update-context (assoc attach-context :attachments [{:transaction-id {:transaction-date (t/local-date 2017 1 1) :description "Paycheck"} :image-id "sample_receipt.jpg" :caption "receipt"}])) (deftest update-an-attachment (let [ctx (realize update-context) attachment (find-attachment ctx "receipt") result (attachments/update (assoc attachment :caption "Updated caption")) retrieved (attachments/find attachment)] (is (valid? result)) (is (= "Updated caption" (:caption result)) "The updated value is returned") (is (= "Updated caption" (:caption retrieved)) "The correct value is retrieved"))) (deftest delete-an-attachment (let [context (realize update-context) attachment (-> context :attachments first) _ (attachments/delete attachment) retrieved (attachments/find attachment) retrieved-trans (transactions/find attachment)] (is (nil? retrieved) "The value cannot be retrieved after delete") (is (= 0 (:attachment-count retrieved-trans)) "The attachment count is updated in the transaction")))
true
(ns clj-money.models.attachments-test (:require [clojure.test :refer [deftest use-fixtures is]] [clj-time.core :as t] [clj-factory.core :refer [factory]] [dgknght.app-lib.test] [clj-money.models.attachments :as attachments] [clj-money.models.transactions :as transactions] [clj-money.factories.user-factory] [clj-money.factories.entity-factory] [clj-money.test-context :refer [realize find-attachment]] [clj-money.test-helpers :refer [reset-db]])) (use-fixtures :each reset-db) (def ^:private attach-context {:users [(factory :user, {:email "PI:EMAIL:<EMAIL>END_PI"})] :entities [{:name "Personal"}] :commodities [{:name "US Dollar" :symbol "USD" :type :currency}] :accounts [{:name "Checking" :type :asset} {:name "Salary" :type :income} {:name "Groceries" :type :expense}] :transactions [{:transaction-date (t/local-date 2017 1 1) :description "Paycheck" :items [{:action :debit :account-id "Checking" :quantity 1000M} {:action :credit :account-id "Salary" :quantity 1000M}]}] :images [{:original-filename "sample_receipt.jpg" :body "resources/fixtures/sample_receipt.jpg" :content-type "image/jpeg"}]}) (defn- attributes [{[transaction] :transactions :as context}] {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction) :image-id (-> context :images first :id) :caption "receipt"}) (deftest create-an-attachment (let [context (realize attach-context) result (attachments/create (attributes context)) transaction (-> context :transactions first) retrieved (attachments/find-by {:transaction-id (:id transaction) :transaction-date (:transaction-date transaction)}) retrieved-trans (transactions/find transaction)] (is (valid? result)) (is retrieved "The value can be retreived from the database") (is (= "receipt" (:caption retrieved)) "The caption is retrieved correctly") (is (= 1 (:attachment-count retrieved-trans)) "The number of attachments in the transaction is updated"))) (deftest transaction-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :transaction-id))] (is (invalid? result [:transaction-id] "Transaction is required")))) (deftest image-id-is-required (let [context (realize attach-context) result (attachments/create (dissoc (attributes context) :image-id))] (is (invalid? result [:image-id] "Image is required")))) (def ^:private update-context (assoc attach-context :attachments [{:transaction-id {:transaction-date (t/local-date 2017 1 1) :description "Paycheck"} :image-id "sample_receipt.jpg" :caption "receipt"}])) (deftest update-an-attachment (let [ctx (realize update-context) attachment (find-attachment ctx "receipt") result (attachments/update (assoc attachment :caption "Updated caption")) retrieved (attachments/find attachment)] (is (valid? result)) (is (= "Updated caption" (:caption result)) "The updated value is returned") (is (= "Updated caption" (:caption retrieved)) "The correct value is retrieved"))) (deftest delete-an-attachment (let [context (realize update-context) attachment (-> context :attachments first) _ (attachments/delete attachment) retrieved (attachments/find attachment) retrieved-trans (transactions/find attachment)] (is (nil? retrieved) "The value cannot be retrieved after delete") (is (= 0 (:attachment-count retrieved-trans)) "The attachment count is updated in the transaction")))
[ { "context": "ody\n (->> (-> {:user \"skilbjo\"\n :password (->", "end": 1852, "score": 0.9994170069694519, "start": 1845, "tag": "USERNAME", "value": "skilbjo" }, { "context": " :password (-> \"god\"\n ", "end": 1907, "score": 0.9995525479316711, "start": 1904, "tag": "PASSWORD", "value": "god" } ]
test/jobs/api_test.clj
skilbjo/compojure
1
(ns jobs.api-test (:require [buddy.core.codecs :as codecs] [buddy.core.hash :as hash] [clj-time.coerce :as coerce] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [clojure.tools.logging :as log] [fixtures.api :as f] [fixtures.fixtures :refer [*cxn*] :as fix] [jobs.api :as api] [server.util :as util] [server.sql :as sql])) (use-fixtures :each (fix/with-database)) (deftest v1.unit-tests (testing "jobs.api unit tests" (is (= {:status 400 :body "Error: '/api/made_up_dataset' is not a valid endpoint.\nTry /api/equities or /api/currency."} (api/v1.latest "made_up_dataset"))))) (deftest v1.integration-test (log/warn "Remember to unset $jdbc_athena_uri, or fn will route requests to athena") (->> "test/insert-source-data.sql" io/resource slurp (jdbc/execute! *cxn*)) (testing "jobs.api.latest integration test" (let [expected (assoc {} :body (->> f/currency-result :body (map #(update % :date coerce/to-sql-date)))) actual (assoc {} :body (->> (api/v1.latest "currency") :body (map #(dissoc % :dw_created_at))))] (is (= expected actual)))) (testing "jobs.api.portfolio integration test" (let [expected (assoc {} :body (->> f/portfolio-result :body)) actual (assoc {} :body (->> (-> {:user "skilbjo" :password (-> "god" sql/escape' hash/sha256 codecs/bytes->hex)} api/v1.portfolio) :body (into [])))] (is (= expected actual)))))
111392
(ns jobs.api-test (:require [buddy.core.codecs :as codecs] [buddy.core.hash :as hash] [clj-time.coerce :as coerce] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [clojure.tools.logging :as log] [fixtures.api :as f] [fixtures.fixtures :refer [*cxn*] :as fix] [jobs.api :as api] [server.util :as util] [server.sql :as sql])) (use-fixtures :each (fix/with-database)) (deftest v1.unit-tests (testing "jobs.api unit tests" (is (= {:status 400 :body "Error: '/api/made_up_dataset' is not a valid endpoint.\nTry /api/equities or /api/currency."} (api/v1.latest "made_up_dataset"))))) (deftest v1.integration-test (log/warn "Remember to unset $jdbc_athena_uri, or fn will route requests to athena") (->> "test/insert-source-data.sql" io/resource slurp (jdbc/execute! *cxn*)) (testing "jobs.api.latest integration test" (let [expected (assoc {} :body (->> f/currency-result :body (map #(update % :date coerce/to-sql-date)))) actual (assoc {} :body (->> (api/v1.latest "currency") :body (map #(dissoc % :dw_created_at))))] (is (= expected actual)))) (testing "jobs.api.portfolio integration test" (let [expected (assoc {} :body (->> f/portfolio-result :body)) actual (assoc {} :body (->> (-> {:user "skilbjo" :password (-> "<PASSWORD>" sql/escape' hash/sha256 codecs/bytes->hex)} api/v1.portfolio) :body (into [])))] (is (= expected actual)))))
true
(ns jobs.api-test (:require [buddy.core.codecs :as codecs] [buddy.core.hash :as hash] [clj-time.coerce :as coerce] [clojure.java.io :as io] [clojure.java.jdbc :as jdbc] [clojure.test :refer :all] [clojure.tools.logging :as log] [fixtures.api :as f] [fixtures.fixtures :refer [*cxn*] :as fix] [jobs.api :as api] [server.util :as util] [server.sql :as sql])) (use-fixtures :each (fix/with-database)) (deftest v1.unit-tests (testing "jobs.api unit tests" (is (= {:status 400 :body "Error: '/api/made_up_dataset' is not a valid endpoint.\nTry /api/equities or /api/currency."} (api/v1.latest "made_up_dataset"))))) (deftest v1.integration-test (log/warn "Remember to unset $jdbc_athena_uri, or fn will route requests to athena") (->> "test/insert-source-data.sql" io/resource slurp (jdbc/execute! *cxn*)) (testing "jobs.api.latest integration test" (let [expected (assoc {} :body (->> f/currency-result :body (map #(update % :date coerce/to-sql-date)))) actual (assoc {} :body (->> (api/v1.latest "currency") :body (map #(dissoc % :dw_created_at))))] (is (= expected actual)))) (testing "jobs.api.portfolio integration test" (let [expected (assoc {} :body (->> f/portfolio-result :body)) actual (assoc {} :body (->> (-> {:user "skilbjo" :password (-> "PI:PASSWORD:<PASSWORD>END_PI" sql/escape' hash/sha256 codecs/bytes->hex)} api/v1.portfolio) :body (into [])))] (is (= expected actual)))))
[ { "context": ";; Copyright (c) 2015 <Diego Souza>\n\n;; Permission is hereby granted, free of charge", "end": 34, "score": 0.9998744130134583, "start": 23, "tag": "NAME", "value": "Diego Souza" } ]
src/storaged/src/leela/storaged/network/protocol.clj
locaweb/leela
22
;; Copyright (c) 2015 <Diego Souza> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns leela.storaged.network.protocol (:require [msgpack.core :as msgp] [clojure.string :refer [split]] [slingshot.slingshot :refer [throw+]] [leela.storaged.bytes :refer :all] [leela.storaged.security :refer [sign]])) (defn encode-query ([res hdrs body] ["query-1.0" res hdrs body]) ([res hdrs] ["query-1.0" res hdrs nil]) ([res] ["query-1.0" res {} nil])) (defn encode-reply ([code hdrs body] ["reply-1.0" code hdrs body]) ([code hdrs] ["reply-1.0" code hdrs nil]) ([code] ["reply-1.0" code {} nil])) (defn kind [q-o-r] (nth q-o-r 0)) (defn kind-nover [q-o-r] (let [known {"reply-1.0" :reply "query-1.0" :query}] (get known (kind q-o-r)))) (defn query? [msg] (= :query (kind-nover msg))) (defn reply? [msg] (= :reply (kind-nover msg))) (defn status [q-o-r] (when (reply? q-o-r) (nth q-o-r 1))) (defn resource [q-o-r] (when (query? q-o-r) (nth q-o-r 1))) (defn status-or-resource [q-o-r] (if (query? q-o-r) (resource q-o-r) (when (reply? q-o-r) (status q-o-r)))) (defn headers [q-o-r] (nth q-o-r 2)) (defn payload [q-o-r] (nth q-o-r 3)) (defn resource-fmap [fun q] [(kind q) (fun (resource q)) (headers q) (payload q)]) (defn status-fmap [fun r] [(kind r) (fun (status r)) (headers r) (payload r)]) (defn payload-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (headers q-o-r) (fun (payload q-o-r))]) (defn headers-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (fun (headers q-o-r)) (payload q-o-r)]) (defn header ([q-o-r key default] (get (headers q-o-r) key default)) ([q-o-r key] (get (headers q-o-r) key))) (defn header-content-type [q-o-r] (header q-o-r :content-type ["application/x-msgpack"])) (defn header-accept [q-o-r] (header q-o-r :accept ["application/x-msgpack"])) (defn- unframe-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(keyword k) (unframe-tr v)])) (coll? msg) (map unframe-tr msg) true msg)) (defn unframe [^bytes frame] (unframe-tr (msgp/unpack frame))) (defn unframe-when [frame vfun] (if-let [q-o-r (unframe frame)] (when (vfun q-o-r) q-o-r))) (defn- keyword->str [k] (subs (str k) 1)) (defn- frame-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(frame-tr k) (frame-tr v)])) (coll? msg) (map frame-tr msg) (keyword? msg) (subs (str msg) 1) true msg)) (defn frame [message] (msgp/pack (frame-tr message)))
98081
;; Copyright (c) 2015 <<NAME>> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns leela.storaged.network.protocol (:require [msgpack.core :as msgp] [clojure.string :refer [split]] [slingshot.slingshot :refer [throw+]] [leela.storaged.bytes :refer :all] [leela.storaged.security :refer [sign]])) (defn encode-query ([res hdrs body] ["query-1.0" res hdrs body]) ([res hdrs] ["query-1.0" res hdrs nil]) ([res] ["query-1.0" res {} nil])) (defn encode-reply ([code hdrs body] ["reply-1.0" code hdrs body]) ([code hdrs] ["reply-1.0" code hdrs nil]) ([code] ["reply-1.0" code {} nil])) (defn kind [q-o-r] (nth q-o-r 0)) (defn kind-nover [q-o-r] (let [known {"reply-1.0" :reply "query-1.0" :query}] (get known (kind q-o-r)))) (defn query? [msg] (= :query (kind-nover msg))) (defn reply? [msg] (= :reply (kind-nover msg))) (defn status [q-o-r] (when (reply? q-o-r) (nth q-o-r 1))) (defn resource [q-o-r] (when (query? q-o-r) (nth q-o-r 1))) (defn status-or-resource [q-o-r] (if (query? q-o-r) (resource q-o-r) (when (reply? q-o-r) (status q-o-r)))) (defn headers [q-o-r] (nth q-o-r 2)) (defn payload [q-o-r] (nth q-o-r 3)) (defn resource-fmap [fun q] [(kind q) (fun (resource q)) (headers q) (payload q)]) (defn status-fmap [fun r] [(kind r) (fun (status r)) (headers r) (payload r)]) (defn payload-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (headers q-o-r) (fun (payload q-o-r))]) (defn headers-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (fun (headers q-o-r)) (payload q-o-r)]) (defn header ([q-o-r key default] (get (headers q-o-r) key default)) ([q-o-r key] (get (headers q-o-r) key))) (defn header-content-type [q-o-r] (header q-o-r :content-type ["application/x-msgpack"])) (defn header-accept [q-o-r] (header q-o-r :accept ["application/x-msgpack"])) (defn- unframe-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(keyword k) (unframe-tr v)])) (coll? msg) (map unframe-tr msg) true msg)) (defn unframe [^bytes frame] (unframe-tr (msgp/unpack frame))) (defn unframe-when [frame vfun] (if-let [q-o-r (unframe frame)] (when (vfun q-o-r) q-o-r))) (defn- keyword->str [k] (subs (str k) 1)) (defn- frame-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(frame-tr k) (frame-tr v)])) (coll? msg) (map frame-tr msg) (keyword? msg) (subs (str msg) 1) true msg)) (defn frame [message] (msgp/pack (frame-tr message)))
true
;; Copyright (c) 2015 <PI:NAME:<NAME>END_PI> ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (ns leela.storaged.network.protocol (:require [msgpack.core :as msgp] [clojure.string :refer [split]] [slingshot.slingshot :refer [throw+]] [leela.storaged.bytes :refer :all] [leela.storaged.security :refer [sign]])) (defn encode-query ([res hdrs body] ["query-1.0" res hdrs body]) ([res hdrs] ["query-1.0" res hdrs nil]) ([res] ["query-1.0" res {} nil])) (defn encode-reply ([code hdrs body] ["reply-1.0" code hdrs body]) ([code hdrs] ["reply-1.0" code hdrs nil]) ([code] ["reply-1.0" code {} nil])) (defn kind [q-o-r] (nth q-o-r 0)) (defn kind-nover [q-o-r] (let [known {"reply-1.0" :reply "query-1.0" :query}] (get known (kind q-o-r)))) (defn query? [msg] (= :query (kind-nover msg))) (defn reply? [msg] (= :reply (kind-nover msg))) (defn status [q-o-r] (when (reply? q-o-r) (nth q-o-r 1))) (defn resource [q-o-r] (when (query? q-o-r) (nth q-o-r 1))) (defn status-or-resource [q-o-r] (if (query? q-o-r) (resource q-o-r) (when (reply? q-o-r) (status q-o-r)))) (defn headers [q-o-r] (nth q-o-r 2)) (defn payload [q-o-r] (nth q-o-r 3)) (defn resource-fmap [fun q] [(kind q) (fun (resource q)) (headers q) (payload q)]) (defn status-fmap [fun r] [(kind r) (fun (status r)) (headers r) (payload r)]) (defn payload-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (headers q-o-r) (fun (payload q-o-r))]) (defn headers-fmap [fun q-o-r] [(kind q-o-r) (status-or-resource q-o-r) (fun (headers q-o-r)) (payload q-o-r)]) (defn header ([q-o-r key default] (get (headers q-o-r) key default)) ([q-o-r key] (get (headers q-o-r) key))) (defn header-content-type [q-o-r] (header q-o-r :content-type ["application/x-msgpack"])) (defn header-accept [q-o-r] (header q-o-r :accept ["application/x-msgpack"])) (defn- unframe-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(keyword k) (unframe-tr v)])) (coll? msg) (map unframe-tr msg) true msg)) (defn unframe [^bytes frame] (unframe-tr (msgp/unpack frame))) (defn unframe-when [frame vfun] (if-let [q-o-r (unframe frame)] (when (vfun q-o-r) q-o-r))) (defn- keyword->str [k] (subs (str k) 1)) (defn- frame-tr [msg] (cond (map? msg) (into {} (for [[k v] msg] [(frame-tr k) (frame-tr v)])) (coll? msg) (map frame-tr msg) (keyword? msg) (subs (str msg) 1) true msg)) (defn frame [message] (msgp/pack (frame-tr message)))
[ { "context": " 200\r\n :body \"<h1>About page</h1> \r\n \t <p>Milos Marinkovic, Sofrware Developer</p>\"\r\n :headers {}})\r\n\r\n(de", "end": 627, "score": 0.9998435974121094, "start": 611, "tag": "NAME", "value": "Milos Marinkovic" } ]
src/clojure_practice/core.clj
marinkovicmilos/practice-clojure
0
(ns clojure-practice.core (:require [ring.adapter.jetty :as jetty] [ring.middleware.reload :refer [wrap-reload]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [not-found]] [views.home :as home] [views.create :as create] [views.customerview :as customerview])) (defn hello [request] {:status 200 :body "<h1>Hello World</h1> <p>My first Clojure app with defroutes for requests</p>" :headers {}}) (defn about [request] {:status 200 :body "<h1>About page</h1> <p>Milos Marinkovic, Sofrware Developer</p>" :headers {}}) (defn greeting [request] (let [name (get-in request [:route-params :name])] {:status 200 :body (str "Hello " name ".") :headers {}})) (defn greeting-full-name [request] (let [firstName (get-in request [:route-params :firstName]) lastName (get-in request [:route-params :lastName])] {:status 200 :body (str "Hello " firstName ", " lastName ".") :headers {}})) (defroutes app ;;(GET "/" [] hello) (GET "/" [] (home/home-page)) (GET "/add-customer" [] (create/add-customer-page)) (GET "/customers" [] (customerview/all-customers-page)) (GET "/about" [] about) (GET "/greeting/:name" [] greeting) (GET "/greeting/:firstName/:lastName" [] greeting-full-name) (not-found "<h1>Error 404</h1> <p>Page not found</p>")) (defn -main [port-number] (jetty/run-jetty app {:port (Integer. port-number)})) (defn -wrap-reload-main [port-number] (jetty/run-jetty (wrap-reload #'app) {:port (Integer. port-number)}))
23737
(ns clojure-practice.core (:require [ring.adapter.jetty :as jetty] [ring.middleware.reload :refer [wrap-reload]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [not-found]] [views.home :as home] [views.create :as create] [views.customerview :as customerview])) (defn hello [request] {:status 200 :body "<h1>Hello World</h1> <p>My first Clojure app with defroutes for requests</p>" :headers {}}) (defn about [request] {:status 200 :body "<h1>About page</h1> <p><NAME>, Sofrware Developer</p>" :headers {}}) (defn greeting [request] (let [name (get-in request [:route-params :name])] {:status 200 :body (str "Hello " name ".") :headers {}})) (defn greeting-full-name [request] (let [firstName (get-in request [:route-params :firstName]) lastName (get-in request [:route-params :lastName])] {:status 200 :body (str "Hello " firstName ", " lastName ".") :headers {}})) (defroutes app ;;(GET "/" [] hello) (GET "/" [] (home/home-page)) (GET "/add-customer" [] (create/add-customer-page)) (GET "/customers" [] (customerview/all-customers-page)) (GET "/about" [] about) (GET "/greeting/:name" [] greeting) (GET "/greeting/:firstName/:lastName" [] greeting-full-name) (not-found "<h1>Error 404</h1> <p>Page not found</p>")) (defn -main [port-number] (jetty/run-jetty app {:port (Integer. port-number)})) (defn -wrap-reload-main [port-number] (jetty/run-jetty (wrap-reload #'app) {:port (Integer. port-number)}))
true
(ns clojure-practice.core (:require [ring.adapter.jetty :as jetty] [ring.middleware.reload :refer [wrap-reload]] [compojure.core :refer [defroutes GET]] [compojure.route :refer [not-found]] [views.home :as home] [views.create :as create] [views.customerview :as customerview])) (defn hello [request] {:status 200 :body "<h1>Hello World</h1> <p>My first Clojure app with defroutes for requests</p>" :headers {}}) (defn about [request] {:status 200 :body "<h1>About page</h1> <p>PI:NAME:<NAME>END_PI, Sofrware Developer</p>" :headers {}}) (defn greeting [request] (let [name (get-in request [:route-params :name])] {:status 200 :body (str "Hello " name ".") :headers {}})) (defn greeting-full-name [request] (let [firstName (get-in request [:route-params :firstName]) lastName (get-in request [:route-params :lastName])] {:status 200 :body (str "Hello " firstName ", " lastName ".") :headers {}})) (defroutes app ;;(GET "/" [] hello) (GET "/" [] (home/home-page)) (GET "/add-customer" [] (create/add-customer-page)) (GET "/customers" [] (customerview/all-customers-page)) (GET "/about" [] about) (GET "/greeting/:name" [] greeting) (GET "/greeting/:firstName/:lastName" [] greeting-full-name) (not-found "<h1>Error 404</h1> <p>Page not found</p>")) (defn -main [port-number] (jetty/run-jetty app {:port (Integer. port-number)})) (defn -wrap-reload-main [port-number] (jetty/run-jetty (wrap-reload #'app) {:port (Integer. port-number)}))
[ { "context": "(for [[start end] cs]\n ^{:key (str \"location-connection\" start \"->\" end)}\n [location-connection sta", "end": 6830, "score": 0.599087119102478, "start": 6820, "tag": "KEY", "value": "connection" } ]
src/cljs/armchair/location_map/views.cljs
maiwald/armchair
6
(ns armchair.location-map.views (:require [reagent.core :as r] [armchair.components :as c] [armchair.components.tile-map :refer [tile-select tile-dropzone]] [armchair.sprites :refer [Sprite]] [armchair.math :as m] [armchair.util :as u :refer [<sub >evt e->left?]] [goog.functions :refer [debounce]])) (defn drag-container [] (let [dragging? (<sub [:dragging?]) move-cursor (when dragging? #(>evt [:move-cursor (u/e->point %)])) stop-dragging (when dragging? #(>evt [:end-dragging]))] (into [:div {:class ["drag-container" (when dragging? "drag-container_is-dragging")] :on-mouse-leave stop-dragging :on-mouse-up stop-dragging :on-mouse-move move-cursor}] (r/children (r/current-component))))) (defn location [] (let [mouse-down-start (atom nil)] (fn [location-id] (let [{:keys [display-name characters preview-image-background-src preview-image-foreground-src preview-image-w preview-image-h zoom-scale bounds is-inspecting inspected-tile can-drop? drag-entity]} (<sub [:location-map/location location-id]) is-dragging (<sub [:dragging-item? location-id]) position (<sub [:location-map/location-position location-id]) start-dragging (fn [e] (when (e->left? e) (u/stop-e! e) (u/prevent-e! e) (>evt [:start-dragging #{location-id} (u/e->point e) zoom-scale]))) stop-dragging (fn [e] (when is-dragging (u/stop-e! e) (>evt [:end-dragging]))) inspect-location #(>evt [:inspect :location location-id])] [:div {:class ["location" (when is-inspecting "location_is-inspecting") (when is-dragging "location_is-dragging")] :on-mouse-down u/stop-e! :style {:left (u/px (:x position)) :top (u/px (:y position))}} [:header {:class "location__header" :on-mouse-down (fn [e] (reset! mouse-down-start (js/Date.now)) (start-dragging e)) :on-mouse-up (fn [e] ;; should this count as click or just a drag? (when (and (some? @mouse-down-start) (< (- (js/Date.now) @mouse-down-start) 200)) (inspect-location) (reset! mouse-down-start nil)) (stop-dragging e))} [:p {:class "location__header__title"} display-name]] (if (and (some? preview-image-background-src) (some? preview-image-foreground-src)) [:div {:class "location__tilemap-wrapper"} [:div {:class "location__tilemap" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [:img {:src preview-image-background-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (seq characters) [:<> (for [[tile {:keys [sprite display-name]}] characters] [:div {:key (str "location-character:" location-id ",tile:" (pr-str tile)) :class ["location__tilemap__character"] :style (u/tile-style tile zoom-scale)} [Sprite sprite display-name zoom-scale]])]) [:img {:src preview-image-foreground-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (some? inspected-tile) [:div {:class ["location__tilemap__tile_is-inspecting"] :style (u/tile-style inspected-tile zoom-scale)}]) [tile-select {:zoom-scale zoom-scale :on-drag-start (fn [e tile] (if-let [entity (drag-entity tile)] (>evt [:start-entity-drag entity]) (u/prevent-e! e))) :on-drag-end (fn [] (>evt [:stop-entity-drag])) :on-click (fn [tile] (>evt [:inspect :tile location-id (m/relative-point tile bounds)]))}] (when (<sub [:ui/dnd]) [tile-dropzone {:zoom-scale zoom-scale :can-drop? can-drop? :on-drop (fn [tile] (>evt [:drop-entity location-id (m/relative-point tile bounds)])) :on-drag-leave #(>evt [:unset-entity-drop-preview]) :on-drag-over (fn [tile] (>evt [:set-entity-drop-preview location-id (m/relative-point tile bounds)]))}])]] [:div {:class "location__loading" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [c/spinner]])])))) (defn location-connection [[start-location start-tile] [end-location end-tile]] (let [tile-size (<sub [:location-map/tile-size]) {start-tile :tile start-tile-center :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {end-tile-center :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:<> [:rect {:stroke "red" :stroke-width 1 :fill "none" :x (:x start-tile) :y (:y start-tile) :width tile-size :height tile-size}] [:rect {:fill "yellow" :x (- (:x end-tile-center) 3) :y (- (:y end-tile-center) 3) :width 6 :height 6}] [:line {:class ["location-connection"] :x1 (:x start-tile-center) :y1 (:y start-tile-center) :x2 (:x end-tile-center) :y2 (:y end-tile-center)}]])) (defn connections [] (let [cs (<sub [:location-map/connections])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (for [[start end] cs] ^{:key (str "location-connection" start "->" end)} [location-connection start end])])) (defn connection-preview [] (when-let [drag-preview (<sub [:location-map/dnd-connection-preview])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (let [{[start-location start-tile] :start [end-location end-tile] :end} drag-preview {{start-x :x start-y :y} :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {{end-x :x end-y :y} :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:line {:stroke-width 2 :stroke "red" :x1 start-x :y1 start-y :x2 end-x :y2 end-y}])])) (defn e->scroll-center [e] (let [target (.-currentTarget e)] (m/Point. (+ (.-scrollLeft target) (/ (.-clientWidth target) 2)) (+ (.-scrollTop target) (/ (.-clientHeight target) 2))))) (defn location-map-header [] [:header.page-header [:h1 "World"] [:ul.page-header__actions [:li [c/button {:title "Zoom Out" :icon "minus" :on-click #(>evt [:location-map/zoom-out])}]] [:li [c/button {:title "Zoom In" :icon "plus" :on-click #(>evt [:location-map/zoom-in])}]] [:li [c/button {:title "New Location" :icon "plus" :on-click #(>evt [:armchair.modals.location-creation/open])}]]]]) (defn location-map [] (let [update-scroll-center (debounce #(>evt [:location-map/update-scroll-center %]) 200) on-scroll (comp update-scroll-center e->scroll-center)] (fn [] (let [{:keys [bounds scroll-center location-ids zoom-scale]} (<sub [:location-map])] [c/scroll-container {:width (:w bounds) :height (:h bounds) :scroll-center scroll-center :zoom-scale zoom-scale :on-scroll on-scroll} [drag-container (for [id location-ids] ^{:key (str "location:" id)} [location id]) [connections] [connection-preview]]]))))
66558
(ns armchair.location-map.views (:require [reagent.core :as r] [armchair.components :as c] [armchair.components.tile-map :refer [tile-select tile-dropzone]] [armchair.sprites :refer [Sprite]] [armchair.math :as m] [armchair.util :as u :refer [<sub >evt e->left?]] [goog.functions :refer [debounce]])) (defn drag-container [] (let [dragging? (<sub [:dragging?]) move-cursor (when dragging? #(>evt [:move-cursor (u/e->point %)])) stop-dragging (when dragging? #(>evt [:end-dragging]))] (into [:div {:class ["drag-container" (when dragging? "drag-container_is-dragging")] :on-mouse-leave stop-dragging :on-mouse-up stop-dragging :on-mouse-move move-cursor}] (r/children (r/current-component))))) (defn location [] (let [mouse-down-start (atom nil)] (fn [location-id] (let [{:keys [display-name characters preview-image-background-src preview-image-foreground-src preview-image-w preview-image-h zoom-scale bounds is-inspecting inspected-tile can-drop? drag-entity]} (<sub [:location-map/location location-id]) is-dragging (<sub [:dragging-item? location-id]) position (<sub [:location-map/location-position location-id]) start-dragging (fn [e] (when (e->left? e) (u/stop-e! e) (u/prevent-e! e) (>evt [:start-dragging #{location-id} (u/e->point e) zoom-scale]))) stop-dragging (fn [e] (when is-dragging (u/stop-e! e) (>evt [:end-dragging]))) inspect-location #(>evt [:inspect :location location-id])] [:div {:class ["location" (when is-inspecting "location_is-inspecting") (when is-dragging "location_is-dragging")] :on-mouse-down u/stop-e! :style {:left (u/px (:x position)) :top (u/px (:y position))}} [:header {:class "location__header" :on-mouse-down (fn [e] (reset! mouse-down-start (js/Date.now)) (start-dragging e)) :on-mouse-up (fn [e] ;; should this count as click or just a drag? (when (and (some? @mouse-down-start) (< (- (js/Date.now) @mouse-down-start) 200)) (inspect-location) (reset! mouse-down-start nil)) (stop-dragging e))} [:p {:class "location__header__title"} display-name]] (if (and (some? preview-image-background-src) (some? preview-image-foreground-src)) [:div {:class "location__tilemap-wrapper"} [:div {:class "location__tilemap" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [:img {:src preview-image-background-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (seq characters) [:<> (for [[tile {:keys [sprite display-name]}] characters] [:div {:key (str "location-character:" location-id ",tile:" (pr-str tile)) :class ["location__tilemap__character"] :style (u/tile-style tile zoom-scale)} [Sprite sprite display-name zoom-scale]])]) [:img {:src preview-image-foreground-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (some? inspected-tile) [:div {:class ["location__tilemap__tile_is-inspecting"] :style (u/tile-style inspected-tile zoom-scale)}]) [tile-select {:zoom-scale zoom-scale :on-drag-start (fn [e tile] (if-let [entity (drag-entity tile)] (>evt [:start-entity-drag entity]) (u/prevent-e! e))) :on-drag-end (fn [] (>evt [:stop-entity-drag])) :on-click (fn [tile] (>evt [:inspect :tile location-id (m/relative-point tile bounds)]))}] (when (<sub [:ui/dnd]) [tile-dropzone {:zoom-scale zoom-scale :can-drop? can-drop? :on-drop (fn [tile] (>evt [:drop-entity location-id (m/relative-point tile bounds)])) :on-drag-leave #(>evt [:unset-entity-drop-preview]) :on-drag-over (fn [tile] (>evt [:set-entity-drop-preview location-id (m/relative-point tile bounds)]))}])]] [:div {:class "location__loading" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [c/spinner]])])))) (defn location-connection [[start-location start-tile] [end-location end-tile]] (let [tile-size (<sub [:location-map/tile-size]) {start-tile :tile start-tile-center :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {end-tile-center :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:<> [:rect {:stroke "red" :stroke-width 1 :fill "none" :x (:x start-tile) :y (:y start-tile) :width tile-size :height tile-size}] [:rect {:fill "yellow" :x (- (:x end-tile-center) 3) :y (- (:y end-tile-center) 3) :width 6 :height 6}] [:line {:class ["location-connection"] :x1 (:x start-tile-center) :y1 (:y start-tile-center) :x2 (:x end-tile-center) :y2 (:y end-tile-center)}]])) (defn connections [] (let [cs (<sub [:location-map/connections])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (for [[start end] cs] ^{:key (str "location-<KEY>" start "->" end)} [location-connection start end])])) (defn connection-preview [] (when-let [drag-preview (<sub [:location-map/dnd-connection-preview])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (let [{[start-location start-tile] :start [end-location end-tile] :end} drag-preview {{start-x :x start-y :y} :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {{end-x :x end-y :y} :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:line {:stroke-width 2 :stroke "red" :x1 start-x :y1 start-y :x2 end-x :y2 end-y}])])) (defn e->scroll-center [e] (let [target (.-currentTarget e)] (m/Point. (+ (.-scrollLeft target) (/ (.-clientWidth target) 2)) (+ (.-scrollTop target) (/ (.-clientHeight target) 2))))) (defn location-map-header [] [:header.page-header [:h1 "World"] [:ul.page-header__actions [:li [c/button {:title "Zoom Out" :icon "minus" :on-click #(>evt [:location-map/zoom-out])}]] [:li [c/button {:title "Zoom In" :icon "plus" :on-click #(>evt [:location-map/zoom-in])}]] [:li [c/button {:title "New Location" :icon "plus" :on-click #(>evt [:armchair.modals.location-creation/open])}]]]]) (defn location-map [] (let [update-scroll-center (debounce #(>evt [:location-map/update-scroll-center %]) 200) on-scroll (comp update-scroll-center e->scroll-center)] (fn [] (let [{:keys [bounds scroll-center location-ids zoom-scale]} (<sub [:location-map])] [c/scroll-container {:width (:w bounds) :height (:h bounds) :scroll-center scroll-center :zoom-scale zoom-scale :on-scroll on-scroll} [drag-container (for [id location-ids] ^{:key (str "location:" id)} [location id]) [connections] [connection-preview]]]))))
true
(ns armchair.location-map.views (:require [reagent.core :as r] [armchair.components :as c] [armchair.components.tile-map :refer [tile-select tile-dropzone]] [armchair.sprites :refer [Sprite]] [armchair.math :as m] [armchair.util :as u :refer [<sub >evt e->left?]] [goog.functions :refer [debounce]])) (defn drag-container [] (let [dragging? (<sub [:dragging?]) move-cursor (when dragging? #(>evt [:move-cursor (u/e->point %)])) stop-dragging (when dragging? #(>evt [:end-dragging]))] (into [:div {:class ["drag-container" (when dragging? "drag-container_is-dragging")] :on-mouse-leave stop-dragging :on-mouse-up stop-dragging :on-mouse-move move-cursor}] (r/children (r/current-component))))) (defn location [] (let [mouse-down-start (atom nil)] (fn [location-id] (let [{:keys [display-name characters preview-image-background-src preview-image-foreground-src preview-image-w preview-image-h zoom-scale bounds is-inspecting inspected-tile can-drop? drag-entity]} (<sub [:location-map/location location-id]) is-dragging (<sub [:dragging-item? location-id]) position (<sub [:location-map/location-position location-id]) start-dragging (fn [e] (when (e->left? e) (u/stop-e! e) (u/prevent-e! e) (>evt [:start-dragging #{location-id} (u/e->point e) zoom-scale]))) stop-dragging (fn [e] (when is-dragging (u/stop-e! e) (>evt [:end-dragging]))) inspect-location #(>evt [:inspect :location location-id])] [:div {:class ["location" (when is-inspecting "location_is-inspecting") (when is-dragging "location_is-dragging")] :on-mouse-down u/stop-e! :style {:left (u/px (:x position)) :top (u/px (:y position))}} [:header {:class "location__header" :on-mouse-down (fn [e] (reset! mouse-down-start (js/Date.now)) (start-dragging e)) :on-mouse-up (fn [e] ;; should this count as click or just a drag? (when (and (some? @mouse-down-start) (< (- (js/Date.now) @mouse-down-start) 200)) (inspect-location) (reset! mouse-down-start nil)) (stop-dragging e))} [:p {:class "location__header__title"} display-name]] (if (and (some? preview-image-background-src) (some? preview-image-foreground-src)) [:div {:class "location__tilemap-wrapper"} [:div {:class "location__tilemap" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [:img {:src preview-image-background-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (seq characters) [:<> (for [[tile {:keys [sprite display-name]}] characters] [:div {:key (str "location-character:" location-id ",tile:" (pr-str tile)) :class ["location__tilemap__character"] :style (u/tile-style tile zoom-scale)} [Sprite sprite display-name zoom-scale]])]) [:img {:src preview-image-foreground-src :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}}] (when (some? inspected-tile) [:div {:class ["location__tilemap__tile_is-inspecting"] :style (u/tile-style inspected-tile zoom-scale)}]) [tile-select {:zoom-scale zoom-scale :on-drag-start (fn [e tile] (if-let [entity (drag-entity tile)] (>evt [:start-entity-drag entity]) (u/prevent-e! e))) :on-drag-end (fn [] (>evt [:stop-entity-drag])) :on-click (fn [tile] (>evt [:inspect :tile location-id (m/relative-point tile bounds)]))}] (when (<sub [:ui/dnd]) [tile-dropzone {:zoom-scale zoom-scale :can-drop? can-drop? :on-drop (fn [tile] (>evt [:drop-entity location-id (m/relative-point tile bounds)])) :on-drag-leave #(>evt [:unset-entity-drop-preview]) :on-drag-over (fn [tile] (>evt [:set-entity-drop-preview location-id (m/relative-point tile bounds)]))}])]] [:div {:class "location__loading" :style {:width (u/px preview-image-w) :height (u/px preview-image-h)}} [c/spinner]])])))) (defn location-connection [[start-location start-tile] [end-location end-tile]] (let [tile-size (<sub [:location-map/tile-size]) {start-tile :tile start-tile-center :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {end-tile-center :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:<> [:rect {:stroke "red" :stroke-width 1 :fill "none" :x (:x start-tile) :y (:y start-tile) :width tile-size :height tile-size}] [:rect {:fill "yellow" :x (- (:x end-tile-center) 3) :y (- (:y end-tile-center) 3) :width 6 :height 6}] [:line {:class ["location-connection"] :x1 (:x start-tile-center) :y1 (:y start-tile-center) :x2 (:x end-tile-center) :y2 (:y end-tile-center)}]])) (defn connections [] (let [cs (<sub [:location-map/connections])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (for [[start end] cs] ^{:key (str "location-PI:KEY:<KEY>END_PI" start "->" end)} [location-connection start end])])) (defn connection-preview [] (when-let [drag-preview (<sub [:location-map/dnd-connection-preview])] [:svg {:class "location-connections" :version "1.1" :baseProfile "full" :xmlns "http://www.w3.org/2000/svg"} (let [{[start-location start-tile] :start [end-location end-tile] :end} drag-preview {{start-x :x start-y :y} :tile-center} (<sub [:location-map/connection-position start-location start-tile]) {{end-x :x end-y :y} :tile-center} (<sub [:location-map/connection-position end-location end-tile])] [:line {:stroke-width 2 :stroke "red" :x1 start-x :y1 start-y :x2 end-x :y2 end-y}])])) (defn e->scroll-center [e] (let [target (.-currentTarget e)] (m/Point. (+ (.-scrollLeft target) (/ (.-clientWidth target) 2)) (+ (.-scrollTop target) (/ (.-clientHeight target) 2))))) (defn location-map-header [] [:header.page-header [:h1 "World"] [:ul.page-header__actions [:li [c/button {:title "Zoom Out" :icon "minus" :on-click #(>evt [:location-map/zoom-out])}]] [:li [c/button {:title "Zoom In" :icon "plus" :on-click #(>evt [:location-map/zoom-in])}]] [:li [c/button {:title "New Location" :icon "plus" :on-click #(>evt [:armchair.modals.location-creation/open])}]]]]) (defn location-map [] (let [update-scroll-center (debounce #(>evt [:location-map/update-scroll-center %]) 200) on-scroll (comp update-scroll-center e->scroll-center)] (fn [] (let [{:keys [bounds scroll-center location-ids zoom-scale]} (<sub [:location-map])] [c/scroll-container {:width (:w bounds) :height (:h bounds) :scroll-center scroll-center :zoom-scale zoom-scale :on-scroll on-scroll} [drag-container (for [id location-ids] ^{:key (str "location:" id)} [location id]) [connections] [connection-preview]]]))))
[ { "context": "sticseach as back-end\"\n :url \"https://github.com/nikos/elastic-ring\"\n :license {:name \"MIT\"\n ", "end": 172, "score": 0.9992762804031372, "start": 167, "tag": "USERNAME", "value": "nikos" }, { "context": "ein-environ \"1.0.0\"]]\n\n ; See https://github.com/weavejester/lein-ring#web-server-options for the\n ; various ", "end": 1362, "score": 0.9921810626983643, "start": 1351, "tag": "USERNAME", "value": "weavejester" }, { "context": "n.\n :env {:elastic-url \"http://127.0.0.1:9200\"\n :elastic-user \"use", "end": 1884, "score": 0.8564965724945068, "start": 1875, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "0.1:9200\"\n :elastic-user \"user\"\n :elastic-pass \"pass\"}}\n", "end": 1935, "score": 0.9890685677528381, "start": 1931, "tag": "USERNAME", "value": "user" }, { "context": "er \"user\"\n :elastic-pass \"pass\"}}\n\n :test {:env {:elastic-url \"http://127.0.0", "end": 1981, "score": 0.9994338154792786, "start": 1977, "tag": "PASSWORD", "value": "pass" }, { "context": "s \"pass\"}}\n\n :test {:env {:elastic-url \"http://127.0.0.1:9200\"\n :elastic-user \"user\"\n ", "end": 2033, "score": 0.9863467812538147, "start": 2024, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "://127.0.0.1:9200\"\n :elastic-user \"user\"\n :elastic-pass \"pass\"}}})\n", "end": 2075, "score": 0.931448221206665, "start": 2071, "tag": "USERNAME", "value": "user" }, { "context": "lastic-user \"user\"\n :elastic-pass \"pass\"}}})\n", "end": 2112, "score": 0.9994810223579407, "start": 2108, "tag": "PASSWORD", "value": "pass" } ]
project.clj
nikos/elastic-ring
1
(defproject mini-restful "0.1.2-SNAPSHOT" :description "An example RESTful application written in Clojure using elasticseach as back-end" :url "https://github.com/nikos/elastic-ring" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.logging "0.3.1"] ;; HTTP handling [ring/ring-core "1.4.0"] [ring/ring-jetty-adapter "1.4.0"] [ring/ring-json "0.4.0"] [compojure "1.4.0"] ;; schema validation [prismatic/schema "0.4.3"] ;; elasticsearch driver [clojurewerkz/elastisch "2.2.0-beta4"] [clj-time "0.11.0"] [cheshire "5.5.0"] [environ "1.0.0"] [buddy/buddy-hashers "0.6.0"] [buddy/buddy-auth "0.6.0"] [crypto-random "1.2.0"]] ; The lein-ring plugin allows us to easily start a development web server ; with "lein ring server". It also allows us to package up our application ; as a standalone .jar or as a .war for deployment to a servlet container ; (I know... SO 2005). :plugins [[lein-ring "0.9.6"] [lein-environ "1.0.0"]] ; See https://github.com/weavejester/lein-ring#web-server-options for the ; various options available for the lein-ring plugin :ring {:handler elastic-ring.handler/app :port 3000 :nrepl {:start? true :port 9998}} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring-mock "0.1.5"]] ; Since we are using environ, we can override these values with ; environment variables in production. :env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "pass"}} :test {:env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "pass"}}})
109066
(defproject mini-restful "0.1.2-SNAPSHOT" :description "An example RESTful application written in Clojure using elasticseach as back-end" :url "https://github.com/nikos/elastic-ring" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.logging "0.3.1"] ;; HTTP handling [ring/ring-core "1.4.0"] [ring/ring-jetty-adapter "1.4.0"] [ring/ring-json "0.4.0"] [compojure "1.4.0"] ;; schema validation [prismatic/schema "0.4.3"] ;; elasticsearch driver [clojurewerkz/elastisch "2.2.0-beta4"] [clj-time "0.11.0"] [cheshire "5.5.0"] [environ "1.0.0"] [buddy/buddy-hashers "0.6.0"] [buddy/buddy-auth "0.6.0"] [crypto-random "1.2.0"]] ; The lein-ring plugin allows us to easily start a development web server ; with "lein ring server". It also allows us to package up our application ; as a standalone .jar or as a .war for deployment to a servlet container ; (I know... SO 2005). :plugins [[lein-ring "0.9.6"] [lein-environ "1.0.0"]] ; See https://github.com/weavejester/lein-ring#web-server-options for the ; various options available for the lein-ring plugin :ring {:handler elastic-ring.handler/app :port 3000 :nrepl {:start? true :port 9998}} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring-mock "0.1.5"]] ; Since we are using environ, we can override these values with ; environment variables in production. :env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "<PASSWORD>"}} :test {:env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "<PASSWORD>"}}})
true
(defproject mini-restful "0.1.2-SNAPSHOT" :description "An example RESTful application written in Clojure using elasticseach as back-end" :url "https://github.com/nikos/elastic-ring" :license {:name "MIT" :url "http://opensource.org/licenses/MIT"} :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.logging "0.3.1"] ;; HTTP handling [ring/ring-core "1.4.0"] [ring/ring-jetty-adapter "1.4.0"] [ring/ring-json "0.4.0"] [compojure "1.4.0"] ;; schema validation [prismatic/schema "0.4.3"] ;; elasticsearch driver [clojurewerkz/elastisch "2.2.0-beta4"] [clj-time "0.11.0"] [cheshire "5.5.0"] [environ "1.0.0"] [buddy/buddy-hashers "0.6.0"] [buddy/buddy-auth "0.6.0"] [crypto-random "1.2.0"]] ; The lein-ring plugin allows us to easily start a development web server ; with "lein ring server". It also allows us to package up our application ; as a standalone .jar or as a .war for deployment to a servlet container ; (I know... SO 2005). :plugins [[lein-ring "0.9.6"] [lein-environ "1.0.0"]] ; See https://github.com/weavejester/lein-ring#web-server-options for the ; various options available for the lein-ring plugin :ring {:handler elastic-ring.handler/app :port 3000 :nrepl {:start? true :port 9998}} :profiles {:dev {:dependencies [[javax.servlet/servlet-api "2.5"] [ring-mock "0.1.5"]] ; Since we are using environ, we can override these values with ; environment variables in production. :env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "PI:PASSWORD:<PASSWORD>END_PI"}} :test {:env {:elastic-url "http://127.0.0.1:9200" :elastic-user "user" :elastic-pass "PI:PASSWORD:<PASSWORD>END_PI"}}})
[ { "context": "(ns ^{:author \"Imre Koszo\"}\nyada.process-request-body-test\n (:require\n ", "end": 25, "score": 0.9998866319656372, "start": 15, "tag": "NAME", "value": "Imre Koszo" } ]
bundles/full/test/yada/process_request_body_test.clj
danielcompton/yada
0
(ns ^{:author "Imre Koszo"} yada.process-request-body-test (:require [clojure.test :refer :all :exclude [deftest]] [cheshire.core :as json] [schema.core :as s] [schema.test :refer [deftest]] [yada.interceptors :as i] [yada.resource :refer [resource]] [yada.request-body :refer [process-request-body]] [byte-streams :as bs] [schema.coerce :as sc] [cognitect.transit :as transit]) (:import (clojure.lang ExceptionInfo Keyword) (java.io ByteArrayOutputStream))) (defmacro is-coercing-correctly? [expected value content-type] `(let [expected# ~expected res# (process-request-body {} ~value ~content-type)] (is (= {:body expected#} res#)))) (declare thrown?) (def ^:private test-map {:a "Hello" :b :foo :c [4 5 6]}) (deftest coerce-request-body-test (let [content-type "application/json" s "{\"a\": \"Hello\", \"b\": \"foo\", \"c\": [4, 5, 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? (update test-map :b name) s content-type))) (let [content-type "application/edn" s "{:a \"Hello\" :b :foo :c [4 5 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? test-map s content-type)))) (defn post-resource [resource body content-type] (let [ctx {:method :post :request {:headers {"content-length" (str (count (bs/to-byte-array body))) "content-type" content-type} :body (bs/to-input-stream body)} :resource resource}] (i/process-request-body ctx))) (defn process-body ([content-type body-schema body] (process-body content-type body-schema nil body)) ([content-type body-schema body-matcher body] (post-resource (resource {:methods {:post (merge {:consumes content-type :parameters {:body body-schema} :response ""} (when body-matcher {:coercion-matchers {:body body-matcher}}))}}) body content-type))) (def process-json-body (partial process-body "application/json")) (def process-edn-body (partial process-body "application/edn")) (def process-plaintext-body (partial process-body "text/plain")) (def process-transit-json-body (partial process-body "application/transit+json")) (def process-transit-msgpack-body (partial process-body "application/transit+msgpack")) ;; TODO: test 400 errors ;; TODO: transit (deftest json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-json-body {:foo s/Str} (json/encode {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo s/Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo (s/eq :yoyo)} (json/encode {:foo :yoyo})) [:parameters :body]))) (let [processed (process-json-body {:foo (s/enum :yoyo :bar)} (json/encode {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo "yoyo"} (get-in processed [:body])))) (is (= 5 (get-in (process-json-body s/Int (json/encode 5)) [:parameters :body]))) (let [processed (process-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (json/encode {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-json-body {:foo s/Str} (json/encode {:foo 123})) [:parameters :body]))))) (deftest edn-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-edn-body {:foo s/Str} (pr-str {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo s/Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo (s/eq :yoyo)} (pr-str {:foo :yoyo})) [:parameters :body]))) (let [processed (process-edn-body {:foo (s/enum :yoyo :bar)} (pr-str {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-edn-body s/Int (pr-str 5)) [:parameters :body]))) (let [processed (process-edn-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (pr-str {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-edn-body {:foo s/Str} (pr-str {:foo 123})) [:parameters :body]))))) (deftest plaintext-test (testing "happy path" (is (= "foo" (get-in (process-plaintext-body s/Str "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body s/Keyword "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body Keyword "foo") [:parameters :body]))) (is (= :yoyo (get-in (process-plaintext-body (s/eq :yoyo) "yoyo") [:parameters :body]))) (let [processed (process-plaintext-body s/Int "5")] (is (= 5 (get-in processed [:parameters :body]))) (is (= "5" (get-in processed [:body])))) (let [processed (process-plaintext-body s/Int #(when (= s/Int %) (constantly 1234)) "9999")] (is (= 1234 (get-in processed [:parameters :body]))) (is (= "9999" (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-plaintext-body {:foo s/Str} "1234") [:parameters :body]))))) (defn- transit-encode [type v] (let [baos (ByteArrayOutputStream. 100)] (transit/write (transit/writer baos type) v) (.toByteArray baos))) (def ^:private transit-json (partial transit-encode :json)) (def ^:private transit-msgpack (partial transit-encode :msgpack)) (deftest transit-json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo s/Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo (s/eq :yoyo)} (transit-json {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-json-body {:foo (s/enum :yoyo :bar)} (transit-json {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-json-body s/Int (transit-json 5)) [:parameters :body]))) (let [processed (process-transit-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-json {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo 123})) [:parameters :body]))))) (deftest transit-msgpack-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo s/Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo (s/eq :yoyo)} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo (s/enum :yoyo :bar)} (transit-msgpack {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-msgpack-body s/Int (transit-msgpack 5)) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-msgpack {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo 123})) [:parameters :body])))))
105226
(ns ^{:author "<NAME>"} yada.process-request-body-test (:require [clojure.test :refer :all :exclude [deftest]] [cheshire.core :as json] [schema.core :as s] [schema.test :refer [deftest]] [yada.interceptors :as i] [yada.resource :refer [resource]] [yada.request-body :refer [process-request-body]] [byte-streams :as bs] [schema.coerce :as sc] [cognitect.transit :as transit]) (:import (clojure.lang ExceptionInfo Keyword) (java.io ByteArrayOutputStream))) (defmacro is-coercing-correctly? [expected value content-type] `(let [expected# ~expected res# (process-request-body {} ~value ~content-type)] (is (= {:body expected#} res#)))) (declare thrown?) (def ^:private test-map {:a "Hello" :b :foo :c [4 5 6]}) (deftest coerce-request-body-test (let [content-type "application/json" s "{\"a\": \"Hello\", \"b\": \"foo\", \"c\": [4, 5, 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? (update test-map :b name) s content-type))) (let [content-type "application/edn" s "{:a \"Hello\" :b :foo :c [4 5 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? test-map s content-type)))) (defn post-resource [resource body content-type] (let [ctx {:method :post :request {:headers {"content-length" (str (count (bs/to-byte-array body))) "content-type" content-type} :body (bs/to-input-stream body)} :resource resource}] (i/process-request-body ctx))) (defn process-body ([content-type body-schema body] (process-body content-type body-schema nil body)) ([content-type body-schema body-matcher body] (post-resource (resource {:methods {:post (merge {:consumes content-type :parameters {:body body-schema} :response ""} (when body-matcher {:coercion-matchers {:body body-matcher}}))}}) body content-type))) (def process-json-body (partial process-body "application/json")) (def process-edn-body (partial process-body "application/edn")) (def process-plaintext-body (partial process-body "text/plain")) (def process-transit-json-body (partial process-body "application/transit+json")) (def process-transit-msgpack-body (partial process-body "application/transit+msgpack")) ;; TODO: test 400 errors ;; TODO: transit (deftest json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-json-body {:foo s/Str} (json/encode {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo s/Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo (s/eq :yoyo)} (json/encode {:foo :yoyo})) [:parameters :body]))) (let [processed (process-json-body {:foo (s/enum :yoyo :bar)} (json/encode {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo "yoyo"} (get-in processed [:body])))) (is (= 5 (get-in (process-json-body s/Int (json/encode 5)) [:parameters :body]))) (let [processed (process-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (json/encode {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-json-body {:foo s/Str} (json/encode {:foo 123})) [:parameters :body]))))) (deftest edn-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-edn-body {:foo s/Str} (pr-str {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo s/Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo (s/eq :yoyo)} (pr-str {:foo :yoyo})) [:parameters :body]))) (let [processed (process-edn-body {:foo (s/enum :yoyo :bar)} (pr-str {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-edn-body s/Int (pr-str 5)) [:parameters :body]))) (let [processed (process-edn-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (pr-str {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-edn-body {:foo s/Str} (pr-str {:foo 123})) [:parameters :body]))))) (deftest plaintext-test (testing "happy path" (is (= "foo" (get-in (process-plaintext-body s/Str "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body s/Keyword "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body Keyword "foo") [:parameters :body]))) (is (= :yoyo (get-in (process-plaintext-body (s/eq :yoyo) "yoyo") [:parameters :body]))) (let [processed (process-plaintext-body s/Int "5")] (is (= 5 (get-in processed [:parameters :body]))) (is (= "5" (get-in processed [:body])))) (let [processed (process-plaintext-body s/Int #(when (= s/Int %) (constantly 1234)) "9999")] (is (= 1234 (get-in processed [:parameters :body]))) (is (= "9999" (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-plaintext-body {:foo s/Str} "1234") [:parameters :body]))))) (defn- transit-encode [type v] (let [baos (ByteArrayOutputStream. 100)] (transit/write (transit/writer baos type) v) (.toByteArray baos))) (def ^:private transit-json (partial transit-encode :json)) (def ^:private transit-msgpack (partial transit-encode :msgpack)) (deftest transit-json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo s/Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo (s/eq :yoyo)} (transit-json {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-json-body {:foo (s/enum :yoyo :bar)} (transit-json {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-json-body s/Int (transit-json 5)) [:parameters :body]))) (let [processed (process-transit-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-json {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo 123})) [:parameters :body]))))) (deftest transit-msgpack-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo s/Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo (s/eq :yoyo)} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo (s/enum :yoyo :bar)} (transit-msgpack {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-msgpack-body s/Int (transit-msgpack 5)) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-msgpack {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo 123})) [:parameters :body])))))
true
(ns ^{:author "PI:NAME:<NAME>END_PI"} yada.process-request-body-test (:require [clojure.test :refer :all :exclude [deftest]] [cheshire.core :as json] [schema.core :as s] [schema.test :refer [deftest]] [yada.interceptors :as i] [yada.resource :refer [resource]] [yada.request-body :refer [process-request-body]] [byte-streams :as bs] [schema.coerce :as sc] [cognitect.transit :as transit]) (:import (clojure.lang ExceptionInfo Keyword) (java.io ByteArrayOutputStream))) (defmacro is-coercing-correctly? [expected value content-type] `(let [expected# ~expected res# (process-request-body {} ~value ~content-type)] (is (= {:body expected#} res#)))) (declare thrown?) (def ^:private test-map {:a "Hello" :b :foo :c [4 5 6]}) (deftest coerce-request-body-test (let [content-type "application/json" s "{\"a\": \"Hello\", \"b\": \"foo\", \"c\": [4, 5, 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? (update test-map :b name) s content-type))) (let [content-type "application/edn" s "{:a \"Hello\" :b :foo :c [4 5 6]}"] (testing (str "coercing " content-type) (is-coercing-correctly? test-map s content-type)))) (defn post-resource [resource body content-type] (let [ctx {:method :post :request {:headers {"content-length" (str (count (bs/to-byte-array body))) "content-type" content-type} :body (bs/to-input-stream body)} :resource resource}] (i/process-request-body ctx))) (defn process-body ([content-type body-schema body] (process-body content-type body-schema nil body)) ([content-type body-schema body-matcher body] (post-resource (resource {:methods {:post (merge {:consumes content-type :parameters {:body body-schema} :response ""} (when body-matcher {:coercion-matchers {:body body-matcher}}))}}) body content-type))) (def process-json-body (partial process-body "application/json")) (def process-edn-body (partial process-body "application/edn")) (def process-plaintext-body (partial process-body "text/plain")) (def process-transit-json-body (partial process-body "application/transit+json")) (def process-transit-msgpack-body (partial process-body "application/transit+msgpack")) ;; TODO: test 400 errors ;; TODO: transit (deftest json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-json-body {:foo s/Str} (json/encode {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo s/Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo Keyword} (json/encode {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-json-body {:foo (s/eq :yoyo)} (json/encode {:foo :yoyo})) [:parameters :body]))) (let [processed (process-json-body {:foo (s/enum :yoyo :bar)} (json/encode {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo "yoyo"} (get-in processed [:body])))) (is (= 5 (get-in (process-json-body s/Int (json/encode 5)) [:parameters :body]))) (let [processed (process-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (json/encode {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-json-body {:foo s/Str} (json/encode {:foo 123})) [:parameters :body]))))) (deftest edn-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-edn-body {:foo s/Str} (pr-str {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo s/Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo Keyword} (pr-str {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-edn-body {:foo (s/eq :yoyo)} (pr-str {:foo :yoyo})) [:parameters :body]))) (let [processed (process-edn-body {:foo (s/enum :yoyo :bar)} (pr-str {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-edn-body s/Int (pr-str 5)) [:parameters :body]))) (let [processed (process-edn-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (pr-str {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-edn-body {:foo s/Str} (pr-str {:foo 123})) [:parameters :body]))))) (deftest plaintext-test (testing "happy path" (is (= "foo" (get-in (process-plaintext-body s/Str "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body s/Keyword "foo") [:parameters :body]))) (is (= :foo (get-in (process-plaintext-body Keyword "foo") [:parameters :body]))) (is (= :yoyo (get-in (process-plaintext-body (s/eq :yoyo) "yoyo") [:parameters :body]))) (let [processed (process-plaintext-body s/Int "5")] (is (= 5 (get-in processed [:parameters :body]))) (is (= "5" (get-in processed [:body])))) (let [processed (process-plaintext-body s/Int #(when (= s/Int %) (constantly 1234)) "9999")] (is (= 1234 (get-in processed [:parameters :body]))) (is (= "9999" (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-plaintext-body {:foo s/Str} "1234") [:parameters :body]))))) (defn- transit-encode [type v] (let [baos (ByteArrayOutputStream. 100)] (transit/write (transit/writer baos type) v) (.toByteArray baos))) (def ^:private transit-json (partial transit-encode :json)) (def ^:private transit-msgpack (partial transit-encode :msgpack)) (deftest transit-json-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo s/Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo Keyword} (transit-json {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-json-body {:foo (s/eq :yoyo)} (transit-json {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-json-body {:foo (s/enum :yoyo :bar)} (transit-json {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-json-body s/Int (transit-json 5)) [:parameters :body]))) (let [processed (process-transit-json-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-json {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-json-body {:foo s/Str} (transit-json {:foo 123})) [:parameters :body]))))) (deftest transit-msgpack-test (testing "happy path" (is (= {:foo "bar"} (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo "bar"})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo s/Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo Keyword} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (is (= {:foo :yoyo} (get-in (process-transit-msgpack-body {:foo (s/eq :yoyo)} (transit-msgpack {:foo :yoyo})) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo (s/enum :yoyo :bar)} (transit-msgpack {:foo :yoyo}))] (is (= {:foo :yoyo} (get-in processed [:parameters :body]))) (is (= {:foo :yoyo} (get-in processed [:body])))) (is (= 5 (get-in (process-transit-msgpack-body s/Int (transit-msgpack 5)) [:parameters :body]))) (let [processed (process-transit-msgpack-body {:foo s/Int} #(when (= s/Int %) (constantly 1234)) (transit-msgpack {:foo 9999}))] (is (= {:foo 1234} (get-in processed [:parameters :body]))) (is (= {:foo 9999} (get-in processed [:body]))))) (testing "sad path" (is (thrown? ExceptionInfo (get-in (process-transit-msgpack-body {:foo s/Str} (transit-msgpack {:foo 123})) [:parameters :body])))))
[ { "context": "(ns\r\n ^{:author \"Chris Perkins\"\r\n :doc \"The Rapscallion XML generation and tr", "end": 31, "score": 0.9998588562011719, "start": 18, "tag": "NAME", "value": "Chris Perkins" } ]
src/rapscallion/core.clj
grammati/rapscallion
1
(ns ^{:author "Chris Perkins" :doc "The Rapscallion XML generation and transformation library."} rapscallion.core (:require (clojure (string :as string) (pprint :as pprint) (walk :as walk))) (:require (eksemel (xml :as xml))) (:require (imparsonate (core :as imp) (lib :as implib))) (:import (java.io Reader StringReader PushbackReader) (eksemel.xml Element)) ) (defn- compile-error [& messages] (throw (IllegalArgumentException. (apply str messages)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Extract embedded expressions from text (defn slurp-reader "Consume the given Reader and return its contents as a string." [#^Reader reader] (let [sb (StringBuilder.)] (loop [c (.read reader)] (if (neg? c) (.toString sb) (do (.append sb (char c)) (recur (.read reader))))))) (defn read-partial "Like (read s), but returns a 2-element vector of the form that was read and the remaining, unread portion of the string." [^String s] (let [rdr (PushbackReader. (StringReader. s))] [(read rdr) (slurp-reader rdr)])) (defn read-all [^String s] (loop [forms [] s s] (if (empty? s) forms (let [[form s] (read-partial s)] (recur (conj forms form) (.trim s)))))) (defn read-one [^String s] (let [[form & more] (read-all s)] (when more (compile-error "Expected exactly one clojure form - saw \"" s "\"")) form)) (defn- merge-adjacent-strings [col] (let [joiner #(if (string? (first %)) [(apply str %)] %) joined (map joiner (partition-by string? col))] (apply concat joined))) (defn extract-exprs "Extract embedded expressions from the string, returning a sequence of strings and forms." ([^String s] (extract-exprs s "$")) ([^String s ^String c] (let [pat (java.util.regex.Pattern/quote c)] (loop [parts [] s s] (let [[left ^String rest] (seq (.split s pat 2)) parts (if (not-empty left) (conj parts left) parts)] (cond (nil? rest) ; at the end (merge-adjacent-strings parts) (empty? rest) ; trailing $ (compile-error "Trailing " c ". Double it to insert a literal " c) (.startsWith rest c) ; doubled $$ == literal $ (recur (conj parts c) (.substring rest 1)) :else (let [brace? (.startsWith rest "{") rest (if brace? (.substring rest 1) rest) [form ^String right] (read-partial rest)] (when (and brace? (not (.startsWith right "}"))) (throw (Exception. "mismatched curly-bracket in embedded code"))) ; FIXME - exception class, line number, etc. (recur (conj parts form) (if brace? (.substring right 1) right))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; XML template language ; directives: ;name element attr notes ;---------------------------------------------------------------------- ;args no yes top-level element only? ;if yes yes <rap:if test="..."> ;for yes yes <rap:for expr="..."> ;let yes yes <rap:let bindings="..."> ;attrs no yes ;meta no yes ;defn yes yes <rap:defn fn="name [args]"> ;call yes yes <rap:call fn="name args"> ;match yes yes <rap:match xpath="foo/bar{:cool}"> (def ^:dynamic *strict* true) ; for debugging - don't change this to false unless you know what you're doing (def ^:dynamic *keep-whitespace* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Each value that is substituted into a template gets passed through ;; this multimethod. Eg: ;; <foo>Hello ${name}</foo> ;; compiles to ;; (Element. :foo nil ["Hello " (xml-value name)]) (defmulti xml-value type) ;; The default is just to stringify the object. (defmethod xml-value :default [x] (str x)) ;; Elements are inserted as-is. (defmethod xml-value Element [x] x) (defmethod xml-value clojure.lang.Sequential [x] (map xml-value x)) ;; This is a special case that handles "call-with-content". ;; Example: ;; <rap:call fn='foo'> ;; <bar>Hi</bar> ;; </rap:call> ;; This generates code that will call "foo" with one parameter - a fn ;; that returns (Element. :bar nil ["Hi"]). That fn is flagged in its ;; metadata as a :call-body. Inside the definition of "foo", it can ;; be inserted as either $x or $(x) (assuming it is bound to "x" ;; inside foo). Why? Consider the definition of foo: ;; <rap:defn fn='foo [x]'> ;; <wrap>$x</wrap> ;; <rap:defn> ;; The author of this function cannot know whether to use $x or $(x), ;; because he doesn't know how it will be called: ;; $(foo 23) ;; <rap:call fn='foo'>...etc...</rap:call> ;; (defmethod xml-value ::call-body [f] (f)) (defmulti compile-xml type) (defmethod compile-xml String [s] (let [s (if *keep-whitespace* s (string/trim s)) parts (extract-exprs s)] (if (and (= 1 (count parts)) (string? (first parts))) (first parts) (vec (for [p parts] (if (string? p) p `(xml-value ~p))))))) (defn flatseq [& cols] (filter (complement nil?) (flatten cols))) (defn process-attr [v] (let [v (extract-exprs v)] (if (> (count v) 1) `(str ~@v) (first v)))) (defn process-attrs [elt] (assoc elt :attrs (into {} (for [[k v] (:attrs elt)] [k (process-attr v)])))) (defn directive? [elt] (.startsWith (name (:tag elt)) "rap:")) ; FIXME - use xmlns (defn- strip-ns [qname] (-> qname name (.split ":" 2) second keyword)) (defmulti compile-directive (fn ([elt] (when-not (directive? elt) (compile-error "compile-directive called, but element is not a directive. tag: " (:tag elt))) (strip-ns (:tag elt))) ([tag & _] tag))) (defmethod compile-directive :default [elt] (compile-error "Unknown directive: " (:tag elt))) (defn pop-directive-attrs "Given a directive-element and an attribute name, returns a two-element vector of the element with the attribute removed, and the attribute parsed into clojure forms." [elt attr] (let [tag (:tag elt) [elt expr] (xml/pop-attr elt attr)] (when (empty? expr) (compile-error "Attribute " attr " is required on directive " tag)) (when (not-empty (:attrs elt)) (compile-error "Unsupported attibutes on " tag " directive: " (string/join " " (keys (:attrs elt))))) [elt (read-all expr)])) (defmethod compile-directive :let ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :let bindings (:content elt)))) ([_ bindings body] `(let [~@bindings] ~body))) (defmethod compile-directive :if ([elt] (let [[elt test] (pop-directive-attrs elt :test)] (compile-directive :if test (:content elt)))) ([_ [test & more :as exprs] body] (when more (compile-error "Only one form is allowed as the 'test' attribute of an :if directive. Found: " exprs)) `(if ~test ~body))) (defmethod compile-directive :for ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :for bindings (:content elt)))) ([_ bindings body] `(for [~@bindings] ~body))) (defmethod compile-directive :attrs ([elt] (compile-error "Directive :attrs is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":attrs directive must be a single form - saw " exprs)) `(xml/merge-attrs ~elt ~expr))) (defn merge-meta [obj m] (with-meta obj (into (or (meta obj) {}) (if (keyword? m) {m true} m)))) (defmethod compile-directive :meta ([elt] (compile-error "Directive :meta is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":meta directive must be a single form - saw " exprs)) `(merge-meta ~elt ~expr))) (defmethod compile-directive :call ([elt] (let [[elt body-args] (xml/pop-attr elt :args) body-args (and body-args (read-all body-args)) [elt fn-and-args] (pop-directive-attrs elt :fn)] (compile-directive :call fn-and-args (:content elt) body-args))) ([elt fn-and-args body] (compile-directive elt fn-and-args body nil)) ([_ [f & args] body body-args] `(~f ~@args (with-meta (fn [~@body-args] ~body) {:type ::call-body})))) (comment ;; hypothetical syntax for defdirective (defdirective :call :as-attribute :fn :as-element {:attributes [:fn :args] })) (defn compile-element [elt] (if (directive? elt) (compile-directive elt) elt)) (defn extract-directives "Pull rap: directives out of the :attrs map and put them in metadata instead." [elt] (let [is-directive (fn [[k v]] (.startsWith (name k) "rap:")) ; FIXME - use xmlns attrs (:attrs elt) directives (filter is-directive attrs) directives (into {} (for [[k v] directives] [(strip-ns k) (read-all v)])) attrs (into {} (filter (complement is-directive) attrs)) elt (assoc elt :attrs attrs)] (vary-meta elt assoc :directives directives))) (defn pop-directive [elt name] (let [directives (:directives (meta elt)) value (get directives name) directives (dissoc directives name) elt (vary-meta elt assoc :directives directives)] [elt value])) (def ^:dynamic *directives* (atom [{:name :attrs} {:name :meta} {:name :call} {:name :let} {:name :if} {:name :for} {:name :include} ])) (defn apply-directives "Given an element, return the element with any directives attached as attributes compiled." ([elt] (apply-directives elt @*directives*)) ([elt directives] (let [directive-values (:directives (meta elt)) elt (vary-meta elt dissoc :directives) body (compile-element elt)] (loop [directive-values directive-values body body [next-directive & directives] directives] (if (empty? directive-values) body ;; done - all directives attached to this element have been processed (if-not next-directive (when *strict* (compile-error "Unprocessed directives on element " (:tag elt) " (" (string/join ", " (keys directive-values)) ").")) (let [directive-name (:name next-directive) directive-value (get directive-values directive-name)] (recur (dissoc directive-values directive-name) (if directive-value (compile-directive directive-name directive-value body) body) directives)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:defn (defn- defn? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:defn) (get-in elt [:attrs :rap:defn])))) (defn- make-defn [elt] (if (= (:tag elt) :rap:defn) (let [[elt fnspec] (pop-directive-attrs elt :fn)] `(~@fnspec (flatseq ~@(map compile-xml (:content elt))))) (let [[elt fnspec] (xml/pop-attr elt :rap:defn) [name argvec] (read-all fnspec)] `(~name [~@argvec] ~(compile-xml elt))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:match (imp/defparser match-expr-parser :root :path :path #{:relpath :abspath} :abspath ["/" :relpat] :relpath (imp/list-of :elt "/") :elt [#{:tag "*"} :filter*] :tag #"[\w-]+" keyword :filter #{:xml-filter :clj-filter} :xml-filter ["[" :attr-filter "]"] :attr-filter ["@" :attrname ["=" :quoted-string]:?] (fn [n v] {:type :attr :name (keyword n) :value v}) :attrname #"[\w-]+" ;FIXME :quoted-string implib/double-quoted-string :clj-filter ["{" :clj-form "}"] (fn [form] {:type :expr :form form}) :clj-form read-partial ) (defn compile-element-filter [[tag filters]] (let [elt-sym (gensym "elt")] `(fn [~elt-sym] (and (= ~tag (:tag ~elt-sym)) ~@(for [{type :type :as f} filters] (case type :attr (if-let [v (:value f)] `(= ~v (get-in ~elt-sym [:attrs ~(:name f)])) `(not (nil? (get-in ~elt-sym [:attrs ~(:name f)])))) :expr `(~(:form f) (meta ~elt-sym)))))))) (defn compile-match-expression "" [expr] {:pre [(not (empty? expr))]} (map compile-element-filter (match-expr-parser expr))) (defn matcher? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:match) (get-in elt [:attrs :rap:match])))) (defn- map-content [elt f] (assoc elt :content (flatseq (map f (:content elt))))) (defn set-content [elt & content] (assoc elt :content (flatseq content))) (defn append-content [elt & new-content] (apply set-content elt (:content elt) new-content)) (defn match-filter "Build code for a function that will replace elements matching the given expression with the return value of replacer." [[match-fn & more-fns] replacer recursive?] (fn m [elt] (if (xml/element? elt) (if (match-fn elt) (if more-fns (-> elt (map-content (match-filter more-fns replacer false)) (map-content m)) (replacer elt)) (if recursive? (map-content elt m) elt)) elt))) (defn compile-matcher ([expr body action as-sym] (let [action (keyword (or action :replace)) as-sym (or as-sym (gensym "matched-element")) as-sym (if (string? as-sym) (read-one as-sym) as-sym) body (into [] (map compile-xml body)) expr (string/trim expr) [expr recursive?] (if (.startsWith expr "/") [(.substring expr 1) false] [expr true]) exprs (compile-match-expression expr) fn-body (case action :replace body :append `(append-content ~as-sym ~@body) (compile-error "Unknown value for 'action' attribute on rap:match elment: " action))] `(match-filter [~@exprs] (fn [~as-sym] ~fn-body) ~recursive?)))) (defn make-matcher [elt] (if (= (:tag elt) :rap:match) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :expr :action :as)] (when-not expr (compile-error "Attribute :expr is required on rap:match element.")) (when-not (empty? (:attrs elt)) (compile-error "Unrecognized attributes on rap:match element:" (keys (:attrs elt)))) (compile-matcher expr (:content elt) action as-sym)) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :rap:match :rap:action :rap:as)] (compile-matcher expr [elt] action as-sym)))) (defn compile-content "" [content] (let [[elt & more :as content] content] (cond (nil? elt) nil (defn? elt) (let [[defns others] (split-with defn? content)] `(letfn [~@(map make-defn defns)] ~(compile-content others))) (matcher? elt) `(let [matcher# ~(make-matcher elt)] (map matcher# ~(compile-content more))) :else `[~(compile-xml elt) ~@(compile-content more)]))) (defn process-content [elt] (let [compiled (compile-content (:content elt)) compiled (if (nil? compiled) nil `(flatseq ~compiled))] ;TODO - be smarter here (assoc elt :content compiled))) (defmethod compile-xml Element [elt] (-> elt extract-directives process-content process-attrs apply-directives )) (defn- de-elementize "We work with Element instances at compile-time, but they do not self-evaluate like normal maps do. Convert them into an eval-able form." ;; TODO - I don't think I need this in clojure 1.3+ ... confirm. [x] (walk/prewalk (fn [e] (if (xml/element? e) (list `xml/element (:tag e) (:attrs e) (:content e)) e)) x)) (defn to-template-fn "Given a template, returns a data structure that can be eval-ed into a function." [xml-in] (let [roots (xml/parse xml-in xml/old-parse-options) ;TODO root (first (filter xml/element? roots)) [root [args requires uses imports]] (xml/pop-attrs root :rap:args :rap:require :rap:use :rap:import) args (read-all args) roots (if (= (:tag root) :rap:template) (:content root) [root]) compiled (into [] (map #(-> % compile-xml de-elementize) roots)) ] `(do ~@(for [lib (read-all requires)] `(require '~lib)) ~@(for [lib (read-all uses)] `(use '~lib)) ~@(for [lib (read-all imports)] `(import '~lib)) (fn template-main# ([context#] (template-main# context# nil)) ([{:keys [~@args]} in#] [~@compiled in#]))))) (defn dump "Print the code generated for the given XML template." [template] (pprint/pprint (to-template-fn template))) (declare ^:dynamic *template-ns*) (defn- eval-in-ns "Eval the " ([form] (eval-in-ns form *template-ns*)) ([form ns-or-name] (binding [*ns* (if (symbol? ns-or-name) (create-ns ns-or-name) ns-or-name)] (eval form)))) ; Namespace in which to eval templates (defonce ^:dynamic *template-ns* (let [ns-name (gensym "template-ns")] (eval-in-ns '(clojure.core/with-loading-context (clojure.core/refer 'clojure.core)) ns-name) (find-ns ns-name))) (defn compile-template "Compiles the template into a function that takes a context-map as input and produces a tree of Elements." [xml-in] (-> xml-in to-template-fn eval-in-ns (with-meta {::template-fn true ::template-source xml-in}) )) (defn template? [template] (::template-fn (meta template))) (defmacro locals [] (into {} (for [[k _] &env] [(keyword k) k]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public API (declare ^:dynamic *template-loader*) (defn template-loader "Returns a function that will return template, given a string (path or XML)." [root] (let [cache (atom nil)] ^{:root root} (fn loader [source] (if (and (string? source) (.startsWith source "<")) (compile-template source) ;don't cache strings (let [path (string/join "/" [(or root \.) source]) f (java.io.File. path) mod-t (.lastModified f) [cached-template cached-mod-t] (get @cache path)] (if (= cached-mod-t mod-t) cached-template (let [compiled (binding [*template-loader* loader] (compile-template f))] (swap! cache assoc path [compiled mod-t]) compiled))))))) (def ^:dynamic *template-loader* (template-loader nil)) (defn template "Returns a compiled template, either by compiling it or by getting it from the template cache." [source] (*template-loader* source)) (defn render "Render a template as a string of XML" ([template] (render template {})) ([template context] (let [tmpl (if (template? template) template (compile-template template)) elts (tmpl context)] (xml/emit elts)))) (defmacro render-with-locals [template] `(render ~template (locals)))
72024
(ns ^{:author "<NAME>" :doc "The Rapscallion XML generation and transformation library."} rapscallion.core (:require (clojure (string :as string) (pprint :as pprint) (walk :as walk))) (:require (eksemel (xml :as xml))) (:require (imparsonate (core :as imp) (lib :as implib))) (:import (java.io Reader StringReader PushbackReader) (eksemel.xml Element)) ) (defn- compile-error [& messages] (throw (IllegalArgumentException. (apply str messages)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Extract embedded expressions from text (defn slurp-reader "Consume the given Reader and return its contents as a string." [#^Reader reader] (let [sb (StringBuilder.)] (loop [c (.read reader)] (if (neg? c) (.toString sb) (do (.append sb (char c)) (recur (.read reader))))))) (defn read-partial "Like (read s), but returns a 2-element vector of the form that was read and the remaining, unread portion of the string." [^String s] (let [rdr (PushbackReader. (StringReader. s))] [(read rdr) (slurp-reader rdr)])) (defn read-all [^String s] (loop [forms [] s s] (if (empty? s) forms (let [[form s] (read-partial s)] (recur (conj forms form) (.trim s)))))) (defn read-one [^String s] (let [[form & more] (read-all s)] (when more (compile-error "Expected exactly one clojure form - saw \"" s "\"")) form)) (defn- merge-adjacent-strings [col] (let [joiner #(if (string? (first %)) [(apply str %)] %) joined (map joiner (partition-by string? col))] (apply concat joined))) (defn extract-exprs "Extract embedded expressions from the string, returning a sequence of strings and forms." ([^String s] (extract-exprs s "$")) ([^String s ^String c] (let [pat (java.util.regex.Pattern/quote c)] (loop [parts [] s s] (let [[left ^String rest] (seq (.split s pat 2)) parts (if (not-empty left) (conj parts left) parts)] (cond (nil? rest) ; at the end (merge-adjacent-strings parts) (empty? rest) ; trailing $ (compile-error "Trailing " c ". Double it to insert a literal " c) (.startsWith rest c) ; doubled $$ == literal $ (recur (conj parts c) (.substring rest 1)) :else (let [brace? (.startsWith rest "{") rest (if brace? (.substring rest 1) rest) [form ^String right] (read-partial rest)] (when (and brace? (not (.startsWith right "}"))) (throw (Exception. "mismatched curly-bracket in embedded code"))) ; FIXME - exception class, line number, etc. (recur (conj parts form) (if brace? (.substring right 1) right))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; XML template language ; directives: ;name element attr notes ;---------------------------------------------------------------------- ;args no yes top-level element only? ;if yes yes <rap:if test="..."> ;for yes yes <rap:for expr="..."> ;let yes yes <rap:let bindings="..."> ;attrs no yes ;meta no yes ;defn yes yes <rap:defn fn="name [args]"> ;call yes yes <rap:call fn="name args"> ;match yes yes <rap:match xpath="foo/bar{:cool}"> (def ^:dynamic *strict* true) ; for debugging - don't change this to false unless you know what you're doing (def ^:dynamic *keep-whitespace* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Each value that is substituted into a template gets passed through ;; this multimethod. Eg: ;; <foo>Hello ${name}</foo> ;; compiles to ;; (Element. :foo nil ["Hello " (xml-value name)]) (defmulti xml-value type) ;; The default is just to stringify the object. (defmethod xml-value :default [x] (str x)) ;; Elements are inserted as-is. (defmethod xml-value Element [x] x) (defmethod xml-value clojure.lang.Sequential [x] (map xml-value x)) ;; This is a special case that handles "call-with-content". ;; Example: ;; <rap:call fn='foo'> ;; <bar>Hi</bar> ;; </rap:call> ;; This generates code that will call "foo" with one parameter - a fn ;; that returns (Element. :bar nil ["Hi"]). That fn is flagged in its ;; metadata as a :call-body. Inside the definition of "foo", it can ;; be inserted as either $x or $(x) (assuming it is bound to "x" ;; inside foo). Why? Consider the definition of foo: ;; <rap:defn fn='foo [x]'> ;; <wrap>$x</wrap> ;; <rap:defn> ;; The author of this function cannot know whether to use $x or $(x), ;; because he doesn't know how it will be called: ;; $(foo 23) ;; <rap:call fn='foo'>...etc...</rap:call> ;; (defmethod xml-value ::call-body [f] (f)) (defmulti compile-xml type) (defmethod compile-xml String [s] (let [s (if *keep-whitespace* s (string/trim s)) parts (extract-exprs s)] (if (and (= 1 (count parts)) (string? (first parts))) (first parts) (vec (for [p parts] (if (string? p) p `(xml-value ~p))))))) (defn flatseq [& cols] (filter (complement nil?) (flatten cols))) (defn process-attr [v] (let [v (extract-exprs v)] (if (> (count v) 1) `(str ~@v) (first v)))) (defn process-attrs [elt] (assoc elt :attrs (into {} (for [[k v] (:attrs elt)] [k (process-attr v)])))) (defn directive? [elt] (.startsWith (name (:tag elt)) "rap:")) ; FIXME - use xmlns (defn- strip-ns [qname] (-> qname name (.split ":" 2) second keyword)) (defmulti compile-directive (fn ([elt] (when-not (directive? elt) (compile-error "compile-directive called, but element is not a directive. tag: " (:tag elt))) (strip-ns (:tag elt))) ([tag & _] tag))) (defmethod compile-directive :default [elt] (compile-error "Unknown directive: " (:tag elt))) (defn pop-directive-attrs "Given a directive-element and an attribute name, returns a two-element vector of the element with the attribute removed, and the attribute parsed into clojure forms." [elt attr] (let [tag (:tag elt) [elt expr] (xml/pop-attr elt attr)] (when (empty? expr) (compile-error "Attribute " attr " is required on directive " tag)) (when (not-empty (:attrs elt)) (compile-error "Unsupported attibutes on " tag " directive: " (string/join " " (keys (:attrs elt))))) [elt (read-all expr)])) (defmethod compile-directive :let ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :let bindings (:content elt)))) ([_ bindings body] `(let [~@bindings] ~body))) (defmethod compile-directive :if ([elt] (let [[elt test] (pop-directive-attrs elt :test)] (compile-directive :if test (:content elt)))) ([_ [test & more :as exprs] body] (when more (compile-error "Only one form is allowed as the 'test' attribute of an :if directive. Found: " exprs)) `(if ~test ~body))) (defmethod compile-directive :for ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :for bindings (:content elt)))) ([_ bindings body] `(for [~@bindings] ~body))) (defmethod compile-directive :attrs ([elt] (compile-error "Directive :attrs is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":attrs directive must be a single form - saw " exprs)) `(xml/merge-attrs ~elt ~expr))) (defn merge-meta [obj m] (with-meta obj (into (or (meta obj) {}) (if (keyword? m) {m true} m)))) (defmethod compile-directive :meta ([elt] (compile-error "Directive :meta is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":meta directive must be a single form - saw " exprs)) `(merge-meta ~elt ~expr))) (defmethod compile-directive :call ([elt] (let [[elt body-args] (xml/pop-attr elt :args) body-args (and body-args (read-all body-args)) [elt fn-and-args] (pop-directive-attrs elt :fn)] (compile-directive :call fn-and-args (:content elt) body-args))) ([elt fn-and-args body] (compile-directive elt fn-and-args body nil)) ([_ [f & args] body body-args] `(~f ~@args (with-meta (fn [~@body-args] ~body) {:type ::call-body})))) (comment ;; hypothetical syntax for defdirective (defdirective :call :as-attribute :fn :as-element {:attributes [:fn :args] })) (defn compile-element [elt] (if (directive? elt) (compile-directive elt) elt)) (defn extract-directives "Pull rap: directives out of the :attrs map and put them in metadata instead." [elt] (let [is-directive (fn [[k v]] (.startsWith (name k) "rap:")) ; FIXME - use xmlns attrs (:attrs elt) directives (filter is-directive attrs) directives (into {} (for [[k v] directives] [(strip-ns k) (read-all v)])) attrs (into {} (filter (complement is-directive) attrs)) elt (assoc elt :attrs attrs)] (vary-meta elt assoc :directives directives))) (defn pop-directive [elt name] (let [directives (:directives (meta elt)) value (get directives name) directives (dissoc directives name) elt (vary-meta elt assoc :directives directives)] [elt value])) (def ^:dynamic *directives* (atom [{:name :attrs} {:name :meta} {:name :call} {:name :let} {:name :if} {:name :for} {:name :include} ])) (defn apply-directives "Given an element, return the element with any directives attached as attributes compiled." ([elt] (apply-directives elt @*directives*)) ([elt directives] (let [directive-values (:directives (meta elt)) elt (vary-meta elt dissoc :directives) body (compile-element elt)] (loop [directive-values directive-values body body [next-directive & directives] directives] (if (empty? directive-values) body ;; done - all directives attached to this element have been processed (if-not next-directive (when *strict* (compile-error "Unprocessed directives on element " (:tag elt) " (" (string/join ", " (keys directive-values)) ").")) (let [directive-name (:name next-directive) directive-value (get directive-values directive-name)] (recur (dissoc directive-values directive-name) (if directive-value (compile-directive directive-name directive-value body) body) directives)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:defn (defn- defn? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:defn) (get-in elt [:attrs :rap:defn])))) (defn- make-defn [elt] (if (= (:tag elt) :rap:defn) (let [[elt fnspec] (pop-directive-attrs elt :fn)] `(~@fnspec (flatseq ~@(map compile-xml (:content elt))))) (let [[elt fnspec] (xml/pop-attr elt :rap:defn) [name argvec] (read-all fnspec)] `(~name [~@argvec] ~(compile-xml elt))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:match (imp/defparser match-expr-parser :root :path :path #{:relpath :abspath} :abspath ["/" :relpat] :relpath (imp/list-of :elt "/") :elt [#{:tag "*"} :filter*] :tag #"[\w-]+" keyword :filter #{:xml-filter :clj-filter} :xml-filter ["[" :attr-filter "]"] :attr-filter ["@" :attrname ["=" :quoted-string]:?] (fn [n v] {:type :attr :name (keyword n) :value v}) :attrname #"[\w-]+" ;FIXME :quoted-string implib/double-quoted-string :clj-filter ["{" :clj-form "}"] (fn [form] {:type :expr :form form}) :clj-form read-partial ) (defn compile-element-filter [[tag filters]] (let [elt-sym (gensym "elt")] `(fn [~elt-sym] (and (= ~tag (:tag ~elt-sym)) ~@(for [{type :type :as f} filters] (case type :attr (if-let [v (:value f)] `(= ~v (get-in ~elt-sym [:attrs ~(:name f)])) `(not (nil? (get-in ~elt-sym [:attrs ~(:name f)])))) :expr `(~(:form f) (meta ~elt-sym)))))))) (defn compile-match-expression "" [expr] {:pre [(not (empty? expr))]} (map compile-element-filter (match-expr-parser expr))) (defn matcher? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:match) (get-in elt [:attrs :rap:match])))) (defn- map-content [elt f] (assoc elt :content (flatseq (map f (:content elt))))) (defn set-content [elt & content] (assoc elt :content (flatseq content))) (defn append-content [elt & new-content] (apply set-content elt (:content elt) new-content)) (defn match-filter "Build code for a function that will replace elements matching the given expression with the return value of replacer." [[match-fn & more-fns] replacer recursive?] (fn m [elt] (if (xml/element? elt) (if (match-fn elt) (if more-fns (-> elt (map-content (match-filter more-fns replacer false)) (map-content m)) (replacer elt)) (if recursive? (map-content elt m) elt)) elt))) (defn compile-matcher ([expr body action as-sym] (let [action (keyword (or action :replace)) as-sym (or as-sym (gensym "matched-element")) as-sym (if (string? as-sym) (read-one as-sym) as-sym) body (into [] (map compile-xml body)) expr (string/trim expr) [expr recursive?] (if (.startsWith expr "/") [(.substring expr 1) false] [expr true]) exprs (compile-match-expression expr) fn-body (case action :replace body :append `(append-content ~as-sym ~@body) (compile-error "Unknown value for 'action' attribute on rap:match elment: " action))] `(match-filter [~@exprs] (fn [~as-sym] ~fn-body) ~recursive?)))) (defn make-matcher [elt] (if (= (:tag elt) :rap:match) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :expr :action :as)] (when-not expr (compile-error "Attribute :expr is required on rap:match element.")) (when-not (empty? (:attrs elt)) (compile-error "Unrecognized attributes on rap:match element:" (keys (:attrs elt)))) (compile-matcher expr (:content elt) action as-sym)) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :rap:match :rap:action :rap:as)] (compile-matcher expr [elt] action as-sym)))) (defn compile-content "" [content] (let [[elt & more :as content] content] (cond (nil? elt) nil (defn? elt) (let [[defns others] (split-with defn? content)] `(letfn [~@(map make-defn defns)] ~(compile-content others))) (matcher? elt) `(let [matcher# ~(make-matcher elt)] (map matcher# ~(compile-content more))) :else `[~(compile-xml elt) ~@(compile-content more)]))) (defn process-content [elt] (let [compiled (compile-content (:content elt)) compiled (if (nil? compiled) nil `(flatseq ~compiled))] ;TODO - be smarter here (assoc elt :content compiled))) (defmethod compile-xml Element [elt] (-> elt extract-directives process-content process-attrs apply-directives )) (defn- de-elementize "We work with Element instances at compile-time, but they do not self-evaluate like normal maps do. Convert them into an eval-able form." ;; TODO - I don't think I need this in clojure 1.3+ ... confirm. [x] (walk/prewalk (fn [e] (if (xml/element? e) (list `xml/element (:tag e) (:attrs e) (:content e)) e)) x)) (defn to-template-fn "Given a template, returns a data structure that can be eval-ed into a function." [xml-in] (let [roots (xml/parse xml-in xml/old-parse-options) ;TODO root (first (filter xml/element? roots)) [root [args requires uses imports]] (xml/pop-attrs root :rap:args :rap:require :rap:use :rap:import) args (read-all args) roots (if (= (:tag root) :rap:template) (:content root) [root]) compiled (into [] (map #(-> % compile-xml de-elementize) roots)) ] `(do ~@(for [lib (read-all requires)] `(require '~lib)) ~@(for [lib (read-all uses)] `(use '~lib)) ~@(for [lib (read-all imports)] `(import '~lib)) (fn template-main# ([context#] (template-main# context# nil)) ([{:keys [~@args]} in#] [~@compiled in#]))))) (defn dump "Print the code generated for the given XML template." [template] (pprint/pprint (to-template-fn template))) (declare ^:dynamic *template-ns*) (defn- eval-in-ns "Eval the " ([form] (eval-in-ns form *template-ns*)) ([form ns-or-name] (binding [*ns* (if (symbol? ns-or-name) (create-ns ns-or-name) ns-or-name)] (eval form)))) ; Namespace in which to eval templates (defonce ^:dynamic *template-ns* (let [ns-name (gensym "template-ns")] (eval-in-ns '(clojure.core/with-loading-context (clojure.core/refer 'clojure.core)) ns-name) (find-ns ns-name))) (defn compile-template "Compiles the template into a function that takes a context-map as input and produces a tree of Elements." [xml-in] (-> xml-in to-template-fn eval-in-ns (with-meta {::template-fn true ::template-source xml-in}) )) (defn template? [template] (::template-fn (meta template))) (defmacro locals [] (into {} (for [[k _] &env] [(keyword k) k]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public API (declare ^:dynamic *template-loader*) (defn template-loader "Returns a function that will return template, given a string (path or XML)." [root] (let [cache (atom nil)] ^{:root root} (fn loader [source] (if (and (string? source) (.startsWith source "<")) (compile-template source) ;don't cache strings (let [path (string/join "/" [(or root \.) source]) f (java.io.File. path) mod-t (.lastModified f) [cached-template cached-mod-t] (get @cache path)] (if (= cached-mod-t mod-t) cached-template (let [compiled (binding [*template-loader* loader] (compile-template f))] (swap! cache assoc path [compiled mod-t]) compiled))))))) (def ^:dynamic *template-loader* (template-loader nil)) (defn template "Returns a compiled template, either by compiling it or by getting it from the template cache." [source] (*template-loader* source)) (defn render "Render a template as a string of XML" ([template] (render template {})) ([template context] (let [tmpl (if (template? template) template (compile-template template)) elts (tmpl context)] (xml/emit elts)))) (defmacro render-with-locals [template] `(render ~template (locals)))
true
(ns ^{:author "PI:NAME:<NAME>END_PI" :doc "The Rapscallion XML generation and transformation library."} rapscallion.core (:require (clojure (string :as string) (pprint :as pprint) (walk :as walk))) (:require (eksemel (xml :as xml))) (:require (imparsonate (core :as imp) (lib :as implib))) (:import (java.io Reader StringReader PushbackReader) (eksemel.xml Element)) ) (defn- compile-error [& messages] (throw (IllegalArgumentException. (apply str messages)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Extract embedded expressions from text (defn slurp-reader "Consume the given Reader and return its contents as a string." [#^Reader reader] (let [sb (StringBuilder.)] (loop [c (.read reader)] (if (neg? c) (.toString sb) (do (.append sb (char c)) (recur (.read reader))))))) (defn read-partial "Like (read s), but returns a 2-element vector of the form that was read and the remaining, unread portion of the string." [^String s] (let [rdr (PushbackReader. (StringReader. s))] [(read rdr) (slurp-reader rdr)])) (defn read-all [^String s] (loop [forms [] s s] (if (empty? s) forms (let [[form s] (read-partial s)] (recur (conj forms form) (.trim s)))))) (defn read-one [^String s] (let [[form & more] (read-all s)] (when more (compile-error "Expected exactly one clojure form - saw \"" s "\"")) form)) (defn- merge-adjacent-strings [col] (let [joiner #(if (string? (first %)) [(apply str %)] %) joined (map joiner (partition-by string? col))] (apply concat joined))) (defn extract-exprs "Extract embedded expressions from the string, returning a sequence of strings and forms." ([^String s] (extract-exprs s "$")) ([^String s ^String c] (let [pat (java.util.regex.Pattern/quote c)] (loop [parts [] s s] (let [[left ^String rest] (seq (.split s pat 2)) parts (if (not-empty left) (conj parts left) parts)] (cond (nil? rest) ; at the end (merge-adjacent-strings parts) (empty? rest) ; trailing $ (compile-error "Trailing " c ". Double it to insert a literal " c) (.startsWith rest c) ; doubled $$ == literal $ (recur (conj parts c) (.substring rest 1)) :else (let [brace? (.startsWith rest "{") rest (if brace? (.substring rest 1) rest) [form ^String right] (read-partial rest)] (when (and brace? (not (.startsWith right "}"))) (throw (Exception. "mismatched curly-bracket in embedded code"))) ; FIXME - exception class, line number, etc. (recur (conj parts form) (if brace? (.substring right 1) right))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; XML template language ; directives: ;name element attr notes ;---------------------------------------------------------------------- ;args no yes top-level element only? ;if yes yes <rap:if test="..."> ;for yes yes <rap:for expr="..."> ;let yes yes <rap:let bindings="..."> ;attrs no yes ;meta no yes ;defn yes yes <rap:defn fn="name [args]"> ;call yes yes <rap:call fn="name args"> ;match yes yes <rap:match xpath="foo/bar{:cool}"> (def ^:dynamic *strict* true) ; for debugging - don't change this to false unless you know what you're doing (def ^:dynamic *keep-whitespace* false) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Each value that is substituted into a template gets passed through ;; this multimethod. Eg: ;; <foo>Hello ${name}</foo> ;; compiles to ;; (Element. :foo nil ["Hello " (xml-value name)]) (defmulti xml-value type) ;; The default is just to stringify the object. (defmethod xml-value :default [x] (str x)) ;; Elements are inserted as-is. (defmethod xml-value Element [x] x) (defmethod xml-value clojure.lang.Sequential [x] (map xml-value x)) ;; This is a special case that handles "call-with-content". ;; Example: ;; <rap:call fn='foo'> ;; <bar>Hi</bar> ;; </rap:call> ;; This generates code that will call "foo" with one parameter - a fn ;; that returns (Element. :bar nil ["Hi"]). That fn is flagged in its ;; metadata as a :call-body. Inside the definition of "foo", it can ;; be inserted as either $x or $(x) (assuming it is bound to "x" ;; inside foo). Why? Consider the definition of foo: ;; <rap:defn fn='foo [x]'> ;; <wrap>$x</wrap> ;; <rap:defn> ;; The author of this function cannot know whether to use $x or $(x), ;; because he doesn't know how it will be called: ;; $(foo 23) ;; <rap:call fn='foo'>...etc...</rap:call> ;; (defmethod xml-value ::call-body [f] (f)) (defmulti compile-xml type) (defmethod compile-xml String [s] (let [s (if *keep-whitespace* s (string/trim s)) parts (extract-exprs s)] (if (and (= 1 (count parts)) (string? (first parts))) (first parts) (vec (for [p parts] (if (string? p) p `(xml-value ~p))))))) (defn flatseq [& cols] (filter (complement nil?) (flatten cols))) (defn process-attr [v] (let [v (extract-exprs v)] (if (> (count v) 1) `(str ~@v) (first v)))) (defn process-attrs [elt] (assoc elt :attrs (into {} (for [[k v] (:attrs elt)] [k (process-attr v)])))) (defn directive? [elt] (.startsWith (name (:tag elt)) "rap:")) ; FIXME - use xmlns (defn- strip-ns [qname] (-> qname name (.split ":" 2) second keyword)) (defmulti compile-directive (fn ([elt] (when-not (directive? elt) (compile-error "compile-directive called, but element is not a directive. tag: " (:tag elt))) (strip-ns (:tag elt))) ([tag & _] tag))) (defmethod compile-directive :default [elt] (compile-error "Unknown directive: " (:tag elt))) (defn pop-directive-attrs "Given a directive-element and an attribute name, returns a two-element vector of the element with the attribute removed, and the attribute parsed into clojure forms." [elt attr] (let [tag (:tag elt) [elt expr] (xml/pop-attr elt attr)] (when (empty? expr) (compile-error "Attribute " attr " is required on directive " tag)) (when (not-empty (:attrs elt)) (compile-error "Unsupported attibutes on " tag " directive: " (string/join " " (keys (:attrs elt))))) [elt (read-all expr)])) (defmethod compile-directive :let ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :let bindings (:content elt)))) ([_ bindings body] `(let [~@bindings] ~body))) (defmethod compile-directive :if ([elt] (let [[elt test] (pop-directive-attrs elt :test)] (compile-directive :if test (:content elt)))) ([_ [test & more :as exprs] body] (when more (compile-error "Only one form is allowed as the 'test' attribute of an :if directive. Found: " exprs)) `(if ~test ~body))) (defmethod compile-directive :for ([elt] (let [[elt bindings] (pop-directive-attrs elt :bindings)] (compile-directive :for bindings (:content elt)))) ([_ bindings body] `(for [~@bindings] ~body))) (defmethod compile-directive :attrs ([elt] (compile-error "Directive :attrs is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":attrs directive must be a single form - saw " exprs)) `(xml/merge-attrs ~elt ~expr))) (defn merge-meta [obj m] (with-meta obj (into (or (meta obj) {}) (if (keyword? m) {m true} m)))) (defmethod compile-directive :meta ([elt] (compile-error "Directive :meta is not allowed as an element.")) ([_ [expr & more :as exprs] elt] (when more (compile-error ":meta directive must be a single form - saw " exprs)) `(merge-meta ~elt ~expr))) (defmethod compile-directive :call ([elt] (let [[elt body-args] (xml/pop-attr elt :args) body-args (and body-args (read-all body-args)) [elt fn-and-args] (pop-directive-attrs elt :fn)] (compile-directive :call fn-and-args (:content elt) body-args))) ([elt fn-and-args body] (compile-directive elt fn-and-args body nil)) ([_ [f & args] body body-args] `(~f ~@args (with-meta (fn [~@body-args] ~body) {:type ::call-body})))) (comment ;; hypothetical syntax for defdirective (defdirective :call :as-attribute :fn :as-element {:attributes [:fn :args] })) (defn compile-element [elt] (if (directive? elt) (compile-directive elt) elt)) (defn extract-directives "Pull rap: directives out of the :attrs map and put them in metadata instead." [elt] (let [is-directive (fn [[k v]] (.startsWith (name k) "rap:")) ; FIXME - use xmlns attrs (:attrs elt) directives (filter is-directive attrs) directives (into {} (for [[k v] directives] [(strip-ns k) (read-all v)])) attrs (into {} (filter (complement is-directive) attrs)) elt (assoc elt :attrs attrs)] (vary-meta elt assoc :directives directives))) (defn pop-directive [elt name] (let [directives (:directives (meta elt)) value (get directives name) directives (dissoc directives name) elt (vary-meta elt assoc :directives directives)] [elt value])) (def ^:dynamic *directives* (atom [{:name :attrs} {:name :meta} {:name :call} {:name :let} {:name :if} {:name :for} {:name :include} ])) (defn apply-directives "Given an element, return the element with any directives attached as attributes compiled." ([elt] (apply-directives elt @*directives*)) ([elt directives] (let [directive-values (:directives (meta elt)) elt (vary-meta elt dissoc :directives) body (compile-element elt)] (loop [directive-values directive-values body body [next-directive & directives] directives] (if (empty? directive-values) body ;; done - all directives attached to this element have been processed (if-not next-directive (when *strict* (compile-error "Unprocessed directives on element " (:tag elt) " (" (string/join ", " (keys directive-values)) ").")) (let [directive-name (:name next-directive) directive-value (get directive-values directive-name)] (recur (dissoc directive-values directive-name) (if directive-value (compile-directive directive-name directive-value body) body) directives)))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:defn (defn- defn? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:defn) (get-in elt [:attrs :rap:defn])))) (defn- make-defn [elt] (if (= (:tag elt) :rap:defn) (let [[elt fnspec] (pop-directive-attrs elt :fn)] `(~@fnspec (flatseq ~@(map compile-xml (:content elt))))) (let [[elt fnspec] (xml/pop-attr elt :rap:defn) [name argvec] (read-all fnspec)] `(~name [~@argvec] ~(compile-xml elt))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; rap:match (imp/defparser match-expr-parser :root :path :path #{:relpath :abspath} :abspath ["/" :relpat] :relpath (imp/list-of :elt "/") :elt [#{:tag "*"} :filter*] :tag #"[\w-]+" keyword :filter #{:xml-filter :clj-filter} :xml-filter ["[" :attr-filter "]"] :attr-filter ["@" :attrname ["=" :quoted-string]:?] (fn [n v] {:type :attr :name (keyword n) :value v}) :attrname #"[\w-]+" ;FIXME :quoted-string implib/double-quoted-string :clj-filter ["{" :clj-form "}"] (fn [form] {:type :expr :form form}) :clj-form read-partial ) (defn compile-element-filter [[tag filters]] (let [elt-sym (gensym "elt")] `(fn [~elt-sym] (and (= ~tag (:tag ~elt-sym)) ~@(for [{type :type :as f} filters] (case type :attr (if-let [v (:value f)] `(= ~v (get-in ~elt-sym [:attrs ~(:name f)])) `(not (nil? (get-in ~elt-sym [:attrs ~(:name f)])))) :expr `(~(:form f) (meta ~elt-sym)))))))) (defn compile-match-expression "" [expr] {:pre [(not (empty? expr))]} (map compile-element-filter (match-expr-parser expr))) (defn matcher? [elt] (and (xml/element? elt) (or (= (:tag elt) :rap:match) (get-in elt [:attrs :rap:match])))) (defn- map-content [elt f] (assoc elt :content (flatseq (map f (:content elt))))) (defn set-content [elt & content] (assoc elt :content (flatseq content))) (defn append-content [elt & new-content] (apply set-content elt (:content elt) new-content)) (defn match-filter "Build code for a function that will replace elements matching the given expression with the return value of replacer." [[match-fn & more-fns] replacer recursive?] (fn m [elt] (if (xml/element? elt) (if (match-fn elt) (if more-fns (-> elt (map-content (match-filter more-fns replacer false)) (map-content m)) (replacer elt)) (if recursive? (map-content elt m) elt)) elt))) (defn compile-matcher ([expr body action as-sym] (let [action (keyword (or action :replace)) as-sym (or as-sym (gensym "matched-element")) as-sym (if (string? as-sym) (read-one as-sym) as-sym) body (into [] (map compile-xml body)) expr (string/trim expr) [expr recursive?] (if (.startsWith expr "/") [(.substring expr 1) false] [expr true]) exprs (compile-match-expression expr) fn-body (case action :replace body :append `(append-content ~as-sym ~@body) (compile-error "Unknown value for 'action' attribute on rap:match elment: " action))] `(match-filter [~@exprs] (fn [~as-sym] ~fn-body) ~recursive?)))) (defn make-matcher [elt] (if (= (:tag elt) :rap:match) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :expr :action :as)] (when-not expr (compile-error "Attribute :expr is required on rap:match element.")) (when-not (empty? (:attrs elt)) (compile-error "Unrecognized attributes on rap:match element:" (keys (:attrs elt)))) (compile-matcher expr (:content elt) action as-sym)) (let [[elt [expr action as-sym]] (xml/pop-attrs elt :rap:match :rap:action :rap:as)] (compile-matcher expr [elt] action as-sym)))) (defn compile-content "" [content] (let [[elt & more :as content] content] (cond (nil? elt) nil (defn? elt) (let [[defns others] (split-with defn? content)] `(letfn [~@(map make-defn defns)] ~(compile-content others))) (matcher? elt) `(let [matcher# ~(make-matcher elt)] (map matcher# ~(compile-content more))) :else `[~(compile-xml elt) ~@(compile-content more)]))) (defn process-content [elt] (let [compiled (compile-content (:content elt)) compiled (if (nil? compiled) nil `(flatseq ~compiled))] ;TODO - be smarter here (assoc elt :content compiled))) (defmethod compile-xml Element [elt] (-> elt extract-directives process-content process-attrs apply-directives )) (defn- de-elementize "We work with Element instances at compile-time, but they do not self-evaluate like normal maps do. Convert them into an eval-able form." ;; TODO - I don't think I need this in clojure 1.3+ ... confirm. [x] (walk/prewalk (fn [e] (if (xml/element? e) (list `xml/element (:tag e) (:attrs e) (:content e)) e)) x)) (defn to-template-fn "Given a template, returns a data structure that can be eval-ed into a function." [xml-in] (let [roots (xml/parse xml-in xml/old-parse-options) ;TODO root (first (filter xml/element? roots)) [root [args requires uses imports]] (xml/pop-attrs root :rap:args :rap:require :rap:use :rap:import) args (read-all args) roots (if (= (:tag root) :rap:template) (:content root) [root]) compiled (into [] (map #(-> % compile-xml de-elementize) roots)) ] `(do ~@(for [lib (read-all requires)] `(require '~lib)) ~@(for [lib (read-all uses)] `(use '~lib)) ~@(for [lib (read-all imports)] `(import '~lib)) (fn template-main# ([context#] (template-main# context# nil)) ([{:keys [~@args]} in#] [~@compiled in#]))))) (defn dump "Print the code generated for the given XML template." [template] (pprint/pprint (to-template-fn template))) (declare ^:dynamic *template-ns*) (defn- eval-in-ns "Eval the " ([form] (eval-in-ns form *template-ns*)) ([form ns-or-name] (binding [*ns* (if (symbol? ns-or-name) (create-ns ns-or-name) ns-or-name)] (eval form)))) ; Namespace in which to eval templates (defonce ^:dynamic *template-ns* (let [ns-name (gensym "template-ns")] (eval-in-ns '(clojure.core/with-loading-context (clojure.core/refer 'clojure.core)) ns-name) (find-ns ns-name))) (defn compile-template "Compiles the template into a function that takes a context-map as input and produces a tree of Elements." [xml-in] (-> xml-in to-template-fn eval-in-ns (with-meta {::template-fn true ::template-source xml-in}) )) (defn template? [template] (::template-fn (meta template))) (defmacro locals [] (into {} (for [[k _] &env] [(keyword k) k]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public API (declare ^:dynamic *template-loader*) (defn template-loader "Returns a function that will return template, given a string (path or XML)." [root] (let [cache (atom nil)] ^{:root root} (fn loader [source] (if (and (string? source) (.startsWith source "<")) (compile-template source) ;don't cache strings (let [path (string/join "/" [(or root \.) source]) f (java.io.File. path) mod-t (.lastModified f) [cached-template cached-mod-t] (get @cache path)] (if (= cached-mod-t mod-t) cached-template (let [compiled (binding [*template-loader* loader] (compile-template f))] (swap! cache assoc path [compiled mod-t]) compiled))))))) (def ^:dynamic *template-loader* (template-loader nil)) (defn template "Returns a compiled template, either by compiling it or by getting it from the template cache." [source] (*template-loader* source)) (defn render "Render a template as a string of XML" ([template] (render template {})) ([template context] (let [tmpl (if (template? template) template (compile-template template)) elts (tmpl context)] (xml/emit elts)))) (defmacro render-with-locals [template] `(render ~template (locals)))
[ { "context": ";; Copyright 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 36, "score": 0.999881386756897, "start": 23, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 50, "score": 0.999931812286377, "start": 38, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/buddy/auth/http.clj
eipplusone/buddy-auth
292
;; Copyright 2015-2016 Andrey Antukh <niwi@niwi.nz> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.auth.http "The http request response abstraction for builtin auth/authz backends.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols Definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IRequest (-get-header [req name] "Get a value of header.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn response "A multi arity function that creates a ring compatible response." ([body] {:status 200 :body body :headers {}}) ([body status] {:status status :body body :headers {}}) ([body status headers] {:status status :body body :headers headers})) (defn response? [resp] (and (map? resp) (integer? (:status resp)) (map? (:headers resp)))) (defn redirect "Returns a Ring compatible response for an HTTP 302 redirect." ([url] (redirect url 302)) ([url status] {:status status :body "" :headers {"Location" url}})) (defn find-header "Looks up a header in a headers map case insensitively, returning the header map entry, or nil if not present." [headers ^String header-name] (first (filter #(.equalsIgnoreCase header-name (name (key %))) headers))) (extend-protocol IRequest clojure.lang.IPersistentMap (-get-header [request header-name] (some-> (:headers request) (find-header header-name) val)))
105155
;; Copyright 2015-2016 <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.auth.http "The http request response abstraction for builtin auth/authz backends.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols Definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IRequest (-get-header [req name] "Get a value of header.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn response "A multi arity function that creates a ring compatible response." ([body] {:status 200 :body body :headers {}}) ([body status] {:status status :body body :headers {}}) ([body status headers] {:status status :body body :headers headers})) (defn response? [resp] (and (map? resp) (integer? (:status resp)) (map? (:headers resp)))) (defn redirect "Returns a Ring compatible response for an HTTP 302 redirect." ([url] (redirect url 302)) ([url status] {:status status :body "" :headers {"Location" url}})) (defn find-header "Looks up a header in a headers map case insensitively, returning the header map entry, or nil if not present." [headers ^String header-name] (first (filter #(.equalsIgnoreCase header-name (name (key %))) headers))) (extend-protocol IRequest clojure.lang.IPersistentMap (-get-header [request header-name] (some-> (:headers request) (find-header header-name) val)))
true
;; Copyright 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.auth.http "The http request response abstraction for builtin auth/authz backends.") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Protocols Definition ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defprotocol IRequest (-get-header [req name] "Get a value of header.")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn response "A multi arity function that creates a ring compatible response." ([body] {:status 200 :body body :headers {}}) ([body status] {:status status :body body :headers {}}) ([body status headers] {:status status :body body :headers headers})) (defn response? [resp] (and (map? resp) (integer? (:status resp)) (map? (:headers resp)))) (defn redirect "Returns a Ring compatible response for an HTTP 302 redirect." ([url] (redirect url 302)) ([url status] {:status status :body "" :headers {"Location" url}})) (defn find-header "Looks up a header in a headers map case insensitively, returning the header map entry, or nil if not present." [headers ^String header-name] (first (filter #(.equalsIgnoreCase header-name (name (key %))) headers))) (extend-protocol IRequest clojure.lang.IPersistentMap (-get-header [request header-name] (some-> (:headers request) (find-header header-name) val)))
[ { "context": "8\"))\n (is (= (:remote-addr request-map) \"127.0.0.1\"))\n (is (= (:scheme request-map) :http))", "end": 1799, "score": 0.9997462034225464, "start": 1790, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "jks\"\n :key-password \"password\"}\n (let [response (http/get \"https://localho", "end": 2774, "score": 0.9944390058517456, "start": 2766, "tag": "PASSWORD", "value": "password" } ]
test/ring/adapter/simpleweb_test.clj
netmelody/ring-simpleweb-adapter
1
(ns ring.adapter.simpleweb-test (:use clojure.test ring.adapter.simpleweb) (:require [clj-http.client :as http])) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-simpleweb ~app ~(assoc options :join? false))] (try ~@body (finally (.close server#))))) (deftest test-run-simpleweb (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "echo server" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "age=123&surname=jones")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :keystore "test/keystore.jks" :key-password "password"} (let [response (http/get "https://localhost:4347" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))))
79487
(ns ring.adapter.simpleweb-test (:use clojure.test ring.adapter.simpleweb) (:require [clj-http.client :as http])) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-simpleweb ~app ~(assoc options :join? false))] (try ~@body (finally (.close server#))))) (deftest test-run-simpleweb (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "echo server" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "age=123&surname=jones")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :keystore "test/keystore.jks" :key-password "<PASSWORD>"} (let [response (http/get "https://localhost:4347" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))))
true
(ns ring.adapter.simpleweb-test (:use clojure.test ring.adapter.simpleweb) (:require [clj-http.client :as http])) (defn- hello-world [request] {:status 200 :headers {"Content-Type" "text/plain"} :body "Hello World"}) (defn- content-type-handler [content-type] (constantly {:status 200 :headers {"Content-Type" content-type} :body ""})) (defn- echo-handler [request] {:status 200 :headers {"request-map" (str (dissoc request :body))} :body (:body request)}) (defmacro with-server [app options & body] `(let [server# (run-simpleweb ~app ~(assoc options :join? false))] (try ~@body (finally (.close server#))))) (deftest test-run-simpleweb (testing "HTTP server" (with-server hello-world {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (:status response) 200)) (is (.startsWith (get-in response [:headers "content-type"]) "text/plain")) (is (= (:body response) "Hello World"))))) (testing "echo server" (with-server echo-handler {:port 4347} (let [response (http/get "http://localhost:4347/foo/bar/baz?surname=jones&age=123" {:body "hello"})] (is (= (:status response) 200)) (is (= (:body response) "hello")) (let [request-map (read-string (get-in response [:headers "request-map"]))] (is (= (:query-string request-map) "age=123&surname=jones")) (is (= (:uri request-map) "/foo/bar/baz")) (is (= (:content-length request-map) 5)) (is (= (:character-encoding request-map) "UTF-8")) (is (= (:request-method request-map) :get)) (is (= (:content-type request-map) "text/plain; charset=UTF-8")) (is (= (:remote-addr request-map) "127.0.0.1")) (is (= (:scheme request-map) :http)) (is (= (:server-name request-map) "localhost")) (is (= (:server-port request-map) 4347)) (is (= (:ssl-client-cert request-map) nil)))))) (testing "default character encoding" (with-server (content-type-handler "text/plain") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (.contains (get-in response [:headers "content-type"]) "text/plain"))))) (testing "custom content-type" (with-server (content-type-handler "text/plain;charset=UTF-16;version=1") {:port 4347} (let [response (http/get "http://localhost:4347")] (is (= (get-in response [:headers "content-type"]) "text/plain;charset=UTF-16;version=1"))))) (testing "HTTPS server" (with-server hello-world {:port 4347 :keystore "test/keystore.jks" :key-password "PI:PASSWORD:<PASSWORD>END_PI"} (let [response (http/get "https://localhost:4347" {:insecure? true})] (is (= (:status response) 200)) (is (= (:body response) "Hello World"))))))
[ { "context": " {[:db/id 637716744120508] {:artist/name \"Janis Joplin\"}})))\n\n (testing \"reading from unique attribute\"", "end": 56787, "score": 0.9997291564941406, "start": 56775, "tag": "NAME", "value": "Janis Joplin" }, { "context": "6a-85c0-823e3efddb7f\"]\n {:artist/name \"Janis Joplin\"}})))\n\n (testing \"explicit db\"\n (is (= (parse", "end": 57075, "score": 0.9998512268066406, "start": 57063, "tag": "NAME", "value": "Janis Joplin" }, { "context": " :artist/name \"not Janis Joplin\"}]))}\n [{[:artist/gid #uuid\"76c", "end": 57355, "score": 0.9846842885017395, "start": 57343, "tag": "NAME", "value": "Janis Joplin" }, { "context": "85c0-823e3efddb7f\"]\n {:artist/name \"not Janis Joplin\"}})))\n\n (comment\n \"after transact data (I wil", "end": 57593, "score": 0.9993454217910767, "start": 57581, "tag": "NAME", "value": "Janis Joplin" }, { "context": "-823e3efddb7f\"\n :artist/name \"not Janis Joplin\"}])\n (is (= (parser {}\n [{[:", "end": 57849, "score": 0.9992936253547668, "start": 57837, "tag": "NAME", "value": "Janis Joplin" }, { "context": "85c0-823e3efddb7f\"]\n {:artist/name \"not Janis Joplin\"}})))\n\n (testing \"implicit dependency\"\n (is (", "end": 58107, "score": 0.9993718862533569, "start": 58095, "tag": "NAME", "value": "Janis Joplin" }, { "context": "efddb7f\"]\n {:artist/super-name \"SUPER - Janis Joplin\"}})))\n\n (testing \"process-query\"\n (is (= (par", "end": 58405, "score": 0.9996350407600403, "start": 58393, "tag": "NAME", "value": "Janis Joplin" }, { "context": "ore-1600\n [{:artist/super-name \"SUPER - Heinrich Schütz\",\n :artist/country {:country/name", "end": 58708, "score": 0.9998716711997986, "start": 58693, "tag": "NAME", "value": "Heinrich Schütz" }, { "context": "fore-1600\n {:artist/super-name \"SUPER - Heinrich Schütz\",\n :artist/country {:country/name ", "end": 59212, "score": 0.9998645186424255, "start": 59197, "tag": "NAME", "value": "Heinrich Schütz" }, { "context": " {:release/artists [{:artist/super-name \"SUPER - Horst Jankowski\"}]}})))\n\n (testing \"without subquery\"\n (i", "end": 60473, "score": 0.9997529983520508, "start": 60458, "tag": "NAME", "value": "Horst Jankowski" }, { "context": "-85c0-823e3efddb7f\"]\n {:artist/name \"Janis Joplin\"\n :artist/gender ::p/not-found}})))\n\n", "end": 62641, "score": 0.9997926950454712, "start": 62629, "tag": "NAME", "value": "Janis Joplin" }, { "context": "6a-85c0-823e3efddb7f\"]\n {:artist/name \"Janis Joplin\"\n :db/id ::p/not-found}})))\n\n ", "end": 62997, "score": 0.9997760057449341, "start": 62985, "tag": "NAME", "value": "Janis Joplin" }, { "context": "efddb7f\"]\n {:artist/super-name \"SUPER - Janis Joplin\"}})))\n\n (testing \"process-query\"\n (is (= (sec", "end": 63342, "score": 0.9997747540473938, "start": 63330, "tag": "NAME", "value": "Janis Joplin" }, { "context": "ore-1600\n [{:artist/super-name \"SUPER - Heinrich Schütz\",\n :artist/country {:country/name", "end": 63652, "score": 0.9998824000358582, "start": 63637, "tag": "NAME", "value": "Heinrich Schütz" }, { "context": "fore-1600\n {:artist/super-name \"SUPER - Heinrich Schütz\",\n :artist/country {:country/name ", "end": 64163, "score": 0.9998800158500671, "start": 64148, "tag": "NAME", "value": "Heinrich Schütz" }, { "context": " {:release/artists [{:artist/super-name \"SUPER - Horst Jankowski\"}]}})))))\n\n(comment\n (pcd/config-parser db-confi", "end": 64670, "score": 0.9997068643569946, "start": 64655, "tag": "NAME", "value": "Horst Jankowski" }, { "context": "]\n [?geid :db/ident ?gender]]\n db\n \"Janis Joplin\")\n\n (d/q '{:find [[(pull ?e [*]) ...]]\n ", "end": 67152, "score": 0.9998264312744141, "start": 67140, "tag": "NAME", "value": "Janis Joplin" } ]
test/com/wsscode/pathom/connect/datomic_test.clj
solussd/pathom-datomic
38
(ns com.wsscode.pathom.connect.datomic-test (:require [clojure.test :refer :all] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.connect.datomic :as pcd] [com.wsscode.pathom.connect.datomic.on-prem :refer [on-prem-config]] [com.wsscode.pathom.connect.planner :as pcp] [com.wsscode.pathom.core :as p] [datomic.api :as d] [edn-query-language.core :as eql])) (def uri "datomic:free://localhost:4334/mbrainz-1968-1973") (def conn (d/connect uri)) (def db (d/db conn)) (def db-config (assoc on-prem-config ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!)) (def whitelist #{:artist/country :artist/gid :artist/name :artist/sortName :artist/type :country/name :medium/format :medium/name :medium/position :medium/trackCount :medium/tracks :release/artists :release/country :release/day :release/gid :release/labels :release/language :release/media :release/month :release/name :release/packaging :release/script :release/status :release/year :track/artists :track/duration :track/name :track/position}) (def db-schema-output {:abstractRelease/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the abstract release" :fulltext true :id 82 :ident :abstractRelease/artistCredit :valueType #:db{:ident :db.type/string}} :abstractRelease/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the abstract release" :id 81 :ident :abstractRelease/artists :valueType #:db{:ident :db.type/ref}} :abstractRelease/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the abstract release" :id 78 :ident :abstractRelease/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :abstractRelease/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the abstract release" :id 79 :ident :abstractRelease/name :index true :valueType #:db{:ident :db.type/string}} :abstractRelease/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of: :release.type/album, :release.type/single, :release.type/ep, :release.type/audiobook, or :release.type/other" :id 80 :ident :abstractRelease/type :valueType #:db{:ident :db.type/ref}} :artist/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's country of origin" :id 71 :ident :artist/country :valueType #:db{:ident :db.type/ref}} :artist/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist stopped actively recording" :id 77 :ident :artist/endDay :valueType #:db{:ident :db.type/long}} :artist/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist stopped actively recording" :id 76 :ident :artist/endMonth :valueType #:db{:ident :db.type/long}} :artist/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist stopped actively recording" :id 75 :ident :artist/endYear :valueType #:db{:ident :db.type/long}} :artist/gender #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.gender/male, :artist.gender/female, or :artist.gender/other." :id 70 :ident :artist/gender :valueType #:db{:ident :db.type/ref}} :artist/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for an artist" :id 66 :ident :artist/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :artist/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name" :fulltext true :id 67 :ident :artist/name :index true :valueType #:db{:ident :db.type/string}} :artist/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name for use in alphabetical sorting, e.g. Beatles, The" :id 68 :ident :artist/sortName :index true :valueType #:db{:ident :db.type/string}} :artist/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist started actively recording" :id 74 :ident :artist/startDay :valueType #:db{:ident :db.type/long}} :artist/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist started actively recording" :id 73 :ident :artist/startMonth :valueType #:db{:ident :db.type/long}} :artist/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist started actively recording" :id 72 :ident :artist/startYear :index true :valueType #:db{:ident :db.type/long}} :artist/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.type/person, :artist.type/other, :artist.type/group." :id 69 :ident :artist/type :valueType #:db{:ident :db.type/ref}} :country/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the country" :id 63 :ident :country/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :db.alter/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will alter the definition of existing attribute v." :id 19 :ident :db.alter/attribute :valueType #:db{:ident :db.type/ref}} :db.excise/attrs #:db{:cardinality #:db{:ident :db.cardinality/many} :id 16 :ident :db.excise/attrs :valueType #:db{:ident :db.type/ref}} :db.excise/before #:db{:cardinality #:db{:ident :db.cardinality/one} :id 18 :ident :db.excise/before :valueType #:db{:ident :db.type/instant}} :db.excise/beforeT #:db{:cardinality #:db{:ident :db.cardinality/one} :id 17 :ident :db.excise/beforeT :valueType #:db{:ident :db.type/long}} :db.install/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as an attribute." :id 13 :ident :db.install/attribute :valueType #:db{:ident :db.type/ref}} :db.install/function #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a data function." :id 14 :ident :db.install/function :valueType #:db{:ident :db.type/ref}} :db.install/partition #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a partition." :id 11 :ident :db.install/partition :valueType #:db{:ident :db.type/ref}} :db.install/valueType #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a value type." :id 12 :ident :db.install/valueType :valueType #:db{:ident :db.type/ref}} :db.sys/partiallyIndexed #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute set to true for transactions not fully incorporated into the index" :id 8 :ident :db.sys/partiallyIndexed :valueType #:db{:ident :db.type/boolean}} :db.sys/reId #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute for an id e in the log that has been changed to id v in the index" :id 9 :ident :db.sys/reId :valueType #:db{:ident :db.type/ref}} :db/cardinality #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. Two possible values: :db.cardinality/one for single-valued attributes, and :db.cardinality/many for many-valued attributes. Defaults to :db.cardinality/one." :id 41 :ident :db/cardinality :valueType #:db{:ident :db.type/ref}} :db/code #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "String-valued attribute of a data function that contains the function's source code." :fulltext true :id 47 :ident :db/code :valueType #:db{:ident :db.type/string}} :db/doc #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Documentation string for an entity." :fulltext true :id 62 :ident :db/doc :valueType #:db{:ident :db.type/string}} :db/excise #:db{:cardinality #:db{:ident :db.cardinality/one} :id 15 :ident :db/excise :valueType #:db{:ident :db.type/ref}} :db/fn #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "A function-valued attribute for direct use by transactions and queries." :id 52 :ident :db/fn :valueType #:db{:ident :db.type/fn}} :db/fulltext #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create a fulltext search index for the attribute. Defaults to false." :id 51 :ident :db/fulltext :valueType #:db{:ident :db.type/boolean}} :db/ident #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute used to uniquely name an entity." :id 10 :ident :db/ident :unique #:db{:id 38} :valueType #:db{:ident :db.type/keyword}} :db/index #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create an AVET index for the attribute. Defaults to false." :id 44 :ident :db/index :valueType #:db{:ident :db.type/boolean}} :db/isComponent #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of attribute whose vtype is :db.type/ref. If true, then the attribute is a component of the entity referencing it. When you query for an entire entity, components are fetched automatically. Defaults to nil." :id 43 :ident :db/isComponent :valueType #:db{:ident :db.type/boolean}} :db/lang #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute of a data function. Value is a keyword naming the implementation language of the function. Legal values are :db.lang/java and :db.lang/clojure" :id 46 :ident :db/lang :valueType #:db{:ident :db.type/ref}} :db/noHistory #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, past values of the attribute are not retained after indexing. Defaults to false." :id 45 :ident :db/noHistory :valueType #:db{:ident :db.type/boolean}} :db/txInstant #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute whose value is a :db.type/instant. A :db/txInstant is recorded automatically with every transaction." :id 50 :ident :db/txInstant :index true :valueType #:db{:ident :db.type/instant}} :db/unique #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If value is :db.unique/value, then attribute value is unique to each entity. Attempts to insert a duplicate value for a temporary entity id will fail. If value is :db.unique/identity, then attribute value is unique, and upsert is enabled. Attempting to insert a duplicate value for a temporary entity id will cause all attributes associated with that temporary id to be merged with the entity already in the database. Defaults to nil." :id 42 :ident :db/unique :valueType #:db{:ident :db.type/ref}} :db/valueType #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute that specifies the attribute's value type. Built-in value types include, :db.type/keyword, :db.type/string, :db.type/ref, :db.type/instant, :db.type/long, :db.type/bigdec, :db.type/boolean, :db.type/float, :db.type/uuid, :db.type/double, :db.type/bigint, :db.type/uri." :id 40 :ident :db/valueType :valueType #:db{:ident :db.type/ref}} :fressian/tag #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Keyword-valued attribute of a value type that specifies the underlying fressian type used for serialization." :id 39 :ident :fressian/tag :index true :valueType #:db{:ident :db.type/keyword}} :label/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the record label is located" :id 87 :ident :label/country :valueType #:db{:ident :db.type/ref}} :label/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label stopped business" :id 93 :ident :label/endDay :valueType #:db{:ident :db.type/long}} :label/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label stopped business" :id 92 :ident :label/endMonth :valueType #:db{:ident :db.type/long}} :label/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label stopped business" :id 91 :ident :label/endYear :valueType #:db{:ident :db.type/long}} :label/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the record label" :id 83 :ident :label/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :label/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label" :fulltext true :id 84 :ident :label/name :index true :valueType #:db{:ident :db.type/string}} :label/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label for use in alphabetical sorting" :id 85 :ident :label/sortName :index true :valueType #:db{:ident :db.type/string}} :label/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label started business" :id 90 :ident :label/startDay :valueType #:db{:ident :db.type/long}} :label/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label started business" :id 89 :ident :label/startMonth :valueType #:db{:ident :db.type/long}} :label/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label started business" :id 88 :ident :label/startYear :index true :valueType #:db{:ident :db.type/long}} :label/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :label.type/distributor, :label.type/holding, :label.type/production, :label.type/originalProduction, :label.type/bootlegProduction, :label.type/reissueProduction, or :label.type/publisher." :id 86 :ident :label/type :valueType #:db{:ident :db.type/ref}} :language/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the written and spoken language" :id 64 :ident :language/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :medium/format #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The format of the medium. An enum with lots of possible values" :id 111 :ident :medium/format :valueType #:db{:ident :db.type/ref}} :medium/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the medium itself, distinct from the name of the release" :fulltext true :id 113 :ident :medium/name :valueType #:db{:ident :db.type/string}} :medium/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of this medium in the release relative to the other media, i.e. disc 1" :id 112 :ident :medium/position :valueType #:db{:ident :db.type/long}} :medium/trackCount #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The total number of tracks on the medium" :id 114 :ident :medium/trackCount :valueType #:db{:ident :db.type/long}} :medium/tracks #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of tracks found on this medium" :id 110 :ident :medium/tracks :isComponent true :valueType #:db{:ident :db.type/ref}} :release/abstractRelease #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "This release is the physical manifestation of the associated abstract release, e.g. the the 1984 US vinyl release of \"The Wall\" by Columbia, as opposed to the 2000 US CD release of \"The Wall\" by Capitol Records." :id 108 :ident :release/abstractRelease :valueType #:db{:ident :db.type/ref}} :release/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the release" :fulltext true :id 106 :ident :release/artistCredit :valueType #:db{:ident :db.type/string}} :release/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the release" :id 107 :ident :release/artists :valueType #:db{:ident :db.type/ref}} :release/barcode #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The barcode on the release packaging" :id 99 :ident :release/barcode :valueType #:db{:ident :db.type/string}} :release/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the recording was released" :id 95 :ident :release/country :valueType #:db{:ident :db.type/ref}} :release/day #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day of the release" :id 105 :ident :release/day :valueType #:db{:ident :db.type/long}} :release/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the release" :id 94 :ident :release/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :release/labels #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The label on which the recording was released" :id 96 :ident :release/labels :valueType #:db{:ident :db.type/ref}} :release/language #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The language used in the release" :id 98 :ident :release/language :valueType #:db{:ident :db.type/ref}} :release/media #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The various media (CDs, vinyl records, cassette tapes, etc.) included in the release." :id 101 :ident :release/media :isComponent true :valueType #:db{:ident :db.type/ref}} :release/month #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month of the release" :id 104 :ident :release/month :valueType #:db{:ident :db.type/long}} :release/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the release" :fulltext true :id 100 :ident :release/name :index true :valueType #:db{:ident :db.type/string}} :release/packaging #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The type of packaging used in the release, an enum, one of: :release.packaging/jewelCase, :release.packaging/slimJewelCase, :release.packaging/digipak, :release.packaging/other , :release.packaging/keepCase, :release.packaging/none, or :release.packaging/cardboardPaperSleeve" :id 102 :ident :release/packaging :valueType #:db{:ident :db.type/ref}} :release/script #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The script used in the release" :id 97 :ident :release/script :valueType #:db{:ident :db.type/ref}} :release/status #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The status of the release" :id 109 :ident :release/status :index true :valueType #:db{:ident :db.type/string}} :release/year #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year of the release" :id 103 :ident :release/year :index true :valueType #:db{:ident :db.type/long}} :script/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Name of written character set, e.g. Hebrew, Latin, Cyrillic" :id 65 :ident :script/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :track/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artists who contributed to the track" :fulltext true :id 116 :ident :track/artistCredit :valueType #:db{:ident :db.type/string}} :track/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The artists who contributed to the track" :id 115 :ident :track/artists :valueType #:db{:ident :db.type/ref}} :track/duration #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The duration of the track in msecs" :id 119 :ident :track/duration :index true :valueType #:db{:ident :db.type/long}} :track/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The track name" :fulltext true :id 118 :ident :track/name :index true :valueType #:db{:ident :db.type/string}} :track/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of the track relative to the other tracks on the medium" :id 117 :ident :track/position :valueType #:db{:ident :db.type/long}}}) (deftest test-db->schema (is (= (pcd/db->schema db-config db) db-schema-output))) (deftest test-schema->uniques (is (= (pcd/schema->uniques db-schema-output) #{:abstractRelease/gid :artist/gid :country/name :db/ident :label/gid :language/name :release/gid :script/name}))) (deftest test-inject-ident-subqueries (testing "add ident sub query part on ident fields" (is (= (pcd/inject-ident-subqueries {::pcd/ident-attributes #{:foo}} [:foo]) [{:foo [:db/ident]}])))) (deftest test-pick-ident-key (let [config (pcd/normalize-config (merge db-config {::pcd/conn conn}))] (testing "nothing available" (is (= (pcd/pick-ident-key config {}) nil)) (is (= (pcd/pick-ident-key config {:id 123 :foo "bar"}) nil))) (testing "pick from :db/id" (is (= (pcd/pick-ident-key config {:db/id 123}) 123))) (testing "picking from schema unique" (is (= (pcd/pick-ident-key config {:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) [:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"]))) (testing "prefer :db/id" (is (= (pcd/pick-ident-key config {:db/id 123 :artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) 123))))) (def index-oir-output `{:abstractRelease/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/artists {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/gid {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/name {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/type {#{:db/id} #{pcd/datomic-resolver}} :artist/country {#{:db/id} #{pcd/datomic-resolver}} :artist/endDay {#{:db/id} #{pcd/datomic-resolver}} :artist/endMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/endYear {#{:db/id} #{pcd/datomic-resolver}} :artist/gender {#{:db/id} #{pcd/datomic-resolver}} :artist/gid {#{:db/id} #{pcd/datomic-resolver}} :artist/name {#{:db/id} #{pcd/datomic-resolver}} :artist/sortName {#{:db/id} #{pcd/datomic-resolver}} :artist/startDay {#{:db/id} #{pcd/datomic-resolver}} :artist/startMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/startYear {#{:db/id} #{pcd/datomic-resolver}} :artist/type {#{:db/id} #{pcd/datomic-resolver}} :db/id {#{:abstractRelease/gid} #{pcd/datomic-resolver} #{:artist/gid} #{pcd/datomic-resolver} #{:country/name} #{pcd/datomic-resolver} #{:db/ident} #{pcd/datomic-resolver} #{:label/gid} #{pcd/datomic-resolver} #{:language/name} #{pcd/datomic-resolver} #{:release/gid} #{pcd/datomic-resolver} #{:script/name} #{pcd/datomic-resolver}} :country/name {#{:db/id} #{pcd/datomic-resolver}} :db.alter/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.excise/attrs {#{:db/id} #{pcd/datomic-resolver}} :db.excise/before {#{:db/id} #{pcd/datomic-resolver}} :db.excise/beforeT {#{:db/id} #{pcd/datomic-resolver}} :db.install/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.install/function {#{:db/id} #{pcd/datomic-resolver}} :db.install/partition {#{:db/id} #{pcd/datomic-resolver}} :db.install/valueType {#{:db/id} #{pcd/datomic-resolver}} :db.sys/partiallyIndexed {#{:db/id} #{pcd/datomic-resolver}} :db.sys/reId {#{:db/id} #{pcd/datomic-resolver}} :db/cardinality {#{:db/id} #{pcd/datomic-resolver}} :db/code {#{:db/id} #{pcd/datomic-resolver}} :db/doc {#{:db/id} #{pcd/datomic-resolver}} :db/excise {#{:db/id} #{pcd/datomic-resolver}} :db/fn {#{:db/id} #{pcd/datomic-resolver}} :db/fulltext {#{:db/id} #{pcd/datomic-resolver}} :db/ident {#{:db/id} #{pcd/datomic-resolver}} :db/index {#{:db/id} #{pcd/datomic-resolver}} :db/isComponent {#{:db/id} #{pcd/datomic-resolver}} :db/lang {#{:db/id} #{pcd/datomic-resolver}} :db/noHistory {#{:db/id} #{pcd/datomic-resolver}} :db/txInstant {#{:db/id} #{pcd/datomic-resolver}} :db/unique {#{:db/id} #{pcd/datomic-resolver}} :db/valueType {#{:db/id} #{pcd/datomic-resolver}} :fressian/tag {#{:db/id} #{pcd/datomic-resolver}} :label/country {#{:db/id} #{pcd/datomic-resolver}} :label/endDay {#{:db/id} #{pcd/datomic-resolver}} :label/endMonth {#{:db/id} #{pcd/datomic-resolver}} :label/endYear {#{:db/id} #{pcd/datomic-resolver}} :label/gid {#{:db/id} #{pcd/datomic-resolver}} :label/name {#{:db/id} #{pcd/datomic-resolver}} :label/sortName {#{:db/id} #{pcd/datomic-resolver}} :label/startDay {#{:db/id} #{pcd/datomic-resolver}} :label/startMonth {#{:db/id} #{pcd/datomic-resolver}} :label/startYear {#{:db/id} #{pcd/datomic-resolver}} :label/type {#{:db/id} #{pcd/datomic-resolver}} :language/name {#{:db/id} #{pcd/datomic-resolver}} :medium/format {#{:db/id} #{pcd/datomic-resolver}} :medium/name {#{:db/id} #{pcd/datomic-resolver}} :medium/position {#{:db/id} #{pcd/datomic-resolver}} :medium/trackCount {#{:db/id} #{pcd/datomic-resolver}} :medium/tracks {#{:db/id} #{pcd/datomic-resolver}} :release/abstractRelease {#{:db/id} #{pcd/datomic-resolver}} :release/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :release/artists {#{:db/id} #{pcd/datomic-resolver}} :release/barcode {#{:db/id} #{pcd/datomic-resolver}} :release/country {#{:db/id} #{pcd/datomic-resolver}} :release/day {#{:db/id} #{pcd/datomic-resolver}} :release/gid {#{:db/id} #{pcd/datomic-resolver}} :release/labels {#{:db/id} #{pcd/datomic-resolver}} :release/language {#{:db/id} #{pcd/datomic-resolver}} :release/media {#{:db/id} #{pcd/datomic-resolver}} :release/month {#{:db/id} #{pcd/datomic-resolver}} :release/name {#{:db/id} #{pcd/datomic-resolver}} :release/packaging {#{:db/id} #{pcd/datomic-resolver}} :release/script {#{:db/id} #{pcd/datomic-resolver}} :release/status {#{:db/id} #{pcd/datomic-resolver}} :release/year {#{:db/id} #{pcd/datomic-resolver}} :script/name {#{:db/id} #{pcd/datomic-resolver}} :track/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :track/artists {#{:db/id} #{pcd/datomic-resolver}} :track/duration {#{:db/id} #{pcd/datomic-resolver}} :track/name {#{:db/id} #{pcd/datomic-resolver}} :track/position {#{:db/id} #{pcd/datomic-resolver}}}) (def index-io-output {#{:abstractRelease/gid} {:db/id {}} #{:artist/gid} {:db/id {}} #{:db/id} {:abstractRelease/artistCredit {} :abstractRelease/artists {:db/id {}} :abstractRelease/gid {} :abstractRelease/name {} :abstractRelease/type {:db/id {}} :artist/country {:db/id {}} :artist/endDay {} :artist/endMonth {} :artist/endYear {} :artist/gender {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/startDay {} :artist/startMonth {} :artist/startYear {} :artist/type {:db/id {}} :country/name {} :fressian/tag {} :label/country {:db/id {}} :label/endDay {} :label/endMonth {} :label/endYear {} :label/gid {} :label/name {} :label/sortName {} :label/startDay {} :label/startMonth {} :label/startYear {} :label/type {:db/id {}} :language/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/abstractRelease {:db/id {}} :release/artistCredit {} :release/artists {:db/id {}} :release/barcode {} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :script/name {} :track/artistCredit {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:country/name} {:db/id {}} #{:db/ident} {:db/id {}} #{:label/gid} {:db/id {}} #{:language/name} {:db/id {}} #{:release/gid} {:db/id {}} #{:script/name} {:db/id {}}}) (def index-idents-output #{:abstractRelease/gid :artist/gid :country/name :db/id :db/ident :label/gid :language/name :release/gid :script/name}) (deftest test-index-schema (let [index (pcd/index-schema (pcd/normalize-config {::pcd/schema db-schema-output ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!}))] (is (= (::pc/index-oir index) index-oir-output)) (is (= (::pc/index-io index) index-io-output)) (is (= (::pc/idents index) index-idents-output)))) (def index-io-secure-output {#{:artist/gid} {:db/id {}} #{:country/name} {:db/id {}} #{:db/id} {:artist/country {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/type {:db/id {}} :country/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/artists {:db/id {}} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:release/gid} {:db/id {}}}) (def index-idents-secure-output #{:artist/gid :country/name :release/gid}) (deftest test-index-schema-secure (let [index (pcd/index-schema (pcd/normalize-config (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist)))] (is (= (::pc/index-oir index) '{:artist/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/sortName {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/type {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :country/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :db/id {#{:artist/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:country/name} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:release/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/format {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/trackCount {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/tracks {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/day {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/labels {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/language {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/media {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/month {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/packaging {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/script {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/status {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/year {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/duration {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}}})) (is (= (::pc/index-io index) index-io-secure-output)) (is (= (::pc/idents index) index-idents-secure-output)) (is (= (::pc/autocomplete-ignore index) #{:db/id})))) (deftest test-post-process-entity (is (= (pcd/post-process-entity {::pcd/ident-attributes #{:artist/type}} [:artist/type] {:artist/type {:db/ident :artist.type/person}}) {:artist/type :artist.type/person}))) (def super-name (pc/single-attr-resolver :artist/name :artist/super-name #(str "SUPER - " %))) (pc/defresolver years-active [env {:artist/keys [startYear endYear]}] {::pc/input #{:artist/startYear :artist/endYear} ::pc/output [:artist/active-years-count]} {:artist/active-years-count (- endYear startYear)}) (pc/defresolver artists-before-1600 [env _] {::pc/output [{:artist/artists-before-1600 [:db/id]}]} {:artist/artists-before-1600 (pcd/query-entities env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver artist-before-1600 [env _] {::pc/output [{:artist/artist-before-1600 [:db/id]}]} {:artist/artist-before-1600 (pcd/query-entity env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver all-mediums [env _] {::pc/output [{:all-mediums [:db/id]}]} {:all-mediums (pcd/query-entities env '{:where [[?e :medium/name _]]})}) (def registry [super-name years-active artists-before-1600 artist-before-1600 all-mediums]) (def parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-parser (testing "reading from :db/id" (is (= (parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name "Janis Joplin"}}))) (testing "reading from unique attribute" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "Janis Joplin"}}))) (testing "explicit db" (is (= (parser {::pcd/db (:db-after (d/with (d/db conn) [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not Janis Joplin"}]))} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not Janis Joplin"}}))) (comment "after transact data (I will not transact in your mbrainz), parser should take a new db" (d/transact conn [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not Janis Joplin"}]) (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not Janis Joplin"}}))) (testing "implicit dependency" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - Janis Joplin"}}))) (testing "process-query" (is (= (parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - Heinrich Schütz", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - Heinrich Schütz", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "partial missing information on entities" (is (= (parser {::pcd/db (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)} [{:all-mediums [:artist/name :medium/name]}]) {:all-mediums [{:artist/name "bar", :medium/name "3"} {:artist/name :com.wsscode.pathom.core/not-found, :medium/name "val"} {:artist/name "bla", :medium/name "6val"}]}))) (testing "nested complex dependency" (is (= (parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - Horst Jankowski"}]}}))) (testing "without subquery" (is (= (parser {} [:artist/artists-before-1600]) {:artist/artists-before-1600 [{:db/id 690493302253222} {:db/id 716881581319519}]})) (is (= (parser {} [:artist/artist-before-1600]) {:artist/artist-before-1600 {:db/id 690493302253222}}))) (testing "ident attributes" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/type :artist.type/person}})) (is (= (parser {} [{[:db/id 637716744120508] [{:artist/type [:db/id]}]}]) {[:db/id 637716744120508] {:artist/type {:db/id 17592186045423}}}))))) (def secure-parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-secure-parser (testing "don't allow access with :db/id" (is (= (secure-parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name ::p/not-found}}))) (testing "not found for fields not listed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :artist/gender]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "Janis Joplin" :artist/gender ::p/not-found}}))) (testing "not found for :db/id when its not allowed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :db/id]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "Janis Joplin" :db/id ::p/not-found}}))) (testing "implicit dependency" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - Janis Joplin"}}))) (testing "process-query" (is (= (secure-parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - Heinrich Schütz", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (secure-parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - Heinrich Schütz", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "nested complex dependency" (is (= (secure-parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - Horst Jankowski"}]}}))))) (comment (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema]) (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema-keys]) (pcp/compute-run-graph (merge (-> (pcd/index-schema (pcd/normalize-config (merge db-config {::pcd/conn conn}))) (pc/register registry)) {:edn-query-language.ast/node (eql/query->ast [{:release/artists [:artist/super-name]}]) ::pcp/available-data {:db/id {}}})) (parser {} [{::pc/indexes [::pc/index-oir]}]) :q [:find ?a :where [?e ?a _] [(< ?e 100)]] (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/active-years-count]}]) (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) (pcd/index-io {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (pcd/index-idents {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (parser {} [{:artist/artist-before-1600 [:artist/name :artist/active-years-count {:artist/country [:country/name]}]}]) (is (= (parser {} [{[:db/id 637716744120508] [:artist/type]}]) {[:db/id 637716744120508] {:artist/type :artist.type/person}})) (d/q '[:find (pull ?e [:artist/name]) :where [?e :medium/name _]] (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)) (->> (d/q '[:find ?attr ?type ?card :where [_ :db.install/attribute ?a] [?a :db/valueType ?t] [?a :db/cardinality ?c] [?a :db/ident ?attr] [?t :db/ident ?type] [?c :db/ident ?card]] db) (mapv #(zipmap [:db/ident :db/valueType :db/cardinality] %))) (pcd/db->schema db) (d/q '[:find ?id ?type ?gender ?e :in $ ?name :where [?e :artist/name ?name] [?e :artist/gid ?id] [?e :artist/type ?teid] [?teid :db/ident ?type] [?e :artist/gender ?geid] [?geid :db/ident ?gender]] db "Janis Joplin") (d/q '{:find [[(pull ?e [*]) ...]] :in [$ ?gid] :where [[?e :artist/gid ?gid]]} db #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f") (d/q '[:find (pull ?e [* :foo/bar]) . :in $ ?e] db 637716744120508))
13642
(ns com.wsscode.pathom.connect.datomic-test (:require [clojure.test :refer :all] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.connect.datomic :as pcd] [com.wsscode.pathom.connect.datomic.on-prem :refer [on-prem-config]] [com.wsscode.pathom.connect.planner :as pcp] [com.wsscode.pathom.core :as p] [datomic.api :as d] [edn-query-language.core :as eql])) (def uri "datomic:free://localhost:4334/mbrainz-1968-1973") (def conn (d/connect uri)) (def db (d/db conn)) (def db-config (assoc on-prem-config ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!)) (def whitelist #{:artist/country :artist/gid :artist/name :artist/sortName :artist/type :country/name :medium/format :medium/name :medium/position :medium/trackCount :medium/tracks :release/artists :release/country :release/day :release/gid :release/labels :release/language :release/media :release/month :release/name :release/packaging :release/script :release/status :release/year :track/artists :track/duration :track/name :track/position}) (def db-schema-output {:abstractRelease/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the abstract release" :fulltext true :id 82 :ident :abstractRelease/artistCredit :valueType #:db{:ident :db.type/string}} :abstractRelease/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the abstract release" :id 81 :ident :abstractRelease/artists :valueType #:db{:ident :db.type/ref}} :abstractRelease/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the abstract release" :id 78 :ident :abstractRelease/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :abstractRelease/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the abstract release" :id 79 :ident :abstractRelease/name :index true :valueType #:db{:ident :db.type/string}} :abstractRelease/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of: :release.type/album, :release.type/single, :release.type/ep, :release.type/audiobook, or :release.type/other" :id 80 :ident :abstractRelease/type :valueType #:db{:ident :db.type/ref}} :artist/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's country of origin" :id 71 :ident :artist/country :valueType #:db{:ident :db.type/ref}} :artist/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist stopped actively recording" :id 77 :ident :artist/endDay :valueType #:db{:ident :db.type/long}} :artist/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist stopped actively recording" :id 76 :ident :artist/endMonth :valueType #:db{:ident :db.type/long}} :artist/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist stopped actively recording" :id 75 :ident :artist/endYear :valueType #:db{:ident :db.type/long}} :artist/gender #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.gender/male, :artist.gender/female, or :artist.gender/other." :id 70 :ident :artist/gender :valueType #:db{:ident :db.type/ref}} :artist/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for an artist" :id 66 :ident :artist/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :artist/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name" :fulltext true :id 67 :ident :artist/name :index true :valueType #:db{:ident :db.type/string}} :artist/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name for use in alphabetical sorting, e.g. Beatles, The" :id 68 :ident :artist/sortName :index true :valueType #:db{:ident :db.type/string}} :artist/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist started actively recording" :id 74 :ident :artist/startDay :valueType #:db{:ident :db.type/long}} :artist/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist started actively recording" :id 73 :ident :artist/startMonth :valueType #:db{:ident :db.type/long}} :artist/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist started actively recording" :id 72 :ident :artist/startYear :index true :valueType #:db{:ident :db.type/long}} :artist/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.type/person, :artist.type/other, :artist.type/group." :id 69 :ident :artist/type :valueType #:db{:ident :db.type/ref}} :country/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the country" :id 63 :ident :country/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :db.alter/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will alter the definition of existing attribute v." :id 19 :ident :db.alter/attribute :valueType #:db{:ident :db.type/ref}} :db.excise/attrs #:db{:cardinality #:db{:ident :db.cardinality/many} :id 16 :ident :db.excise/attrs :valueType #:db{:ident :db.type/ref}} :db.excise/before #:db{:cardinality #:db{:ident :db.cardinality/one} :id 18 :ident :db.excise/before :valueType #:db{:ident :db.type/instant}} :db.excise/beforeT #:db{:cardinality #:db{:ident :db.cardinality/one} :id 17 :ident :db.excise/beforeT :valueType #:db{:ident :db.type/long}} :db.install/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as an attribute." :id 13 :ident :db.install/attribute :valueType #:db{:ident :db.type/ref}} :db.install/function #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a data function." :id 14 :ident :db.install/function :valueType #:db{:ident :db.type/ref}} :db.install/partition #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a partition." :id 11 :ident :db.install/partition :valueType #:db{:ident :db.type/ref}} :db.install/valueType #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a value type." :id 12 :ident :db.install/valueType :valueType #:db{:ident :db.type/ref}} :db.sys/partiallyIndexed #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute set to true for transactions not fully incorporated into the index" :id 8 :ident :db.sys/partiallyIndexed :valueType #:db{:ident :db.type/boolean}} :db.sys/reId #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute for an id e in the log that has been changed to id v in the index" :id 9 :ident :db.sys/reId :valueType #:db{:ident :db.type/ref}} :db/cardinality #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. Two possible values: :db.cardinality/one for single-valued attributes, and :db.cardinality/many for many-valued attributes. Defaults to :db.cardinality/one." :id 41 :ident :db/cardinality :valueType #:db{:ident :db.type/ref}} :db/code #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "String-valued attribute of a data function that contains the function's source code." :fulltext true :id 47 :ident :db/code :valueType #:db{:ident :db.type/string}} :db/doc #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Documentation string for an entity." :fulltext true :id 62 :ident :db/doc :valueType #:db{:ident :db.type/string}} :db/excise #:db{:cardinality #:db{:ident :db.cardinality/one} :id 15 :ident :db/excise :valueType #:db{:ident :db.type/ref}} :db/fn #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "A function-valued attribute for direct use by transactions and queries." :id 52 :ident :db/fn :valueType #:db{:ident :db.type/fn}} :db/fulltext #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create a fulltext search index for the attribute. Defaults to false." :id 51 :ident :db/fulltext :valueType #:db{:ident :db.type/boolean}} :db/ident #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute used to uniquely name an entity." :id 10 :ident :db/ident :unique #:db{:id 38} :valueType #:db{:ident :db.type/keyword}} :db/index #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create an AVET index for the attribute. Defaults to false." :id 44 :ident :db/index :valueType #:db{:ident :db.type/boolean}} :db/isComponent #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of attribute whose vtype is :db.type/ref. If true, then the attribute is a component of the entity referencing it. When you query for an entire entity, components are fetched automatically. Defaults to nil." :id 43 :ident :db/isComponent :valueType #:db{:ident :db.type/boolean}} :db/lang #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute of a data function. Value is a keyword naming the implementation language of the function. Legal values are :db.lang/java and :db.lang/clojure" :id 46 :ident :db/lang :valueType #:db{:ident :db.type/ref}} :db/noHistory #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, past values of the attribute are not retained after indexing. Defaults to false." :id 45 :ident :db/noHistory :valueType #:db{:ident :db.type/boolean}} :db/txInstant #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute whose value is a :db.type/instant. A :db/txInstant is recorded automatically with every transaction." :id 50 :ident :db/txInstant :index true :valueType #:db{:ident :db.type/instant}} :db/unique #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If value is :db.unique/value, then attribute value is unique to each entity. Attempts to insert a duplicate value for a temporary entity id will fail. If value is :db.unique/identity, then attribute value is unique, and upsert is enabled. Attempting to insert a duplicate value for a temporary entity id will cause all attributes associated with that temporary id to be merged with the entity already in the database. Defaults to nil." :id 42 :ident :db/unique :valueType #:db{:ident :db.type/ref}} :db/valueType #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute that specifies the attribute's value type. Built-in value types include, :db.type/keyword, :db.type/string, :db.type/ref, :db.type/instant, :db.type/long, :db.type/bigdec, :db.type/boolean, :db.type/float, :db.type/uuid, :db.type/double, :db.type/bigint, :db.type/uri." :id 40 :ident :db/valueType :valueType #:db{:ident :db.type/ref}} :fressian/tag #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Keyword-valued attribute of a value type that specifies the underlying fressian type used for serialization." :id 39 :ident :fressian/tag :index true :valueType #:db{:ident :db.type/keyword}} :label/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the record label is located" :id 87 :ident :label/country :valueType #:db{:ident :db.type/ref}} :label/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label stopped business" :id 93 :ident :label/endDay :valueType #:db{:ident :db.type/long}} :label/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label stopped business" :id 92 :ident :label/endMonth :valueType #:db{:ident :db.type/long}} :label/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label stopped business" :id 91 :ident :label/endYear :valueType #:db{:ident :db.type/long}} :label/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the record label" :id 83 :ident :label/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :label/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label" :fulltext true :id 84 :ident :label/name :index true :valueType #:db{:ident :db.type/string}} :label/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label for use in alphabetical sorting" :id 85 :ident :label/sortName :index true :valueType #:db{:ident :db.type/string}} :label/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label started business" :id 90 :ident :label/startDay :valueType #:db{:ident :db.type/long}} :label/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label started business" :id 89 :ident :label/startMonth :valueType #:db{:ident :db.type/long}} :label/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label started business" :id 88 :ident :label/startYear :index true :valueType #:db{:ident :db.type/long}} :label/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :label.type/distributor, :label.type/holding, :label.type/production, :label.type/originalProduction, :label.type/bootlegProduction, :label.type/reissueProduction, or :label.type/publisher." :id 86 :ident :label/type :valueType #:db{:ident :db.type/ref}} :language/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the written and spoken language" :id 64 :ident :language/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :medium/format #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The format of the medium. An enum with lots of possible values" :id 111 :ident :medium/format :valueType #:db{:ident :db.type/ref}} :medium/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the medium itself, distinct from the name of the release" :fulltext true :id 113 :ident :medium/name :valueType #:db{:ident :db.type/string}} :medium/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of this medium in the release relative to the other media, i.e. disc 1" :id 112 :ident :medium/position :valueType #:db{:ident :db.type/long}} :medium/trackCount #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The total number of tracks on the medium" :id 114 :ident :medium/trackCount :valueType #:db{:ident :db.type/long}} :medium/tracks #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of tracks found on this medium" :id 110 :ident :medium/tracks :isComponent true :valueType #:db{:ident :db.type/ref}} :release/abstractRelease #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "This release is the physical manifestation of the associated abstract release, e.g. the the 1984 US vinyl release of \"The Wall\" by Columbia, as opposed to the 2000 US CD release of \"The Wall\" by Capitol Records." :id 108 :ident :release/abstractRelease :valueType #:db{:ident :db.type/ref}} :release/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the release" :fulltext true :id 106 :ident :release/artistCredit :valueType #:db{:ident :db.type/string}} :release/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the release" :id 107 :ident :release/artists :valueType #:db{:ident :db.type/ref}} :release/barcode #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The barcode on the release packaging" :id 99 :ident :release/barcode :valueType #:db{:ident :db.type/string}} :release/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the recording was released" :id 95 :ident :release/country :valueType #:db{:ident :db.type/ref}} :release/day #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day of the release" :id 105 :ident :release/day :valueType #:db{:ident :db.type/long}} :release/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the release" :id 94 :ident :release/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :release/labels #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The label on which the recording was released" :id 96 :ident :release/labels :valueType #:db{:ident :db.type/ref}} :release/language #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The language used in the release" :id 98 :ident :release/language :valueType #:db{:ident :db.type/ref}} :release/media #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The various media (CDs, vinyl records, cassette tapes, etc.) included in the release." :id 101 :ident :release/media :isComponent true :valueType #:db{:ident :db.type/ref}} :release/month #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month of the release" :id 104 :ident :release/month :valueType #:db{:ident :db.type/long}} :release/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the release" :fulltext true :id 100 :ident :release/name :index true :valueType #:db{:ident :db.type/string}} :release/packaging #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The type of packaging used in the release, an enum, one of: :release.packaging/jewelCase, :release.packaging/slimJewelCase, :release.packaging/digipak, :release.packaging/other , :release.packaging/keepCase, :release.packaging/none, or :release.packaging/cardboardPaperSleeve" :id 102 :ident :release/packaging :valueType #:db{:ident :db.type/ref}} :release/script #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The script used in the release" :id 97 :ident :release/script :valueType #:db{:ident :db.type/ref}} :release/status #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The status of the release" :id 109 :ident :release/status :index true :valueType #:db{:ident :db.type/string}} :release/year #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year of the release" :id 103 :ident :release/year :index true :valueType #:db{:ident :db.type/long}} :script/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Name of written character set, e.g. Hebrew, Latin, Cyrillic" :id 65 :ident :script/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :track/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artists who contributed to the track" :fulltext true :id 116 :ident :track/artistCredit :valueType #:db{:ident :db.type/string}} :track/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The artists who contributed to the track" :id 115 :ident :track/artists :valueType #:db{:ident :db.type/ref}} :track/duration #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The duration of the track in msecs" :id 119 :ident :track/duration :index true :valueType #:db{:ident :db.type/long}} :track/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The track name" :fulltext true :id 118 :ident :track/name :index true :valueType #:db{:ident :db.type/string}} :track/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of the track relative to the other tracks on the medium" :id 117 :ident :track/position :valueType #:db{:ident :db.type/long}}}) (deftest test-db->schema (is (= (pcd/db->schema db-config db) db-schema-output))) (deftest test-schema->uniques (is (= (pcd/schema->uniques db-schema-output) #{:abstractRelease/gid :artist/gid :country/name :db/ident :label/gid :language/name :release/gid :script/name}))) (deftest test-inject-ident-subqueries (testing "add ident sub query part on ident fields" (is (= (pcd/inject-ident-subqueries {::pcd/ident-attributes #{:foo}} [:foo]) [{:foo [:db/ident]}])))) (deftest test-pick-ident-key (let [config (pcd/normalize-config (merge db-config {::pcd/conn conn}))] (testing "nothing available" (is (= (pcd/pick-ident-key config {}) nil)) (is (= (pcd/pick-ident-key config {:id 123 :foo "bar"}) nil))) (testing "pick from :db/id" (is (= (pcd/pick-ident-key config {:db/id 123}) 123))) (testing "picking from schema unique" (is (= (pcd/pick-ident-key config {:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) [:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"]))) (testing "prefer :db/id" (is (= (pcd/pick-ident-key config {:db/id 123 :artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) 123))))) (def index-oir-output `{:abstractRelease/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/artists {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/gid {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/name {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/type {#{:db/id} #{pcd/datomic-resolver}} :artist/country {#{:db/id} #{pcd/datomic-resolver}} :artist/endDay {#{:db/id} #{pcd/datomic-resolver}} :artist/endMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/endYear {#{:db/id} #{pcd/datomic-resolver}} :artist/gender {#{:db/id} #{pcd/datomic-resolver}} :artist/gid {#{:db/id} #{pcd/datomic-resolver}} :artist/name {#{:db/id} #{pcd/datomic-resolver}} :artist/sortName {#{:db/id} #{pcd/datomic-resolver}} :artist/startDay {#{:db/id} #{pcd/datomic-resolver}} :artist/startMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/startYear {#{:db/id} #{pcd/datomic-resolver}} :artist/type {#{:db/id} #{pcd/datomic-resolver}} :db/id {#{:abstractRelease/gid} #{pcd/datomic-resolver} #{:artist/gid} #{pcd/datomic-resolver} #{:country/name} #{pcd/datomic-resolver} #{:db/ident} #{pcd/datomic-resolver} #{:label/gid} #{pcd/datomic-resolver} #{:language/name} #{pcd/datomic-resolver} #{:release/gid} #{pcd/datomic-resolver} #{:script/name} #{pcd/datomic-resolver}} :country/name {#{:db/id} #{pcd/datomic-resolver}} :db.alter/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.excise/attrs {#{:db/id} #{pcd/datomic-resolver}} :db.excise/before {#{:db/id} #{pcd/datomic-resolver}} :db.excise/beforeT {#{:db/id} #{pcd/datomic-resolver}} :db.install/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.install/function {#{:db/id} #{pcd/datomic-resolver}} :db.install/partition {#{:db/id} #{pcd/datomic-resolver}} :db.install/valueType {#{:db/id} #{pcd/datomic-resolver}} :db.sys/partiallyIndexed {#{:db/id} #{pcd/datomic-resolver}} :db.sys/reId {#{:db/id} #{pcd/datomic-resolver}} :db/cardinality {#{:db/id} #{pcd/datomic-resolver}} :db/code {#{:db/id} #{pcd/datomic-resolver}} :db/doc {#{:db/id} #{pcd/datomic-resolver}} :db/excise {#{:db/id} #{pcd/datomic-resolver}} :db/fn {#{:db/id} #{pcd/datomic-resolver}} :db/fulltext {#{:db/id} #{pcd/datomic-resolver}} :db/ident {#{:db/id} #{pcd/datomic-resolver}} :db/index {#{:db/id} #{pcd/datomic-resolver}} :db/isComponent {#{:db/id} #{pcd/datomic-resolver}} :db/lang {#{:db/id} #{pcd/datomic-resolver}} :db/noHistory {#{:db/id} #{pcd/datomic-resolver}} :db/txInstant {#{:db/id} #{pcd/datomic-resolver}} :db/unique {#{:db/id} #{pcd/datomic-resolver}} :db/valueType {#{:db/id} #{pcd/datomic-resolver}} :fressian/tag {#{:db/id} #{pcd/datomic-resolver}} :label/country {#{:db/id} #{pcd/datomic-resolver}} :label/endDay {#{:db/id} #{pcd/datomic-resolver}} :label/endMonth {#{:db/id} #{pcd/datomic-resolver}} :label/endYear {#{:db/id} #{pcd/datomic-resolver}} :label/gid {#{:db/id} #{pcd/datomic-resolver}} :label/name {#{:db/id} #{pcd/datomic-resolver}} :label/sortName {#{:db/id} #{pcd/datomic-resolver}} :label/startDay {#{:db/id} #{pcd/datomic-resolver}} :label/startMonth {#{:db/id} #{pcd/datomic-resolver}} :label/startYear {#{:db/id} #{pcd/datomic-resolver}} :label/type {#{:db/id} #{pcd/datomic-resolver}} :language/name {#{:db/id} #{pcd/datomic-resolver}} :medium/format {#{:db/id} #{pcd/datomic-resolver}} :medium/name {#{:db/id} #{pcd/datomic-resolver}} :medium/position {#{:db/id} #{pcd/datomic-resolver}} :medium/trackCount {#{:db/id} #{pcd/datomic-resolver}} :medium/tracks {#{:db/id} #{pcd/datomic-resolver}} :release/abstractRelease {#{:db/id} #{pcd/datomic-resolver}} :release/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :release/artists {#{:db/id} #{pcd/datomic-resolver}} :release/barcode {#{:db/id} #{pcd/datomic-resolver}} :release/country {#{:db/id} #{pcd/datomic-resolver}} :release/day {#{:db/id} #{pcd/datomic-resolver}} :release/gid {#{:db/id} #{pcd/datomic-resolver}} :release/labels {#{:db/id} #{pcd/datomic-resolver}} :release/language {#{:db/id} #{pcd/datomic-resolver}} :release/media {#{:db/id} #{pcd/datomic-resolver}} :release/month {#{:db/id} #{pcd/datomic-resolver}} :release/name {#{:db/id} #{pcd/datomic-resolver}} :release/packaging {#{:db/id} #{pcd/datomic-resolver}} :release/script {#{:db/id} #{pcd/datomic-resolver}} :release/status {#{:db/id} #{pcd/datomic-resolver}} :release/year {#{:db/id} #{pcd/datomic-resolver}} :script/name {#{:db/id} #{pcd/datomic-resolver}} :track/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :track/artists {#{:db/id} #{pcd/datomic-resolver}} :track/duration {#{:db/id} #{pcd/datomic-resolver}} :track/name {#{:db/id} #{pcd/datomic-resolver}} :track/position {#{:db/id} #{pcd/datomic-resolver}}}) (def index-io-output {#{:abstractRelease/gid} {:db/id {}} #{:artist/gid} {:db/id {}} #{:db/id} {:abstractRelease/artistCredit {} :abstractRelease/artists {:db/id {}} :abstractRelease/gid {} :abstractRelease/name {} :abstractRelease/type {:db/id {}} :artist/country {:db/id {}} :artist/endDay {} :artist/endMonth {} :artist/endYear {} :artist/gender {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/startDay {} :artist/startMonth {} :artist/startYear {} :artist/type {:db/id {}} :country/name {} :fressian/tag {} :label/country {:db/id {}} :label/endDay {} :label/endMonth {} :label/endYear {} :label/gid {} :label/name {} :label/sortName {} :label/startDay {} :label/startMonth {} :label/startYear {} :label/type {:db/id {}} :language/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/abstractRelease {:db/id {}} :release/artistCredit {} :release/artists {:db/id {}} :release/barcode {} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :script/name {} :track/artistCredit {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:country/name} {:db/id {}} #{:db/ident} {:db/id {}} #{:label/gid} {:db/id {}} #{:language/name} {:db/id {}} #{:release/gid} {:db/id {}} #{:script/name} {:db/id {}}}) (def index-idents-output #{:abstractRelease/gid :artist/gid :country/name :db/id :db/ident :label/gid :language/name :release/gid :script/name}) (deftest test-index-schema (let [index (pcd/index-schema (pcd/normalize-config {::pcd/schema db-schema-output ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!}))] (is (= (::pc/index-oir index) index-oir-output)) (is (= (::pc/index-io index) index-io-output)) (is (= (::pc/idents index) index-idents-output)))) (def index-io-secure-output {#{:artist/gid} {:db/id {}} #{:country/name} {:db/id {}} #{:db/id} {:artist/country {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/type {:db/id {}} :country/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/artists {:db/id {}} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:release/gid} {:db/id {}}}) (def index-idents-secure-output #{:artist/gid :country/name :release/gid}) (deftest test-index-schema-secure (let [index (pcd/index-schema (pcd/normalize-config (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist)))] (is (= (::pc/index-oir index) '{:artist/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/sortName {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/type {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :country/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :db/id {#{:artist/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:country/name} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:release/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/format {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/trackCount {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/tracks {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/day {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/labels {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/language {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/media {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/month {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/packaging {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/script {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/status {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/year {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/duration {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}}})) (is (= (::pc/index-io index) index-io-secure-output)) (is (= (::pc/idents index) index-idents-secure-output)) (is (= (::pc/autocomplete-ignore index) #{:db/id})))) (deftest test-post-process-entity (is (= (pcd/post-process-entity {::pcd/ident-attributes #{:artist/type}} [:artist/type] {:artist/type {:db/ident :artist.type/person}}) {:artist/type :artist.type/person}))) (def super-name (pc/single-attr-resolver :artist/name :artist/super-name #(str "SUPER - " %))) (pc/defresolver years-active [env {:artist/keys [startYear endYear]}] {::pc/input #{:artist/startYear :artist/endYear} ::pc/output [:artist/active-years-count]} {:artist/active-years-count (- endYear startYear)}) (pc/defresolver artists-before-1600 [env _] {::pc/output [{:artist/artists-before-1600 [:db/id]}]} {:artist/artists-before-1600 (pcd/query-entities env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver artist-before-1600 [env _] {::pc/output [{:artist/artist-before-1600 [:db/id]}]} {:artist/artist-before-1600 (pcd/query-entity env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver all-mediums [env _] {::pc/output [{:all-mediums [:db/id]}]} {:all-mediums (pcd/query-entities env '{:where [[?e :medium/name _]]})}) (def registry [super-name years-active artists-before-1600 artist-before-1600 all-mediums]) (def parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-parser (testing "reading from :db/id" (is (= (parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name "<NAME>"}}))) (testing "reading from unique attribute" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "<NAME>"}}))) (testing "explicit db" (is (= (parser {::pcd/db (:db-after (d/with (d/db conn) [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not <NAME>"}]))} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not <NAME>"}}))) (comment "after transact data (I will not transact in your mbrainz), parser should take a new db" (d/transact conn [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not <NAME>"}]) (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not <NAME>"}}))) (testing "implicit dependency" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - <NAME>"}}))) (testing "process-query" (is (= (parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - <NAME>", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - <NAME>", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "partial missing information on entities" (is (= (parser {::pcd/db (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)} [{:all-mediums [:artist/name :medium/name]}]) {:all-mediums [{:artist/name "bar", :medium/name "3"} {:artist/name :com.wsscode.pathom.core/not-found, :medium/name "val"} {:artist/name "bla", :medium/name "6val"}]}))) (testing "nested complex dependency" (is (= (parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - <NAME>"}]}}))) (testing "without subquery" (is (= (parser {} [:artist/artists-before-1600]) {:artist/artists-before-1600 [{:db/id 690493302253222} {:db/id 716881581319519}]})) (is (= (parser {} [:artist/artist-before-1600]) {:artist/artist-before-1600 {:db/id 690493302253222}}))) (testing "ident attributes" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/type :artist.type/person}})) (is (= (parser {} [{[:db/id 637716744120508] [{:artist/type [:db/id]}]}]) {[:db/id 637716744120508] {:artist/type {:db/id 17592186045423}}}))))) (def secure-parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-secure-parser (testing "don't allow access with :db/id" (is (= (secure-parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name ::p/not-found}}))) (testing "not found for fields not listed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :artist/gender]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "<NAME>" :artist/gender ::p/not-found}}))) (testing "not found for :db/id when its not allowed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :db/id]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "<NAME>" :db/id ::p/not-found}}))) (testing "implicit dependency" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - <NAME>"}}))) (testing "process-query" (is (= (secure-parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - <NAME>", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (secure-parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - <NAME>", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "nested complex dependency" (is (= (secure-parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - <NAME>"}]}}))))) (comment (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema]) (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema-keys]) (pcp/compute-run-graph (merge (-> (pcd/index-schema (pcd/normalize-config (merge db-config {::pcd/conn conn}))) (pc/register registry)) {:edn-query-language.ast/node (eql/query->ast [{:release/artists [:artist/super-name]}]) ::pcp/available-data {:db/id {}}})) (parser {} [{::pc/indexes [::pc/index-oir]}]) :q [:find ?a :where [?e ?a _] [(< ?e 100)]] (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/active-years-count]}]) (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) (pcd/index-io {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (pcd/index-idents {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (parser {} [{:artist/artist-before-1600 [:artist/name :artist/active-years-count {:artist/country [:country/name]}]}]) (is (= (parser {} [{[:db/id 637716744120508] [:artist/type]}]) {[:db/id 637716744120508] {:artist/type :artist.type/person}})) (d/q '[:find (pull ?e [:artist/name]) :where [?e :medium/name _]] (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)) (->> (d/q '[:find ?attr ?type ?card :where [_ :db.install/attribute ?a] [?a :db/valueType ?t] [?a :db/cardinality ?c] [?a :db/ident ?attr] [?t :db/ident ?type] [?c :db/ident ?card]] db) (mapv #(zipmap [:db/ident :db/valueType :db/cardinality] %))) (pcd/db->schema db) (d/q '[:find ?id ?type ?gender ?e :in $ ?name :where [?e :artist/name ?name] [?e :artist/gid ?id] [?e :artist/type ?teid] [?teid :db/ident ?type] [?e :artist/gender ?geid] [?geid :db/ident ?gender]] db "<NAME>") (d/q '{:find [[(pull ?e [*]) ...]] :in [$ ?gid] :where [[?e :artist/gid ?gid]]} db #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f") (d/q '[:find (pull ?e [* :foo/bar]) . :in $ ?e] db 637716744120508))
true
(ns com.wsscode.pathom.connect.datomic-test (:require [clojure.test :refer :all] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.connect.datomic :as pcd] [com.wsscode.pathom.connect.datomic.on-prem :refer [on-prem-config]] [com.wsscode.pathom.connect.planner :as pcp] [com.wsscode.pathom.core :as p] [datomic.api :as d] [edn-query-language.core :as eql])) (def uri "datomic:free://localhost:4334/mbrainz-1968-1973") (def conn (d/connect uri)) (def db (d/db conn)) (def db-config (assoc on-prem-config ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!)) (def whitelist #{:artist/country :artist/gid :artist/name :artist/sortName :artist/type :country/name :medium/format :medium/name :medium/position :medium/trackCount :medium/tracks :release/artists :release/country :release/day :release/gid :release/labels :release/language :release/media :release/month :release/name :release/packaging :release/script :release/status :release/year :track/artists :track/duration :track/name :track/position}) (def db-schema-output {:abstractRelease/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the abstract release" :fulltext true :id 82 :ident :abstractRelease/artistCredit :valueType #:db{:ident :db.type/string}} :abstractRelease/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the abstract release" :id 81 :ident :abstractRelease/artists :valueType #:db{:ident :db.type/ref}} :abstractRelease/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the abstract release" :id 78 :ident :abstractRelease/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :abstractRelease/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the abstract release" :id 79 :ident :abstractRelease/name :index true :valueType #:db{:ident :db.type/string}} :abstractRelease/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of: :release.type/album, :release.type/single, :release.type/ep, :release.type/audiobook, or :release.type/other" :id 80 :ident :abstractRelease/type :valueType #:db{:ident :db.type/ref}} :artist/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's country of origin" :id 71 :ident :artist/country :valueType #:db{:ident :db.type/ref}} :artist/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist stopped actively recording" :id 77 :ident :artist/endDay :valueType #:db{:ident :db.type/long}} :artist/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist stopped actively recording" :id 76 :ident :artist/endMonth :valueType #:db{:ident :db.type/long}} :artist/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist stopped actively recording" :id 75 :ident :artist/endYear :valueType #:db{:ident :db.type/long}} :artist/gender #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.gender/male, :artist.gender/female, or :artist.gender/other." :id 70 :ident :artist/gender :valueType #:db{:ident :db.type/ref}} :artist/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for an artist" :id 66 :ident :artist/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :artist/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name" :fulltext true :id 67 :ident :artist/name :index true :valueType #:db{:ident :db.type/string}} :artist/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artist's name for use in alphabetical sorting, e.g. Beatles, The" :id 68 :ident :artist/sortName :index true :valueType #:db{:ident :db.type/string}} :artist/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the artist started actively recording" :id 74 :ident :artist/startDay :valueType #:db{:ident :db.type/long}} :artist/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the artist started actively recording" :id 73 :ident :artist/startMonth :valueType #:db{:ident :db.type/long}} :artist/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the artist started actively recording" :id 72 :ident :artist/startYear :index true :valueType #:db{:ident :db.type/long}} :artist/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :artist.type/person, :artist.type/other, :artist.type/group." :id 69 :ident :artist/type :valueType #:db{:ident :db.type/ref}} :country/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the country" :id 63 :ident :country/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :db.alter/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will alter the definition of existing attribute v." :id 19 :ident :db.alter/attribute :valueType #:db{:ident :db.type/ref}} :db.excise/attrs #:db{:cardinality #:db{:ident :db.cardinality/many} :id 16 :ident :db.excise/attrs :valueType #:db{:ident :db.type/ref}} :db.excise/before #:db{:cardinality #:db{:ident :db.cardinality/one} :id 18 :ident :db.excise/before :valueType #:db{:ident :db.type/instant}} :db.excise/beforeT #:db{:cardinality #:db{:ident :db.cardinality/one} :id 17 :ident :db.excise/beforeT :valueType #:db{:ident :db.type/long}} :db.install/attribute #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as an attribute." :id 13 :ident :db.install/attribute :valueType #:db{:ident :db.type/ref}} :db.install/function #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a data function." :id 14 :ident :db.install/function :valueType #:db{:ident :db.type/ref}} :db.install/partition #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a partition." :id 11 :ident :db.install/partition :valueType #:db{:ident :db.type/ref}} :db.install/valueType #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "System attribute with type :db.type/ref. Asserting this attribute on :db.part/db with value v will install v as a value type." :id 12 :ident :db.install/valueType :valueType #:db{:ident :db.type/ref}} :db.sys/partiallyIndexed #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute set to true for transactions not fully incorporated into the index" :id 8 :ident :db.sys/partiallyIndexed :valueType #:db{:ident :db.type/boolean}} :db.sys/reId #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "System-assigned attribute for an id e in the log that has been changed to id v in the index" :id 9 :ident :db.sys/reId :valueType #:db{:ident :db.type/ref}} :db/cardinality #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. Two possible values: :db.cardinality/one for single-valued attributes, and :db.cardinality/many for many-valued attributes. Defaults to :db.cardinality/one." :id 41 :ident :db/cardinality :valueType #:db{:ident :db.type/ref}} :db/code #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "String-valued attribute of a data function that contains the function's source code." :fulltext true :id 47 :ident :db/code :valueType #:db{:ident :db.type/string}} :db/doc #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Documentation string for an entity." :fulltext true :id 62 :ident :db/doc :valueType #:db{:ident :db.type/string}} :db/excise #:db{:cardinality #:db{:ident :db.cardinality/one} :id 15 :ident :db/excise :valueType #:db{:ident :db.type/ref}} :db/fn #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "A function-valued attribute for direct use by transactions and queries." :id 52 :ident :db/fn :valueType #:db{:ident :db.type/fn}} :db/fulltext #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create a fulltext search index for the attribute. Defaults to false." :id 51 :ident :db/fulltext :valueType #:db{:ident :db.type/boolean}} :db/ident #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute used to uniquely name an entity." :id 10 :ident :db/ident :unique #:db{:id 38} :valueType #:db{:ident :db.type/keyword}} :db/index #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, create an AVET index for the attribute. Defaults to false." :id 44 :ident :db/index :valueType #:db{:ident :db.type/boolean}} :db/isComponent #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of attribute whose vtype is :db.type/ref. If true, then the attribute is a component of the entity referencing it. When you query for an entire entity, components are fetched automatically. Defaults to nil." :id 43 :ident :db/isComponent :valueType #:db{:ident :db.type/boolean}} :db/lang #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute of a data function. Value is a keyword naming the implementation language of the function. Legal values are :db.lang/java and :db.lang/clojure" :id 46 :ident :db/lang :valueType #:db{:ident :db.type/ref}} :db/noHistory #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If true, past values of the attribute are not retained after indexing. Defaults to false." :id 45 :ident :db/noHistory :valueType #:db{:ident :db.type/boolean}} :db/txInstant #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Attribute whose value is a :db.type/instant. A :db/txInstant is recorded automatically with every transaction." :id 50 :ident :db/txInstant :index true :valueType #:db{:ident :db.type/instant}} :db/unique #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute. If value is :db.unique/value, then attribute value is unique to each entity. Attempts to insert a duplicate value for a temporary entity id will fail. If value is :db.unique/identity, then attribute value is unique, and upsert is enabled. Attempting to insert a duplicate value for a temporary entity id will cause all attributes associated with that temporary id to be merged with the entity already in the database. Defaults to nil." :id 42 :ident :db/unique :valueType #:db{:ident :db.type/ref}} :db/valueType #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Property of an attribute that specifies the attribute's value type. Built-in value types include, :db.type/keyword, :db.type/string, :db.type/ref, :db.type/instant, :db.type/long, :db.type/bigdec, :db.type/boolean, :db.type/float, :db.type/uuid, :db.type/double, :db.type/bigint, :db.type/uri." :id 40 :ident :db/valueType :valueType #:db{:ident :db.type/ref}} :fressian/tag #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Keyword-valued attribute of a value type that specifies the underlying fressian type used for serialization." :id 39 :ident :fressian/tag :index true :valueType #:db{:ident :db.type/keyword}} :label/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the record label is located" :id 87 :ident :label/country :valueType #:db{:ident :db.type/ref}} :label/endDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label stopped business" :id 93 :ident :label/endDay :valueType #:db{:ident :db.type/long}} :label/endMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label stopped business" :id 92 :ident :label/endMonth :valueType #:db{:ident :db.type/long}} :label/endYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label stopped business" :id 91 :ident :label/endYear :valueType #:db{:ident :db.type/long}} :label/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the record label" :id 83 :ident :label/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :label/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label" :fulltext true :id 84 :ident :label/name :index true :valueType #:db{:ident :db.type/string}} :label/sortName #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the record label for use in alphabetical sorting" :id 85 :ident :label/sortName :index true :valueType #:db{:ident :db.type/string}} :label/startDay #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day the label started business" :id 90 :ident :label/startDay :valueType #:db{:ident :db.type/long}} :label/startMonth #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month the label started business" :id 89 :ident :label/startMonth :valueType #:db{:ident :db.type/long}} :label/startYear #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year the label started business" :id 88 :ident :label/startYear :index true :valueType #:db{:ident :db.type/long}} :label/type #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Enum, one of :label.type/distributor, :label.type/holding, :label.type/production, :label.type/originalProduction, :label.type/bootlegProduction, :label.type/reissueProduction, or :label.type/publisher." :id 86 :ident :label/type :valueType #:db{:ident :db.type/ref}} :language/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the written and spoken language" :id 64 :ident :language/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :medium/format #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The format of the medium. An enum with lots of possible values" :id 111 :ident :medium/format :valueType #:db{:ident :db.type/ref}} :medium/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the medium itself, distinct from the name of the release" :fulltext true :id 113 :ident :medium/name :valueType #:db{:ident :db.type/string}} :medium/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of this medium in the release relative to the other media, i.e. disc 1" :id 112 :ident :medium/position :valueType #:db{:ident :db.type/long}} :medium/trackCount #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The total number of tracks on the medium" :id 114 :ident :medium/trackCount :valueType #:db{:ident :db.type/long}} :medium/tracks #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of tracks found on this medium" :id 110 :ident :medium/tracks :isComponent true :valueType #:db{:ident :db.type/ref}} :release/abstractRelease #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "This release is the physical manifestation of the associated abstract release, e.g. the the 1984 US vinyl release of \"The Wall\" by Columbia, as opposed to the 2000 US CD release of \"The Wall\" by Capitol Records." :id 108 :ident :release/abstractRelease :valueType #:db{:ident :db.type/ref}} :release/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The string represenation of the artist(s) to be credited on the release" :fulltext true :id 106 :ident :release/artistCredit :valueType #:db{:ident :db.type/string}} :release/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The set of artists contributing to the release" :id 107 :ident :release/artists :valueType #:db{:ident :db.type/ref}} :release/barcode #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The barcode on the release packaging" :id 99 :ident :release/barcode :valueType #:db{:ident :db.type/string}} :release/country #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The country where the recording was released" :id 95 :ident :release/country :valueType #:db{:ident :db.type/ref}} :release/day #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The day of the release" :id 105 :ident :release/day :valueType #:db{:ident :db.type/long}} :release/gid #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The globally unique MusicBrainz ID for the release" :id 94 :ident :release/gid :unique #:db{:id 38} :valueType #:db{:ident :db.type/uuid}} :release/labels #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The label on which the recording was released" :id 96 :ident :release/labels :valueType #:db{:ident :db.type/ref}} :release/language #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The language used in the release" :id 98 :ident :release/language :valueType #:db{:ident :db.type/ref}} :release/media #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The various media (CDs, vinyl records, cassette tapes, etc.) included in the release." :id 101 :ident :release/media :isComponent true :valueType #:db{:ident :db.type/ref}} :release/month #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The month of the release" :id 104 :ident :release/month :valueType #:db{:ident :db.type/long}} :release/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The name of the release" :fulltext true :id 100 :ident :release/name :index true :valueType #:db{:ident :db.type/string}} :release/packaging #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The type of packaging used in the release, an enum, one of: :release.packaging/jewelCase, :release.packaging/slimJewelCase, :release.packaging/digipak, :release.packaging/other , :release.packaging/keepCase, :release.packaging/none, or :release.packaging/cardboardPaperSleeve" :id 102 :ident :release/packaging :valueType #:db{:ident :db.type/ref}} :release/script #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The script used in the release" :id 97 :ident :release/script :valueType #:db{:ident :db.type/ref}} :release/status #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The status of the release" :id 109 :ident :release/status :index true :valueType #:db{:ident :db.type/string}} :release/year #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The year of the release" :id 103 :ident :release/year :index true :valueType #:db{:ident :db.type/long}} :script/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "Name of written character set, e.g. Hebrew, Latin, Cyrillic" :id 65 :ident :script/name :unique #:db{:id 37} :valueType #:db{:ident :db.type/string}} :track/artistCredit #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The artists who contributed to the track" :fulltext true :id 116 :ident :track/artistCredit :valueType #:db{:ident :db.type/string}} :track/artists #:db{:cardinality #:db{:ident :db.cardinality/many} :doc "The artists who contributed to the track" :id 115 :ident :track/artists :valueType #:db{:ident :db.type/ref}} :track/duration #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The duration of the track in msecs" :id 119 :ident :track/duration :index true :valueType #:db{:ident :db.type/long}} :track/name #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The track name" :fulltext true :id 118 :ident :track/name :index true :valueType #:db{:ident :db.type/string}} :track/position #:db{:cardinality #:db{:ident :db.cardinality/one} :doc "The position of the track relative to the other tracks on the medium" :id 117 :ident :track/position :valueType #:db{:ident :db.type/long}}}) (deftest test-db->schema (is (= (pcd/db->schema db-config db) db-schema-output))) (deftest test-schema->uniques (is (= (pcd/schema->uniques db-schema-output) #{:abstractRelease/gid :artist/gid :country/name :db/ident :label/gid :language/name :release/gid :script/name}))) (deftest test-inject-ident-subqueries (testing "add ident sub query part on ident fields" (is (= (pcd/inject-ident-subqueries {::pcd/ident-attributes #{:foo}} [:foo]) [{:foo [:db/ident]}])))) (deftest test-pick-ident-key (let [config (pcd/normalize-config (merge db-config {::pcd/conn conn}))] (testing "nothing available" (is (= (pcd/pick-ident-key config {}) nil)) (is (= (pcd/pick-ident-key config {:id 123 :foo "bar"}) nil))) (testing "pick from :db/id" (is (= (pcd/pick-ident-key config {:db/id 123}) 123))) (testing "picking from schema unique" (is (= (pcd/pick-ident-key config {:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) [:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"]))) (testing "prefer :db/id" (is (= (pcd/pick-ident-key config {:db/id 123 :artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"}) 123))))) (def index-oir-output `{:abstractRelease/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/artists {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/gid {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/name {#{:db/id} #{pcd/datomic-resolver}} :abstractRelease/type {#{:db/id} #{pcd/datomic-resolver}} :artist/country {#{:db/id} #{pcd/datomic-resolver}} :artist/endDay {#{:db/id} #{pcd/datomic-resolver}} :artist/endMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/endYear {#{:db/id} #{pcd/datomic-resolver}} :artist/gender {#{:db/id} #{pcd/datomic-resolver}} :artist/gid {#{:db/id} #{pcd/datomic-resolver}} :artist/name {#{:db/id} #{pcd/datomic-resolver}} :artist/sortName {#{:db/id} #{pcd/datomic-resolver}} :artist/startDay {#{:db/id} #{pcd/datomic-resolver}} :artist/startMonth {#{:db/id} #{pcd/datomic-resolver}} :artist/startYear {#{:db/id} #{pcd/datomic-resolver}} :artist/type {#{:db/id} #{pcd/datomic-resolver}} :db/id {#{:abstractRelease/gid} #{pcd/datomic-resolver} #{:artist/gid} #{pcd/datomic-resolver} #{:country/name} #{pcd/datomic-resolver} #{:db/ident} #{pcd/datomic-resolver} #{:label/gid} #{pcd/datomic-resolver} #{:language/name} #{pcd/datomic-resolver} #{:release/gid} #{pcd/datomic-resolver} #{:script/name} #{pcd/datomic-resolver}} :country/name {#{:db/id} #{pcd/datomic-resolver}} :db.alter/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.excise/attrs {#{:db/id} #{pcd/datomic-resolver}} :db.excise/before {#{:db/id} #{pcd/datomic-resolver}} :db.excise/beforeT {#{:db/id} #{pcd/datomic-resolver}} :db.install/attribute {#{:db/id} #{pcd/datomic-resolver}} :db.install/function {#{:db/id} #{pcd/datomic-resolver}} :db.install/partition {#{:db/id} #{pcd/datomic-resolver}} :db.install/valueType {#{:db/id} #{pcd/datomic-resolver}} :db.sys/partiallyIndexed {#{:db/id} #{pcd/datomic-resolver}} :db.sys/reId {#{:db/id} #{pcd/datomic-resolver}} :db/cardinality {#{:db/id} #{pcd/datomic-resolver}} :db/code {#{:db/id} #{pcd/datomic-resolver}} :db/doc {#{:db/id} #{pcd/datomic-resolver}} :db/excise {#{:db/id} #{pcd/datomic-resolver}} :db/fn {#{:db/id} #{pcd/datomic-resolver}} :db/fulltext {#{:db/id} #{pcd/datomic-resolver}} :db/ident {#{:db/id} #{pcd/datomic-resolver}} :db/index {#{:db/id} #{pcd/datomic-resolver}} :db/isComponent {#{:db/id} #{pcd/datomic-resolver}} :db/lang {#{:db/id} #{pcd/datomic-resolver}} :db/noHistory {#{:db/id} #{pcd/datomic-resolver}} :db/txInstant {#{:db/id} #{pcd/datomic-resolver}} :db/unique {#{:db/id} #{pcd/datomic-resolver}} :db/valueType {#{:db/id} #{pcd/datomic-resolver}} :fressian/tag {#{:db/id} #{pcd/datomic-resolver}} :label/country {#{:db/id} #{pcd/datomic-resolver}} :label/endDay {#{:db/id} #{pcd/datomic-resolver}} :label/endMonth {#{:db/id} #{pcd/datomic-resolver}} :label/endYear {#{:db/id} #{pcd/datomic-resolver}} :label/gid {#{:db/id} #{pcd/datomic-resolver}} :label/name {#{:db/id} #{pcd/datomic-resolver}} :label/sortName {#{:db/id} #{pcd/datomic-resolver}} :label/startDay {#{:db/id} #{pcd/datomic-resolver}} :label/startMonth {#{:db/id} #{pcd/datomic-resolver}} :label/startYear {#{:db/id} #{pcd/datomic-resolver}} :label/type {#{:db/id} #{pcd/datomic-resolver}} :language/name {#{:db/id} #{pcd/datomic-resolver}} :medium/format {#{:db/id} #{pcd/datomic-resolver}} :medium/name {#{:db/id} #{pcd/datomic-resolver}} :medium/position {#{:db/id} #{pcd/datomic-resolver}} :medium/trackCount {#{:db/id} #{pcd/datomic-resolver}} :medium/tracks {#{:db/id} #{pcd/datomic-resolver}} :release/abstractRelease {#{:db/id} #{pcd/datomic-resolver}} :release/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :release/artists {#{:db/id} #{pcd/datomic-resolver}} :release/barcode {#{:db/id} #{pcd/datomic-resolver}} :release/country {#{:db/id} #{pcd/datomic-resolver}} :release/day {#{:db/id} #{pcd/datomic-resolver}} :release/gid {#{:db/id} #{pcd/datomic-resolver}} :release/labels {#{:db/id} #{pcd/datomic-resolver}} :release/language {#{:db/id} #{pcd/datomic-resolver}} :release/media {#{:db/id} #{pcd/datomic-resolver}} :release/month {#{:db/id} #{pcd/datomic-resolver}} :release/name {#{:db/id} #{pcd/datomic-resolver}} :release/packaging {#{:db/id} #{pcd/datomic-resolver}} :release/script {#{:db/id} #{pcd/datomic-resolver}} :release/status {#{:db/id} #{pcd/datomic-resolver}} :release/year {#{:db/id} #{pcd/datomic-resolver}} :script/name {#{:db/id} #{pcd/datomic-resolver}} :track/artistCredit {#{:db/id} #{pcd/datomic-resolver}} :track/artists {#{:db/id} #{pcd/datomic-resolver}} :track/duration {#{:db/id} #{pcd/datomic-resolver}} :track/name {#{:db/id} #{pcd/datomic-resolver}} :track/position {#{:db/id} #{pcd/datomic-resolver}}}) (def index-io-output {#{:abstractRelease/gid} {:db/id {}} #{:artist/gid} {:db/id {}} #{:db/id} {:abstractRelease/artistCredit {} :abstractRelease/artists {:db/id {}} :abstractRelease/gid {} :abstractRelease/name {} :abstractRelease/type {:db/id {}} :artist/country {:db/id {}} :artist/endDay {} :artist/endMonth {} :artist/endYear {} :artist/gender {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/startDay {} :artist/startMonth {} :artist/startYear {} :artist/type {:db/id {}} :country/name {} :fressian/tag {} :label/country {:db/id {}} :label/endDay {} :label/endMonth {} :label/endYear {} :label/gid {} :label/name {} :label/sortName {} :label/startDay {} :label/startMonth {} :label/startYear {} :label/type {:db/id {}} :language/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/abstractRelease {:db/id {}} :release/artistCredit {} :release/artists {:db/id {}} :release/barcode {} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :script/name {} :track/artistCredit {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:country/name} {:db/id {}} #{:db/ident} {:db/id {}} #{:label/gid} {:db/id {}} #{:language/name} {:db/id {}} #{:release/gid} {:db/id {}} #{:script/name} {:db/id {}}}) (def index-idents-output #{:abstractRelease/gid :artist/gid :country/name :db/id :db/ident :label/gid :language/name :release/gid :script/name}) (deftest test-index-schema (let [index (pcd/index-schema (pcd/normalize-config {::pcd/schema db-schema-output ::pcd/whitelist ::pcd/DANGER_ALLOW_ALL!}))] (is (= (::pc/index-oir index) index-oir-output)) (is (= (::pc/index-io index) index-io-output)) (is (= (::pc/idents index) index-idents-output)))) (def index-io-secure-output {#{:artist/gid} {:db/id {}} #{:country/name} {:db/id {}} #{:db/id} {:artist/country {:db/id {}} :artist/gid {} :artist/name {} :artist/sortName {} :artist/type {:db/id {}} :country/name {} :medium/format {:db/id {}} :medium/name {} :medium/position {} :medium/trackCount {} :medium/tracks {:db/id {}} :release/artists {:db/id {}} :release/country {:db/id {}} :release/day {} :release/gid {} :release/labels {:db/id {}} :release/language {:db/id {}} :release/media {:db/id {}} :release/month {} :release/name {} :release/packaging {:db/id {}} :release/script {:db/id {}} :release/status {} :release/year {} :track/artists {:db/id {}} :track/duration {} :track/name {} :track/position {}} #{:release/gid} {:db/id {}}}) (def index-idents-secure-output #{:artist/gid :country/name :release/gid}) (deftest test-index-schema-secure (let [index (pcd/index-schema (pcd/normalize-config (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist)))] (is (= (::pc/index-oir index) '{:artist/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/sortName {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :artist/type {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :country/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :db/id {#{:artist/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:country/name} #{com.wsscode.pathom.connect.datomic/datomic-resolver} #{:release/gid} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/format {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/trackCount {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :medium/tracks {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/country {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/day {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/gid {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/labels {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/language {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/media {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/month {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/packaging {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/script {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/status {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :release/year {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/artists {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/duration {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/name {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}} :track/position {#{:db/id} #{com.wsscode.pathom.connect.datomic/datomic-resolver}}})) (is (= (::pc/index-io index) index-io-secure-output)) (is (= (::pc/idents index) index-idents-secure-output)) (is (= (::pc/autocomplete-ignore index) #{:db/id})))) (deftest test-post-process-entity (is (= (pcd/post-process-entity {::pcd/ident-attributes #{:artist/type}} [:artist/type] {:artist/type {:db/ident :artist.type/person}}) {:artist/type :artist.type/person}))) (def super-name (pc/single-attr-resolver :artist/name :artist/super-name #(str "SUPER - " %))) (pc/defresolver years-active [env {:artist/keys [startYear endYear]}] {::pc/input #{:artist/startYear :artist/endYear} ::pc/output [:artist/active-years-count]} {:artist/active-years-count (- endYear startYear)}) (pc/defresolver artists-before-1600 [env _] {::pc/output [{:artist/artists-before-1600 [:db/id]}]} {:artist/artists-before-1600 (pcd/query-entities env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver artist-before-1600 [env _] {::pc/output [{:artist/artist-before-1600 [:db/id]}]} {:artist/artist-before-1600 (pcd/query-entity env '{:where [[?e :artist/name ?name] [?e :artist/startYear ?year] [(< ?year 1600)]]})}) (pc/defresolver all-mediums [env _] {::pc/output [{:all-mediums [:db/id]}]} {:all-mediums (pcd/query-entities env '{:where [[?e :medium/name _]]})}) (def registry [super-name years-active artists-before-1600 artist-before-1600 all-mediums]) (def parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-parser (testing "reading from :db/id" (is (= (parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name "PI:NAME:<NAME>END_PI"}}))) (testing "reading from unique attribute" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "PI:NAME:<NAME>END_PI"}}))) (testing "explicit db" (is (= (parser {::pcd/db (:db-after (d/with (d/db conn) [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not PI:NAME:<NAME>END_PI"}]))} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not PI:NAME:<NAME>END_PI"}}))) (comment "after transact data (I will not transact in your mbrainz), parser should take a new db" (d/transact conn [{:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f" :artist/name "not PI:NAME:<NAME>END_PI"}]) (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "not PI:NAME:<NAME>END_PI"}}))) (testing "implicit dependency" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - PI:NAME:<NAME>END_PI"}}))) (testing "process-query" (is (= (parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - PI:NAME:<NAME>END_PI", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - PI:NAME:<NAME>END_PI", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "partial missing information on entities" (is (= (parser {::pcd/db (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)} [{:all-mediums [:artist/name :medium/name]}]) {:all-mediums [{:artist/name "bar", :medium/name "3"} {:artist/name :com.wsscode.pathom.core/not-found, :medium/name "val"} {:artist/name "bla", :medium/name "6val"}]}))) (testing "nested complex dependency" (is (= (parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - PI:NAME:<NAME>END_PI"}]}}))) (testing "without subquery" (is (= (parser {} [:artist/artists-before-1600]) {:artist/artists-before-1600 [{:db/id 690493302253222} {:db/id 716881581319519}]})) (is (= (parser {} [:artist/artist-before-1600]) {:artist/artist-before-1600 {:db/id 690493302253222}}))) (testing "ident attributes" (is (= (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/type :artist.type/person}})) (is (= (parser {} [{[:db/id 637716744120508] [{:artist/type [:db/id]}]}]) {[:db/id 637716744120508] {:artist/type {:db/id 17592186045423}}}))))) (def secure-parser (p/parser {::p/env {::p/reader [p/map-reader pc/reader3 pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/mutate pc/mutate ::p/plugins [(pc/connect-plugin {::pc/register registry}) (pcd/datomic-connect-plugin (assoc db-config ::pcd/conn conn ::pcd/whitelist whitelist ::pcd/ident-attributes #{:artist/type})) p/error-handler-plugin p/trace-plugin]})) (deftest test-datomic-secure-parser (testing "don't allow access with :db/id" (is (= (secure-parser {} [{[:db/id 637716744120508] [:artist/name]}]) {[:db/id 637716744120508] {:artist/name ::p/not-found}}))) (testing "not found for fields not listed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :artist/gender]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "PI:NAME:<NAME>END_PI" :artist/gender ::p/not-found}}))) (testing "not found for :db/id when its not allowed" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/name :db/id]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/name "PI:NAME:<NAME>END_PI" :db/id ::p/not-found}}))) (testing "implicit dependency" (is (= (secure-parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/super-name]}]) {[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] {:artist/super-name "SUPER - PI:NAME:<NAME>END_PI"}}))) (testing "process-query" (is (= (secure-parser {} [{:artist/artists-before-1600 [:artist/super-name {:artist/country [:country/name]}]}]) {:artist/artists-before-1600 [{:artist/super-name "SUPER - PI:NAME:<NAME>END_PI", :artist/country {:country/name "Germany"}} {:artist/super-name "SUPER - Choir of King's College, Cambridge", :artist/country {:country/name "United Kingdom"}}]})) (is (= (secure-parser {} [{:artist/artist-before-1600 [:artist/super-name {:artist/country [:country/name :db/id]}]}]) {:artist/artist-before-1600 {:artist/super-name "SUPER - PI:NAME:<NAME>END_PI", :artist/country {:country/name "Germany" :db/id 17592186045657}}})) (testing "nested complex dependency" (is (= (secure-parser {} [{[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] [{:release/artists [:artist/super-name]}]}]) {[:release/gid #uuid"b89a6f8b-5784-41d2-973d-dcd4d99b05c2"] {:release/artists [{:artist/super-name "SUPER - PI:NAME:<NAME>END_PI"}]}}))))) (comment (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema]) (pcd/config-parser db-config {::pcd/conn conn} [::pcd/schema-keys]) (pcp/compute-run-graph (merge (-> (pcd/index-schema (pcd/normalize-config (merge db-config {::pcd/conn conn}))) (pc/register registry)) {:edn-query-language.ast/node (eql/query->ast [{:release/artists [:artist/super-name]}]) ::pcp/available-data {:db/id {}}})) (parser {} [{::pc/indexes [::pc/index-oir]}]) :q [:find ?a :where [?e ?a _] [(< ?e 100)]] (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/active-years-count]}]) (parser {} [{[:artist/gid #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f"] [:artist/type]}]) (pcd/index-io {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (pcd/index-idents {::pcd/schema db-schema-output ::pcd/schema-uniques (pcd/schema->uniques db-schema-output)}) (parser {} [{:artist/artist-before-1600 [:artist/name :artist/active-years-count {:artist/country [:country/name]}]}]) (is (= (parser {} [{[:db/id 637716744120508] [:artist/type]}]) {[:db/id 637716744120508] {:artist/type :artist.type/person}})) (d/q '[:find (pull ?e [:artist/name]) :where [?e :medium/name _]] (-> (d/with db [{:medium/name "val"} {:medium/name "6val" :artist/name "bla"} {:medium/name "3" :artist/name "bar"}]) :db-after)) (->> (d/q '[:find ?attr ?type ?card :where [_ :db.install/attribute ?a] [?a :db/valueType ?t] [?a :db/cardinality ?c] [?a :db/ident ?attr] [?t :db/ident ?type] [?c :db/ident ?card]] db) (mapv #(zipmap [:db/ident :db/valueType :db/cardinality] %))) (pcd/db->schema db) (d/q '[:find ?id ?type ?gender ?e :in $ ?name :where [?e :artist/name ?name] [?e :artist/gid ?id] [?e :artist/type ?teid] [?teid :db/ident ?type] [?e :artist/gender ?geid] [?geid :db/ident ?gender]] db "PI:NAME:<NAME>END_PI") (d/q '{:find [[(pull ?e [*]) ...]] :in [$ ?gid] :where [[?e :artist/gid ?gid]]} db #uuid"76c9a186-75bd-436a-85c0-823e3efddb7f") (d/q '[:find (pull ?e [* :foo/bar]) . :in $ ?e] db 637716744120508))
[ { "context": " asn1Enc\n (KerberosPrincipal. \"client/localhost@local.com\")\n (KerberosPrincipal. \"server/", "end": 4360, "score": 0.9628952145576477, "start": 4334, "tag": "EMAIL", "value": "client/localhost@local.com" }, { "context": "cal.com\")\n (KerberosPrincipal. \"server/localhost@local.com\")\n sessionKey\n ", "end": 4429, "score": 0.9694272875785828, "start": 4403, "tag": "EMAIL", "value": "server/localhost@local.com" } ]
storm-core/test/clj/org/apache/storm/security/auth/auto_login_module_test.clj
iskoda/incubator-storm
8
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns org.apache.storm.security.auth.auto-login-module-test (:use [clojure test]) (:use [org.apache.storm util]) (:import [org.apache.storm.security.auth.kerberos AutoTGT AutoTGTKrb5LoginModule AutoTGTKrb5LoginModuleTest]) (:import [javax.security.auth Subject Subject]) (:import [javax.security.auth.kerberos KerberosTicket KerberosPrincipal]) (:import [org.mockito Mockito]) (:import [java.text SimpleDateFormat]) (:import [java.util Date]) (:import [java.util Arrays]) (:import [java.net InetAddress]) ) (deftest login-module-no-subj-no-tgt-test (testing "Behavior is correct when there is no Subject or TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-readonly-subj-no-tgt-test (testing "Behavior is correct when there is a read-only Subject and no TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module readonly-subj nil nil nil) (is (not (.commit login-module))) (is (.logout login-module))))) (deftest login-module-with-subj-no-tgt-test (testing "Behavior is correct when there is a Subject and no TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module (Subject.) nil nil nil) (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-no-subj-with-tgt-test (testing "Behavior is correct when there is no Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.)] (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-readonly-subj-with-tgt-test (testing "Behavior is correct when there is a read-only Subject and a TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModuleTest.)] (.initialize login-module readonly-subj nil nil nil) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-with-subj-and-tgt (testing "Behavior is correct when there is a Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.) _ (set! (. login-module client) (Mockito/mock java.security.Principal)) endTime (.parse (java.text.SimpleDateFormat. "ddMMyyyy") "31122030") asn1Enc (byte-array 10) _ (Arrays/fill asn1Enc (byte 122)) sessionKey (byte-array 10) _ (Arrays/fill sessionKey (byte 123)) ticket (KerberosTicket. asn1Enc (KerberosPrincipal. "client/localhost@local.com") (KerberosPrincipal. "server/localhost@local.com") sessionKey 234 (boolean-array (map even? (range 3 10))) (Date.) (Date.) endTime, endTime, (into-array InetAddress [(InetAddress/getByName "localhost")]))] (.initialize login-module (Subject.) nil nil nil) (.setKerbTicket login-module ticket) (is (.login login-module)) (is (.commit login-module)) (is (.abort login-module)) (is (.logout login-module)))))
122480
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns org.apache.storm.security.auth.auto-login-module-test (:use [clojure test]) (:use [org.apache.storm util]) (:import [org.apache.storm.security.auth.kerberos AutoTGT AutoTGTKrb5LoginModule AutoTGTKrb5LoginModuleTest]) (:import [javax.security.auth Subject Subject]) (:import [javax.security.auth.kerberos KerberosTicket KerberosPrincipal]) (:import [org.mockito Mockito]) (:import [java.text SimpleDateFormat]) (:import [java.util Date]) (:import [java.util Arrays]) (:import [java.net InetAddress]) ) (deftest login-module-no-subj-no-tgt-test (testing "Behavior is correct when there is no Subject or TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-readonly-subj-no-tgt-test (testing "Behavior is correct when there is a read-only Subject and no TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module readonly-subj nil nil nil) (is (not (.commit login-module))) (is (.logout login-module))))) (deftest login-module-with-subj-no-tgt-test (testing "Behavior is correct when there is a Subject and no TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module (Subject.) nil nil nil) (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-no-subj-with-tgt-test (testing "Behavior is correct when there is no Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.)] (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-readonly-subj-with-tgt-test (testing "Behavior is correct when there is a read-only Subject and a TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModuleTest.)] (.initialize login-module readonly-subj nil nil nil) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-with-subj-and-tgt (testing "Behavior is correct when there is a Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.) _ (set! (. login-module client) (Mockito/mock java.security.Principal)) endTime (.parse (java.text.SimpleDateFormat. "ddMMyyyy") "31122030") asn1Enc (byte-array 10) _ (Arrays/fill asn1Enc (byte 122)) sessionKey (byte-array 10) _ (Arrays/fill sessionKey (byte 123)) ticket (KerberosTicket. asn1Enc (KerberosPrincipal. "<EMAIL>") (KerberosPrincipal. "<EMAIL>") sessionKey 234 (boolean-array (map even? (range 3 10))) (Date.) (Date.) endTime, endTime, (into-array InetAddress [(InetAddress/getByName "localhost")]))] (.initialize login-module (Subject.) nil nil nil) (.setKerbTicket login-module ticket) (is (.login login-module)) (is (.commit login-module)) (is (.abort login-module)) (is (.logout login-module)))))
true
;; Licensed to the Apache Software Foundation (ASF) under one ;; or more contributor license agreements. See the NOTICE file ;; distributed with this work for additional information ;; regarding copyright ownership. The ASF licenses this file ;; to you under the Apache License, Version 2.0 (the ;; "License"); you may not use this file except in compliance ;; with the License. You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns org.apache.storm.security.auth.auto-login-module-test (:use [clojure test]) (:use [org.apache.storm util]) (:import [org.apache.storm.security.auth.kerberos AutoTGT AutoTGTKrb5LoginModule AutoTGTKrb5LoginModuleTest]) (:import [javax.security.auth Subject Subject]) (:import [javax.security.auth.kerberos KerberosTicket KerberosPrincipal]) (:import [org.mockito Mockito]) (:import [java.text SimpleDateFormat]) (:import [java.util Date]) (:import [java.util Arrays]) (:import [java.net InetAddress]) ) (deftest login-module-no-subj-no-tgt-test (testing "Behavior is correct when there is no Subject or TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-readonly-subj-no-tgt-test (testing "Behavior is correct when there is a read-only Subject and no TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module readonly-subj nil nil nil) (is (not (.commit login-module))) (is (.logout login-module))))) (deftest login-module-with-subj-no-tgt-test (testing "Behavior is correct when there is a Subject and no TGT" (let [login-module (AutoTGTKrb5LoginModule.)] (.initialize login-module (Subject.) nil nil nil) (is (thrown-cause? javax.security.auth.login.LoginException (.login login-module))) (is (not (.commit login-module))) (is (not (.abort login-module))) (is (.logout login-module))))) (deftest login-module-no-subj-with-tgt-test (testing "Behavior is correct when there is no Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.)] (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-readonly-subj-with-tgt-test (testing "Behavior is correct when there is a read-only Subject and a TGT" (let [readonly-subj (Subject. true #{} #{} #{}) login-module (AutoTGTKrb5LoginModuleTest.)] (.initialize login-module readonly-subj nil nil nil) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.login login-module)) (is (thrown-cause? javax.security.auth.login.LoginException (.commit login-module))) (.setKerbTicket login-module (Mockito/mock KerberosTicket)) (is (.abort login-module)) (is (.logout login-module))))) (deftest login-module-with-subj-and-tgt (testing "Behavior is correct when there is a Subject and a TGT" (let [login-module (AutoTGTKrb5LoginModuleTest.) _ (set! (. login-module client) (Mockito/mock java.security.Principal)) endTime (.parse (java.text.SimpleDateFormat. "ddMMyyyy") "31122030") asn1Enc (byte-array 10) _ (Arrays/fill asn1Enc (byte 122)) sessionKey (byte-array 10) _ (Arrays/fill sessionKey (byte 123)) ticket (KerberosTicket. asn1Enc (KerberosPrincipal. "PI:EMAIL:<EMAIL>END_PI") (KerberosPrincipal. "PI:EMAIL:<EMAIL>END_PI") sessionKey 234 (boolean-array (map even? (range 3 10))) (Date.) (Date.) endTime, endTime, (into-array InetAddress [(InetAddress/getByName "localhost")]))] (.initialize login-module (Subject.) nil nil nil) (.setKerbTicket login-module ticket) (is (.login login-module)) (is (.commit login-module)) (is (.abort login-module)) (is (.logout login-module)))))
[ { "context": " :yaas/authentication-db {{:sec/username \"MichaelStephan1982\"\n :sec/purpose ", "end": 2128, "score": 0.9996775388717651, "start": 2110, "tag": "USERNAME", "value": "MichaelStephan1982" }, { "context": "mmerce backoffice\"} {:sec/id \"6ba7b810-9dad-11d1-80b4-00c04fd430c8\"\n ", "end": 2250, "score": 0.9180726408958435, "start": 2234, "tag": "PASSWORD", "value": "0b4-00c04fd430c8" }, { "context": " :sec/password \"123\"\n ", "end": 2345, "score": 0.9994003772735596, "start": 2342, "tag": "PASSWORD", "value": "123" }, { "context": " :sec/full-username \"Michael Stephan\"\n ", "end": 2550, "score": 0.9995851516723633, "start": 2535, "tag": "USERNAME", "value": "Michael Stephan" }, { "context": " :sec/mail \"michael.stephan@sap.com\"}}\n :yaas/authorization-db {\"6ba7b810-9da", "end": 2661, "score": 0.9999232888221741, "start": 2638, "tag": "EMAIL", "value": "michael.stephan@sap.com" }, { "context": "yaas (yaas)\n credentials {:sec/username \"MichaelStephan1982\" :sec/password \"123\" :sec/purpose \"e-commmerce ba", "end": 3238, "score": 0.9997376799583435, "start": 3220, "tag": "USERNAME", "value": "MichaelStephan1982" }, { "context": ":sec/username \"MichaelStephan1982\" :sec/password \"123\" :sec/purpose \"e-commmerce backoffice\"}\n ", "end": 3258, "score": 0.9993812441825867, "start": 3255, "tag": "PASSWORD", "value": "123" } ]
data/train/clojure/d1dc735a4a447029aac89b75c8256d812e406e0ecore_test.clj
harshp8l/deep-learning-lang-detection
84
(ns concept20.core-test (:require [clojure.test :refer :all] [concept20.core :refer :all])) (defn yaas [] (atom {:yaas/services {:hybris/data-storage-service-v1 {:sec/scopes #{:scope/data-storage-read :scope/data-storage-manage} :yaas/depends-on []} :hybris/product-service-v1 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read_}}]} :hybris/category-service-v2 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read}}]}} :yaas/service-bundles {::data-storage-v1 {:yaas/services [[:hybris/data-storage-service-v1 concept20.core/data-storage-service]]} ::product-content-management-v1 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service]]} ::product-content-management-v2 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service] [:hybris/category-service-v2 concept20.core/category-service]]}} :yaas/subscriptions {} :yaas/measurements [] :yaas/authentication-db {{:sec/username "MichaelStephan1982" :sec/purpose "e-commmerce backoffice"} {:sec/id "6ba7b810-9dad-11d1-80b4-00c04fd430c8" :sec/password "123" :sec/tenant ::sap :sec/full-username "Michael Stephan" :sec/mail "michael.stephan@sap.com"}} :yaas/authorization-db {"6ba7b810-9dad-11d1-80b4-00c04fd430c8" {:sec/roles #{:role/product-manager :role/administrator}}} :yaas/config-db {::sap {:config/authorization {:role/product-manager #{:scope/product-read} :role/administrator #{:scope/subscription-manage}} :config/discovery {}}}})) (deftest test-saas-ui-browser (testing "Calling service from saas ui from customer's browser" (let [yaas (yaas) credentials {:sec/username "MichaelStephan1982" :sec/password "123" :sec/purpose "e-commmerce backoffice"} subscriptions (subscription-ui-browser yaas credentials [::product-content-management-v1 ::product-content-management-v2])] (saas-product-content-management-ui-browser yaas (assoc credentials :yaas/subscription (second subscriptions))) (clojure.pprint/pprint @yaas))))
88229
(ns concept20.core-test (:require [clojure.test :refer :all] [concept20.core :refer :all])) (defn yaas [] (atom {:yaas/services {:hybris/data-storage-service-v1 {:sec/scopes #{:scope/data-storage-read :scope/data-storage-manage} :yaas/depends-on []} :hybris/product-service-v1 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read_}}]} :hybris/category-service-v2 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read}}]}} :yaas/service-bundles {::data-storage-v1 {:yaas/services [[:hybris/data-storage-service-v1 concept20.core/data-storage-service]]} ::product-content-management-v1 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service]]} ::product-content-management-v2 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service] [:hybris/category-service-v2 concept20.core/category-service]]}} :yaas/subscriptions {} :yaas/measurements [] :yaas/authentication-db {{:sec/username "MichaelStephan1982" :sec/purpose "e-commmerce backoffice"} {:sec/id "6ba7b810-9dad-11d1-8<PASSWORD>" :sec/password "<PASSWORD>" :sec/tenant ::sap :sec/full-username "Michael Stephan" :sec/mail "<EMAIL>"}} :yaas/authorization-db {"6ba7b810-9dad-11d1-80b4-00c04fd430c8" {:sec/roles #{:role/product-manager :role/administrator}}} :yaas/config-db {::sap {:config/authorization {:role/product-manager #{:scope/product-read} :role/administrator #{:scope/subscription-manage}} :config/discovery {}}}})) (deftest test-saas-ui-browser (testing "Calling service from saas ui from customer's browser" (let [yaas (yaas) credentials {:sec/username "MichaelStephan1982" :sec/password "<PASSWORD>" :sec/purpose "e-commmerce backoffice"} subscriptions (subscription-ui-browser yaas credentials [::product-content-management-v1 ::product-content-management-v2])] (saas-product-content-management-ui-browser yaas (assoc credentials :yaas/subscription (second subscriptions))) (clojure.pprint/pprint @yaas))))
true
(ns concept20.core-test (:require [clojure.test :refer :all] [concept20.core :refer :all])) (defn yaas [] (atom {:yaas/services {:hybris/data-storage-service-v1 {:sec/scopes #{:scope/data-storage-read :scope/data-storage-manage} :yaas/depends-on []} :hybris/product-service-v1 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read_}}]} :hybris/category-service-v2 {:sec/scopes #{:scope/product-read :scope/product-manage} :yaas/depends-on [{:yaas/use-case ::todo :yaas/service-bundle ::data-storage-v1 :yaas/service :hybris/data-storage-service-v1 :sec/scopes #{:scope/data-storage-read}}]}} :yaas/service-bundles {::data-storage-v1 {:yaas/services [[:hybris/data-storage-service-v1 concept20.core/data-storage-service]]} ::product-content-management-v1 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service]]} ::product-content-management-v2 {:yaas/services [[:hybris/product-service-v1 concept20.core/product-service] [:hybris/category-service-v2 concept20.core/category-service]]}} :yaas/subscriptions {} :yaas/measurements [] :yaas/authentication-db {{:sec/username "MichaelStephan1982" :sec/purpose "e-commmerce backoffice"} {:sec/id "6ba7b810-9dad-11d1-8PI:PASSWORD:<PASSWORD>END_PI" :sec/password "PI:PASSWORD:<PASSWORD>END_PI" :sec/tenant ::sap :sec/full-username "Michael Stephan" :sec/mail "PI:EMAIL:<EMAIL>END_PI"}} :yaas/authorization-db {"6ba7b810-9dad-11d1-80b4-00c04fd430c8" {:sec/roles #{:role/product-manager :role/administrator}}} :yaas/config-db {::sap {:config/authorization {:role/product-manager #{:scope/product-read} :role/administrator #{:scope/subscription-manage}} :config/discovery {}}}})) (deftest test-saas-ui-browser (testing "Calling service from saas ui from customer's browser" (let [yaas (yaas) credentials {:sec/username "MichaelStephan1982" :sec/password "PI:PASSWORD:<PASSWORD>END_PI" :sec/purpose "e-commmerce backoffice"} subscriptions (subscription-ui-browser yaas credentials [::product-content-management-v1 ::product-content-management-v2])] (saas-product-content-management-ui-browser yaas (assoc credentials :yaas/subscription (second subscriptions))) (clojure.pprint/pprint @yaas))))
[ { "context": ";; Authors: Sung Pae <self@sungpae.com>\n\n(ns vim-clojure-static.test\n ", "end": 20, "score": 0.9998763799667358, "start": 12, "tag": "NAME", "value": "Sung Pae" }, { "context": ";; Authors: Sung Pae <self@sungpae.com>\n\n(ns vim-clojure-static.test\n (:require [clojur", "end": 38, "score": 0.9999284148216248, "start": 22, "tag": "EMAIL", "value": "self@sungpae.com" } ]
clj/src/vim_clojure_static/test.clj
amacdougall/vim-clojure-static
0
;; Authors: Sung Pae <self@sungpae.com> (ns vim-clojure-static.test (:require [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :as test])) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (io/make-parents file) (spit file (string/join \newline lines)) (shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/syn-id-names.vim" file) ;; The last line of the file will contain valid EDN (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (edn/read-string (peek (string/split-lines (slurp file))))))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (comment (macroexpand-1 '(defsyntaxtest number-literals-test ["%s" ["123" #(every? (partial = :clojureNumber) %) "456" #(every? (partial = :clojureNumber) %)]] ["#\"%s\"" ["^" #(= % [:clojureRegexpBoundary])]])) (test #'number-literals-test) )
94803
;; Authors: <NAME> <<EMAIL>> (ns vim-clojure-static.test (:require [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :as test])) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (io/make-parents file) (spit file (string/join \newline lines)) (shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/syn-id-names.vim" file) ;; The last line of the file will contain valid EDN (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (edn/read-string (peek (string/split-lines (slurp file))))))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (comment (macroexpand-1 '(defsyntaxtest number-literals-test ["%s" ["123" #(every? (partial = :clojureNumber) %) "456" #(every? (partial = :clojureNumber) %)]] ["#\"%s\"" ["^" #(= % [:clojureRegexpBoundary])]])) (test #'number-literals-test) )
true
;; Authors: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ns vim-clojure-static.test (:require [clojure.java.io :as io] [clojure.java.shell :as shell] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :as test])) (defn syn-id-names "Map lines of clojure text to vim synID names at each column as keywords: (syn-id-names \"foo\" …) -> {\"foo\" [:clojureString :clojureString :clojureString] …} First parameter is the file that is used to communicate with Vim. The file is not deleted to allow manual inspection." [file & lines] (io/make-parents file) (spit file (string/join \newline lines)) (shell/sh "vim" "-u" "NONE" "-N" "-S" "vim/syn-id-names.vim" file) ;; The last line of the file will contain valid EDN (into {} (map (fn [l ids] [l (mapv keyword ids)]) lines (edn/read-string (peek (string/split-lines (slurp file))))))) (defn subfmt "Extract a subsequence of seq s corresponding to the character positions of %s in format spec fmt" [fmt s] (let [f (seq (format fmt \o001)) i (.indexOf f \o001)] (->> s (drop i) (drop-last (- (count f) i 1))))) (defmacro defsyntaxtest "Create a new testing var with tests in the format: (defsyntaxtest example [format [test-string test-predicate …]] [\"#\\\"%s\\\"\" [\"123\" #(every? (partial = :clojureRegexp) %) …]] […]) At runtime the syn-id-names of the strings (which are placed in the format spec) are passed to their associated predicates. The format spec should contain a single `%s`." [name & body] (assert (every? (fn [[fmt tests]] (and (string? fmt) (coll? tests) (even? (count tests)))) body)) (let [[strings contexts] (reduce (fn [[strings contexts] [fmt tests]] (let [[ss λs] (apply map list (partition 2 tests)) ss (map #(format fmt %) ss)] [(concat strings ss) (conj contexts {:fmt fmt :ss ss :λs λs})])) [[] []] body) syntable (gensym "syntable")] `(test/deftest ~name ;; Shellout to vim should happen at runtime (let [~syntable (syn-id-names (str "tmp/" ~(str name) ".clj") ~@strings)] ~@(map (fn [{:keys [fmt ss λs]}] `(test/testing ~fmt ~@(map (fn [s λ] `(test/is (~λ (subfmt ~fmt (get ~syntable ~s))))) ss λs))) contexts))))) (comment (macroexpand-1 '(defsyntaxtest number-literals-test ["%s" ["123" #(every? (partial = :clojureNumber) %) "456" #(every? (partial = :clojureNumber) %)]] ["#\"%s\"" ["^" #(= % [:clojureRegexpBoundary])]])) (test #'number-literals-test) )
[ { "context": "; Maze generator in Clojure\n; Joe Wingbermuehle\n; 2013-10-08\n\n; Initialize an empty maze matrix.\n", "end": 47, "score": 0.9998867511749268, "start": 30, "tag": "NAME", "value": "Joe Wingbermuehle" } ]
maze.clj
tlpierce/maze
63
; Maze generator in Clojure ; Joe Wingbermuehle ; 2013-10-08 ; Initialize an empty maze matrix. (defn init-maze [width height] (let [top_bottom (vec (repeat width 1)) middle (vec (concat [1] (repeat (- width 2) 0) [1]))] (vec (concat [top_bottom] (repeat (- height 2) middle) [top_bottom])))) ; Display a maze. (defn show-maze [maze] (dotimes [y (count maze)] (dotimes [x (count (get maze y))] (if (== (get (get maze y) x) 1) (print "[]") (print " "))) (println))) ; Get/set maze elements. (defn set-maze [maze x y v] (assoc maze y (assoc (get maze y) x v))) (defn get-maze [maze x y] (get (get maze y) x)) ; Carve a maze starting at x, y. (defn carve-maze [maze x y i c] (let [dirs [[1 0] [-1 0] [0 1] [0 -1]] up1 (set-maze maze x y 1) d (get dirs (mod (+ i c) 4)) dx (first d) dy (second d) nx (+ x dx) ny (+ y dy) nx2 (+ nx dx) ny2 (+ ny dy)] (if (and (= (get-maze up1 nx ny) 0) (= (get-maze up1 nx2 ny2) 0)) (let [up2 (set-maze up1 nx ny 1) up3 (carve-maze up2 nx2 ny2 (rand-nth (range 0 4)) 0)] (if (< c 4) (carve-maze up3 nx2 ny2 i (+ c 1)) up3)) (if (< c 4) (carve-maze up1 x y i (+ c 1)) up1)))) ; Generate a random maze. ; width and height must be odd. (defn generate-maze [width height] (let [init (init-maze width height) base (carve-maze init 2 2 (rand-nth (range 0 4)) 0) top (set-maze base 1 0 0) bottom (set-maze top (- width 2) (- height 1) 0)] bottom)) ; Generate and display a random maze. (show-maze (generate-maze 39 23))
21572
; Maze generator in Clojure ; <NAME> ; 2013-10-08 ; Initialize an empty maze matrix. (defn init-maze [width height] (let [top_bottom (vec (repeat width 1)) middle (vec (concat [1] (repeat (- width 2) 0) [1]))] (vec (concat [top_bottom] (repeat (- height 2) middle) [top_bottom])))) ; Display a maze. (defn show-maze [maze] (dotimes [y (count maze)] (dotimes [x (count (get maze y))] (if (== (get (get maze y) x) 1) (print "[]") (print " "))) (println))) ; Get/set maze elements. (defn set-maze [maze x y v] (assoc maze y (assoc (get maze y) x v))) (defn get-maze [maze x y] (get (get maze y) x)) ; Carve a maze starting at x, y. (defn carve-maze [maze x y i c] (let [dirs [[1 0] [-1 0] [0 1] [0 -1]] up1 (set-maze maze x y 1) d (get dirs (mod (+ i c) 4)) dx (first d) dy (second d) nx (+ x dx) ny (+ y dy) nx2 (+ nx dx) ny2 (+ ny dy)] (if (and (= (get-maze up1 nx ny) 0) (= (get-maze up1 nx2 ny2) 0)) (let [up2 (set-maze up1 nx ny 1) up3 (carve-maze up2 nx2 ny2 (rand-nth (range 0 4)) 0)] (if (< c 4) (carve-maze up3 nx2 ny2 i (+ c 1)) up3)) (if (< c 4) (carve-maze up1 x y i (+ c 1)) up1)))) ; Generate a random maze. ; width and height must be odd. (defn generate-maze [width height] (let [init (init-maze width height) base (carve-maze init 2 2 (rand-nth (range 0 4)) 0) top (set-maze base 1 0 0) bottom (set-maze top (- width 2) (- height 1) 0)] bottom)) ; Generate and display a random maze. (show-maze (generate-maze 39 23))
true
; Maze generator in Clojure ; PI:NAME:<NAME>END_PI ; 2013-10-08 ; Initialize an empty maze matrix. (defn init-maze [width height] (let [top_bottom (vec (repeat width 1)) middle (vec (concat [1] (repeat (- width 2) 0) [1]))] (vec (concat [top_bottom] (repeat (- height 2) middle) [top_bottom])))) ; Display a maze. (defn show-maze [maze] (dotimes [y (count maze)] (dotimes [x (count (get maze y))] (if (== (get (get maze y) x) 1) (print "[]") (print " "))) (println))) ; Get/set maze elements. (defn set-maze [maze x y v] (assoc maze y (assoc (get maze y) x v))) (defn get-maze [maze x y] (get (get maze y) x)) ; Carve a maze starting at x, y. (defn carve-maze [maze x y i c] (let [dirs [[1 0] [-1 0] [0 1] [0 -1]] up1 (set-maze maze x y 1) d (get dirs (mod (+ i c) 4)) dx (first d) dy (second d) nx (+ x dx) ny (+ y dy) nx2 (+ nx dx) ny2 (+ ny dy)] (if (and (= (get-maze up1 nx ny) 0) (= (get-maze up1 nx2 ny2) 0)) (let [up2 (set-maze up1 nx ny 1) up3 (carve-maze up2 nx2 ny2 (rand-nth (range 0 4)) 0)] (if (< c 4) (carve-maze up3 nx2 ny2 i (+ c 1)) up3)) (if (< c 4) (carve-maze up1 x y i (+ c 1)) up1)))) ; Generate a random maze. ; width and height must be odd. (defn generate-maze [width height] (let [init (init-maze width height) base (carve-maze init 2 2 (rand-nth (range 0 4)) 0) top (set-maze base 1 0 0) bottom (set-maze top (- width 2) (- height 1) 0)] bottom)) ; Generate and display a random maze. (show-maze (generate-maze 39 23))
[ { "context": "pects \"Hello\" from client, replies with \"World\"\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defn -main []\n (let [ct", "end": 306, "score": 0.9998722076416016, "start": 295, "tag": "NAME", "value": "Isaiah Peng" }, { "context": "from client, replies with \"World\"\n;; Isaiah Peng <issaria@gmail.com>\n;;\n\n(defn -main []\n (let [ctx (mq/context 1)\n ", "end": 325, "score": 0.9999263286590576, "start": 308, "tag": "EMAIL", "value": "issaria@gmail.com" } ]
docs/zeroMQ-guide2/examples/Clojure/rrworker.clj
krattai/noo-ebs
2
(ns rrserver (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Hello World server ;; Connects REP socket to tcp://*:5560 ;; Expects "Hello" from client, replies with "World" ;; Isaiah Peng <issaria@gmail.com> ;; (defn -main [] (let [ctx (mq/context 1) responder (mq/socket ctx mq/rep)] (mq/connect responder "tcp://localhost:5560") (while true (let [string (mq/recv-str responder)] (println (format "Received request: [%s]." string)) ;; Do some work (Thread/sleep 1000) (mq/send responder "World\u0000"))) ;; We never get here but clean anyhow (.close responder) (.term ctx)))
60419
(ns rrserver (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Hello World server ;; Connects REP socket to tcp://*:5560 ;; Expects "Hello" from client, replies with "World" ;; <NAME> <<EMAIL>> ;; (defn -main [] (let [ctx (mq/context 1) responder (mq/socket ctx mq/rep)] (mq/connect responder "tcp://localhost:5560") (while true (let [string (mq/recv-str responder)] (println (format "Received request: [%s]." string)) ;; Do some work (Thread/sleep 1000) (mq/send responder "World\u0000"))) ;; We never get here but clean anyhow (.close responder) (.term ctx)))
true
(ns rrserver (:refer-clojure :exclude [send]) (:require [zhelpers :as mq])) ;; ;; Hello World server ;; Connects REP socket to tcp://*:5560 ;; Expects "Hello" from client, replies with "World" ;; PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; (defn -main [] (let [ctx (mq/context 1) responder (mq/socket ctx mq/rep)] (mq/connect responder "tcp://localhost:5560") (while true (let [string (mq/recv-str responder)] (println (format "Received request: [%s]." string)) ;; Do some work (Thread/sleep 1000) (mq/send responder "World\u0000"))) ;; We never get here but clean anyhow (.close responder) (.term ctx)))
[ { "context": ";; Copyright © 2015-2021 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998852610588074, "start": 25, "tag": "NAME", "value": "Esko Luontola" }, { "context": "t-schema2 \"test_gis_schema2\")\n(def test-username \"test_gis_user\")\n(def test-username2 \"test_gis_user2\")\n\n(defn- w", "end": 922, "score": 0.9989822506904602, "start": 909, "tag": "USERNAME", "value": "test_gis_user" }, { "context": "st-username \"test_gis_user\")\n(def test-username2 \"test_gis_user2\")\n\n(defn- with-tenant-schema [schema-name f]\n (l", "end": 960, "score": 0.9991336464881897, "start": 946, "tag": "USERNAME", "value": "test_gis_user2" }, { "context": "ername and password\n :user username\n :password password})\n\n(defn- login-as [username password]\n (= [{:us", "end": 16309, "score": 0.9972537755966187, "start": 16301, "tag": "PASSWORD", "value": "password" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :passwor", "end": 16716, "score": 0.9791935086250305, "start": 16703, "tag": "USERNAME", "value": "test-username" }, { "context": " :password \"password1\"\n :schema", "end": 16778, "score": 0.9994010925292969, "start": 16769, "tag": "PASSWORD", "value": "password1" }, { "context": "est-username))))\n (is (login-as test-username \"password1\")))\n\n (testing \"update account / create is idemp", "end": 16946, "score": 0.9791967868804932, "start": 16937, "tag": "USERNAME", "value": "password1" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :passwor", "end": 17093, "score": 0.9765856266021729, "start": 17080, "tag": "USERNAME", "value": "test-username" }, { "context": " :password \"password2\"\n :schema", "end": 17155, "score": 0.9993534088134766, "start": 17146, "tag": "PASSWORD", "value": "password2" }, { "context": "a test-schema}))\n (is (login-as test-username \"password2\")))\n\n (testing \"delete account\"\n (db/with-db ", "end": 17263, "score": 0.9696880578994751, "start": 17254, "tag": "USERNAME", "value": "password2" }, { "context": "\n (gis-db/ensure-user-absent! conn {:username test-username\n :schema t", "end": 17386, "score": 0.9991677403450012, "start": 17373, "tag": "USERNAME", "value": "test-username" }, { "context": "s (thrown? PSQLException (login-as test-username \"password2\"))))\n\n (testing \"delete is idempotent\"\n (db/w", "end": 17515, "score": 0.9976322650909424, "start": 17506, "tag": "USERNAME", "value": "password2" }, { "context": "\n (gis-db/ensure-user-absent! conn {:username test-username\n :schema t", "end": 17645, "score": 0.9991971850395203, "start": 17632, "tag": "USERNAME", "value": "test-username" }, { "context": "s (thrown? PSQLException (login-as test-username \"password2\")))))\n\n(deftest gis-user-database-access-test\n (", "end": 17774, "score": 0.9972695112228394, "start": 17765, "tag": "USERNAME", "value": "password2" }, { "context": "t gis-user-database-access-test\n (let [password \"password123\"\n db-spec (gis-db-spec test-username passw", "end": 17850, "score": 0.9994559288024902, "start": 17839, "tag": "PASSWORD", "value": "password123" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :passwor", "end": 17996, "score": 0.9990980625152588, "start": 17983, "tag": "USERNAME", "value": "test-username" }, { "context": " :password password\n :schema ", "end": 18056, "score": 0.9943730235099792, "start": 18048, "tag": "PASSWORD", "value": "password" }, { "context": "/table \"territory\"\n :gis-change/user test-username}\n {:gis-change/op :INSERT\n ", "end": 19367, "score": 0.6849192380905151, "start": 19363, "tag": "USERNAME", "value": "test" }, { "context": "regation_boundary\"\n :gis-change/user test-username}\n {:gis-change/op :INSERT\n ", "end": 19555, "score": 0.5766279697418213, "start": 19551, "tag": "USERNAME", "value": "test" }, { "context": "/table \"subregion\"\n :gis-change/user test-username}\n {:gis-change/op :INSERT\n ", "end": 19731, "score": 0.5918353199958801, "start": 19727, "tag": "USERNAME", "value": "test" }, { "context": "_minimap_viewport\"\n :gis-change/user test-username}]\n (->> (db/with-db [conn {}", "end": 19919, "score": 0.7048169374465942, "start": 19915, "tag": "USERNAME", "value": "test" }, { "context": "ap_viewport\"\n :gis-change/user test-username}]\n (->> (db/with-db [conn {}]\n ", "end": 19928, "score": 0.613377034664154, "start": 19920, "tag": "USERNAME", "value": "username" }, { "context": " (gis-db/ensure-user-absent! conn {:username test-username\n :schema", "end": 20794, "score": 0.9913928508758545, "start": 20781, "tag": "USERNAME", "value": "test-username" }, { "context": "privilege_type \"DELETE\"}]]\n (is (= {:username \"test_gis_user\"\n :schema \"test_gis_schema\"}\n ", "end": 23224, "score": 0.9992381930351257, "start": 23211, "tag": "USERNAME", "value": "test_gis_user" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :pas", "end": 23986, "score": 0.9981642365455627, "start": 23973, "tag": "USERNAME", "value": "test-username" }, { "context": " :password \"password\"\n :sc", "end": 24051, "score": 0.9995486736297607, "start": 24043, "tag": "PASSWORD", "value": "password" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username2\n :pas", "end": 24189, "score": 0.9986581802368164, "start": 24175, "tag": "USERNAME", "value": "test-username2" }, { "context": " :password \"password\"\n :sc", "end": 24254, "score": 0.9994831085205078, "start": 24246, "tag": "PASSWORD", "value": "password" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :pas", "end": 24391, "score": 0.9982013702392578, "start": 24378, "tag": "USERNAME", "value": "test-username" }, { "context": " :password \"password\"\n :sc", "end": 24456, "score": 0.9995636343955994, "start": 24448, "tag": "PASSWORD", "value": "password" }, { "context": "chema test-schema2})\n (is (= #{{:username test-username :schema test-schema}\n {:usernam", "end": 24569, "score": 0.9963197708129883, "start": 24556, "tag": "USERNAME", "value": "test-username" }, { "context": ":schema test-schema}\n {:username test-username2 :schema test-schema}\n {:usernam", "end": 24635, "score": 0.997478723526001, "start": 24621, "tag": "USERNAME", "value": "test-username2" }, { "context": ":schema test-schema}\n {:username test-username :schema test-schema2}}\n (set (gis", "end": 24700, "score": 0.9945229887962341, "start": 24687, "tag": "USERNAME", "value": "test-username" }, { "context": "t (gis-db/get-present-users conn {:username-prefix test-username\n ", "end": 24808, "score": 0.8915316462516785, "start": 24795, "tag": "USERNAME", "value": "test-username" }, { "context": " (gis-db/ensure-user-present! conn {:username test-username\n :pas", "end": 25100, "score": 0.994781494140625, "start": 25087, "tag": "USERNAME", "value": "test-username" }, { "context": " :password \"password\"\n :sc", "end": 25165, "score": 0.999538779258728, "start": 25157, "tag": "PASSWORD", "value": "password" }, { "context": " (gis-db/get-present-users conn {:username-prefix test-username\n ", "end": 25443, "score": 0.8659355044364929, "start": 25430, "tag": "USERNAME", "value": "test-username" } ]
test/territory_bro/gis/gis_db_test.clj
orfjackal/territory-bro
2
;; Copyright © 2015-2021 Esko Luontola ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.gis.gis-db-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.domain.testdata :as testdata] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.config :as config] [territory-bro.infra.db :as db] [territory-bro.infra.event-store :as event-store] [territory-bro.test.fixtures :refer [db-fixture]]) (:import (java.sql Connection SQLException) (java.util UUID) (java.util.regex Pattern) (org.postgresql.util PSQLException))) (def test-schema "test_gis_schema") (def test-schema2 "test_gis_schema2") (def test-username "test_gis_user") (def test-username2 "test_gis_user2") (defn- with-tenant-schema [schema-name f] (let [schema (db/tenant-schema schema-name (:database-schema config/env))] (try (.migrate schema) (f) (finally (db/with-db [conn {}] (jdbc/execute! conn ["DELETE FROM gis_change_log"])) (.clean schema))))) (defn test-schema-fixture [f] (with-tenant-schema test-schema f)) (use-fixtures :each (join-fixtures [db-fixture test-schema-fixture])) (def example-territory {:territory/number "123" :territory/addresses "Street 1 A" :territory/region "Somewhere" :territory/meta {:foo "bar", :gazonk 42} :territory/location testdata/wkt-multi-polygon}) (deftest regions-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "create & list congregation boundaries" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-congregation-boundaries conn))))) (testing "create & list regions" (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/name "the name" :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-regions conn))))) (testing "create & list card minimap viewports" (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-polygon}] (gis-db/get-card-minimap-viewports conn))))))) (deftest territories-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "create new territory" (is territory-id)) (testing "get territory by ID" (is (= {:gis-feature/id territory-id :gis-feature/number "123" :gis-feature/addresses "Street 1 A" :gis-feature/subregion "Somewhere" :gis-feature/meta {:foo "bar", :gazonk 42} :gis-feature/location testdata/wkt-multi-polygon} (gis-db/get-territory-by-id conn territory-id)))) (testing "get territories by IDs" (is (= [territory-id] (->> (gis-db/get-territories conn {:ids [territory-id]}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids []}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids nil}) (map :gis-feature/id))))) (testing "list territories" (is (= ["123"] (->> (gis-db/get-territories conn) (map :gis-feature/number) (sort)))))))) (defn- init-stream! [conn id gis-schema, gis-table] (jdbc/execute! conn ["INSERT INTO stream (stream_id, gis_schema, gis_table) VALUES (?, ?, ?)" id gis-schema gis-table]) id) (deftest validate-gis-change-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "populates the stream table on insert" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "congregation_boundary"} (event-store/stream-info conn id)) "congregation boundary")) (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn id)) "region")) (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "card_minimap_viewport"} (event-store/stream-info conn id)) "card minimap viewport")) (let [id (gis-db/create-territory! conn example-territory)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "territory"} (event-store/stream-info conn id)) "territory"))) (testing "populates the stream table on ID change" (let [old-id (gis-db/create-region! conn "test" testdata/wkt-multi-polygon) new-id (UUID/randomUUID)] (jdbc/execute! conn ["UPDATE subregion SET id = ? WHERE id = ?" new-id old-id]) (is (= {:stream_id old-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn old-id)) "old stream") (is (= {:stream_id new-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn new-id)) "new stream"))) (testing "stream ID conflict detection:" (testing "stream ID is used by current schema and table -> keeps ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another schema -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) "another_schema" "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another table -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "territory") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by non-GIS entity -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) nil nil) new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id])))))))) (deftest gis-change-log-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "before making changes" (is (= [] (gis-db/get-changes conn))) (is (nil? (gis-db/next-unprocessed-change conn)))) (testing "territory table change log," (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "insert" (let [changes (gis-db/get-changes conn)] (is (= 1 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "update" (jdbc/execute! conn ["UPDATE territory SET addresses = 'Another Street 2' WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 2 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :UPDATE :gis-change/old {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "delete" (jdbc/execute! conn ["DELETE FROM territory WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 3 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :DELETE :gis-change/old {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new nil :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))))) (testing "congregation_boundary table change log" (let [region-id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 4 (count changes))) (is (= {:gis-change/table "congregation_boundary" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "region table change log" (let [region-id (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 5 (count changes))) (is (= {:gis-change/table "subregion" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :name "Somewhere" :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "card_minimap_viewport table change log" (let [region-id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon) changes (gis-db/get-changes conn)] (is (= 6 (count changes))) (is (= {:gis-change/table "card_minimap_viewport" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "get changes since X" (let [all-changes (gis-db/get-changes conn)] (is (= all-changes (gis-db/get-changes conn {:since 0})) "since beginning") (is (= (drop 1 all-changes) (gis-db/get-changes conn {:since 1})) "since first change") (is (= (take-last 1 all-changes) (gis-db/get-changes conn {:since (:gis-change/id (first (take-last 2 all-changes)))})) "since second last change") (is (= [] (gis-db/get-changes conn {:since (:gis-change/id (last all-changes))})) "since last change") ;; should probably be an error, but an empty result is safer than returning all events (is (= [] (gis-db/get-changes conn {:since nil})) "since nil"))) (testing "get changes, limit" (let [all-changes (gis-db/get-changes conn)] (is (= [] (gis-db/get-changes conn {:limit 0})) "limit 0") (is (= (take 1 all-changes) (gis-db/get-changes conn {:limit 1})) "limit 1") (is (= (take 2 all-changes) (gis-db/get-changes conn {:limit 2})) "limit 2") ;; in PostgreSQL, LIMIT NULL (or LIMIT ALL) is the same as omitting the LIMIT (is (= all-changes (gis-db/get-changes conn {:limit nil})) "limit nil"))) (testing "marking changes processed" (is (= [] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, before") (is (= [1 2 3 4 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, before") (is (= 1 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, before") (gis-db/mark-changes-processed! conn [1 2 4]) (is (= [1 2 4] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, after") (is (= [3 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, after") (is (= 3 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, after")))) (defn- gis-db-spec [username password] {:connection-uri (-> (:database-url config/env) (str/replace #"\?.*" "")) ; strip username and password :user username :password password}) (defn- login-as [username password] (= [{:user username}] (jdbc/query (gis-db-spec username password) ["select session_user as user"]))) (deftest ensure-gis-user-present-or-absent-test (testing "create account" (db/with-db [conn {}] (is (false? (gis-db/user-exists? conn test-username))) (gis-db/ensure-user-present! conn {:username test-username :password "password1" :schema test-schema}) (is (true? (gis-db/user-exists? conn test-username)))) (is (login-as test-username "password1"))) (testing "update account / create is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password "password2" :schema test-schema})) (is (login-as test-username "password2"))) (testing "delete account" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2")))) (testing "delete is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2"))))) (deftest gis-user-database-access-test (let [password "password123" db-spec (gis-db-spec test-username password)] (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password password :schema test-schema})) (testing "can login to the database" (is (= [{:test 1}] (jdbc/query db-spec ["select 1 as test"])))) (testing "can view the tenant schema and the tables in it" (jdbc/with-db-transaction [conn db-spec] (is (jdbc/query conn [(str "select * from " test-schema ".territory")])) (is (jdbc/query conn [(str "select * from " test-schema ".congregation_boundary")])) (is (jdbc/query conn [(str "select * from " test-schema ".subregion")])) (is (jdbc/query conn [(str "select * from " test-schema ".card_minimap_viewport")])))) (testing "can modify data in the tenant schema" (jdbc/with-db-transaction [conn db-spec] (db/use-tenant-schema conn test-schema) (is (gis-db/create-territory! conn example-territory)) (is (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)) (is (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon)) (is (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)))) (testing "user ID is logged in GIS change log" (is (= [{:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "territory" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "congregation_boundary" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "subregion" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "card_minimap_viewport" :gis-change/user test-username}] (->> (db/with-db [conn {}] (gis-db/get-changes conn)) (map #(select-keys % [:gis-change/op :gis-change/schema :gis-change/table :gis-change/user])))))) (testing "cannot view the master schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema" (jdbc/query db-spec [(str "select * from " (:database-schema config/env) ".congregation")])))) (testing "cannot create objects in the public schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema public" (jdbc/execute! db-spec ["create table public.foo (id serial primary key)"])))) (testing "cannot login to database after user is deleted" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown-with-msg? PSQLException #"FATAL: password authentication failed for user" (jdbc/query db-spec ["select 1 as test"])))))) (deftest validate-grants-test (let [grants [{:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "DELETE"}]] (is (= {:username "test_gis_user" :schema "test_gis_schema"} (#'gis-db/validate-grants grants))) (is (nil? (#'gis-db/validate-grants (drop 1 grants)))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :grantee] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :privilege_type] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_name] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_schema] "foo")))))) (deftest get-present-users-test (with-tenant-schema test-schema2 (fn [] (testing "lists GIS users present in the database" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "password" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username2 :password "password" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username :password "password" :schema test-schema2}) (is (= #{{:username test-username :schema test-schema} {:username test-username2 :schema test-schema} {:username test-username :schema test-schema2}} (set (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))) (testing "doesn't list GIS users with missing grants" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "password" :schema test-schema}) (jdbc/execute! conn [(str "REVOKE DELETE ON TABLE " test-schema ".territory FROM " test-username)]) (is (= [] (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))))) (deftest get-present-schemas-test (with-tenant-schema test-schema2 (fn [] (testing "lists tenant schemas present in the database" (db/with-db [conn {}] (is (= [test-schema test-schema2] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))) (testing "doesn't list tenant schemas whose migrations are not up to date" (db/with-db [conn {}] (jdbc/execute! conn [(format "UPDATE %s.flyway_schema_history SET checksum = 42 WHERE version = '1'" test-schema2)]) (.commit ^Connection (:connection conn)) ; commit so that Flyway will see the changes, since it uses a new DB connection (is (= [test-schema] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))))))
28440
;; Copyright © 2015-2021 <NAME> ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.gis.gis-db-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.domain.testdata :as testdata] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.config :as config] [territory-bro.infra.db :as db] [territory-bro.infra.event-store :as event-store] [territory-bro.test.fixtures :refer [db-fixture]]) (:import (java.sql Connection SQLException) (java.util UUID) (java.util.regex Pattern) (org.postgresql.util PSQLException))) (def test-schema "test_gis_schema") (def test-schema2 "test_gis_schema2") (def test-username "test_gis_user") (def test-username2 "test_gis_user2") (defn- with-tenant-schema [schema-name f] (let [schema (db/tenant-schema schema-name (:database-schema config/env))] (try (.migrate schema) (f) (finally (db/with-db [conn {}] (jdbc/execute! conn ["DELETE FROM gis_change_log"])) (.clean schema))))) (defn test-schema-fixture [f] (with-tenant-schema test-schema f)) (use-fixtures :each (join-fixtures [db-fixture test-schema-fixture])) (def example-territory {:territory/number "123" :territory/addresses "Street 1 A" :territory/region "Somewhere" :territory/meta {:foo "bar", :gazonk 42} :territory/location testdata/wkt-multi-polygon}) (deftest regions-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "create & list congregation boundaries" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-congregation-boundaries conn))))) (testing "create & list regions" (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/name "the name" :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-regions conn))))) (testing "create & list card minimap viewports" (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-polygon}] (gis-db/get-card-minimap-viewports conn))))))) (deftest territories-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "create new territory" (is territory-id)) (testing "get territory by ID" (is (= {:gis-feature/id territory-id :gis-feature/number "123" :gis-feature/addresses "Street 1 A" :gis-feature/subregion "Somewhere" :gis-feature/meta {:foo "bar", :gazonk 42} :gis-feature/location testdata/wkt-multi-polygon} (gis-db/get-territory-by-id conn territory-id)))) (testing "get territories by IDs" (is (= [territory-id] (->> (gis-db/get-territories conn {:ids [territory-id]}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids []}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids nil}) (map :gis-feature/id))))) (testing "list territories" (is (= ["123"] (->> (gis-db/get-territories conn) (map :gis-feature/number) (sort)))))))) (defn- init-stream! [conn id gis-schema, gis-table] (jdbc/execute! conn ["INSERT INTO stream (stream_id, gis_schema, gis_table) VALUES (?, ?, ?)" id gis-schema gis-table]) id) (deftest validate-gis-change-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "populates the stream table on insert" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "congregation_boundary"} (event-store/stream-info conn id)) "congregation boundary")) (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn id)) "region")) (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "card_minimap_viewport"} (event-store/stream-info conn id)) "card minimap viewport")) (let [id (gis-db/create-territory! conn example-territory)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "territory"} (event-store/stream-info conn id)) "territory"))) (testing "populates the stream table on ID change" (let [old-id (gis-db/create-region! conn "test" testdata/wkt-multi-polygon) new-id (UUID/randomUUID)] (jdbc/execute! conn ["UPDATE subregion SET id = ? WHERE id = ?" new-id old-id]) (is (= {:stream_id old-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn old-id)) "old stream") (is (= {:stream_id new-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn new-id)) "new stream"))) (testing "stream ID conflict detection:" (testing "stream ID is used by current schema and table -> keeps ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another schema -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) "another_schema" "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another table -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "territory") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by non-GIS entity -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) nil nil) new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id])))))))) (deftest gis-change-log-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "before making changes" (is (= [] (gis-db/get-changes conn))) (is (nil? (gis-db/next-unprocessed-change conn)))) (testing "territory table change log," (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "insert" (let [changes (gis-db/get-changes conn)] (is (= 1 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "update" (jdbc/execute! conn ["UPDATE territory SET addresses = 'Another Street 2' WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 2 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :UPDATE :gis-change/old {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "delete" (jdbc/execute! conn ["DELETE FROM territory WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 3 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :DELETE :gis-change/old {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new nil :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))))) (testing "congregation_boundary table change log" (let [region-id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 4 (count changes))) (is (= {:gis-change/table "congregation_boundary" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "region table change log" (let [region-id (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 5 (count changes))) (is (= {:gis-change/table "subregion" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :name "Somewhere" :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "card_minimap_viewport table change log" (let [region-id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon) changes (gis-db/get-changes conn)] (is (= 6 (count changes))) (is (= {:gis-change/table "card_minimap_viewport" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "get changes since X" (let [all-changes (gis-db/get-changes conn)] (is (= all-changes (gis-db/get-changes conn {:since 0})) "since beginning") (is (= (drop 1 all-changes) (gis-db/get-changes conn {:since 1})) "since first change") (is (= (take-last 1 all-changes) (gis-db/get-changes conn {:since (:gis-change/id (first (take-last 2 all-changes)))})) "since second last change") (is (= [] (gis-db/get-changes conn {:since (:gis-change/id (last all-changes))})) "since last change") ;; should probably be an error, but an empty result is safer than returning all events (is (= [] (gis-db/get-changes conn {:since nil})) "since nil"))) (testing "get changes, limit" (let [all-changes (gis-db/get-changes conn)] (is (= [] (gis-db/get-changes conn {:limit 0})) "limit 0") (is (= (take 1 all-changes) (gis-db/get-changes conn {:limit 1})) "limit 1") (is (= (take 2 all-changes) (gis-db/get-changes conn {:limit 2})) "limit 2") ;; in PostgreSQL, LIMIT NULL (or LIMIT ALL) is the same as omitting the LIMIT (is (= all-changes (gis-db/get-changes conn {:limit nil})) "limit nil"))) (testing "marking changes processed" (is (= [] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, before") (is (= [1 2 3 4 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, before") (is (= 1 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, before") (gis-db/mark-changes-processed! conn [1 2 4]) (is (= [1 2 4] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, after") (is (= [3 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, after") (is (= 3 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, after")))) (defn- gis-db-spec [username password] {:connection-uri (-> (:database-url config/env) (str/replace #"\?.*" "")) ; strip username and password :user username :password <PASSWORD>}) (defn- login-as [username password] (= [{:user username}] (jdbc/query (gis-db-spec username password) ["select session_user as user"]))) (deftest ensure-gis-user-present-or-absent-test (testing "create account" (db/with-db [conn {}] (is (false? (gis-db/user-exists? conn test-username))) (gis-db/ensure-user-present! conn {:username test-username :password "<PASSWORD>" :schema test-schema}) (is (true? (gis-db/user-exists? conn test-username)))) (is (login-as test-username "password1"))) (testing "update account / create is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password "<PASSWORD>" :schema test-schema})) (is (login-as test-username "password2"))) (testing "delete account" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2")))) (testing "delete is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2"))))) (deftest gis-user-database-access-test (let [password "<PASSWORD>" db-spec (gis-db-spec test-username password)] (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password <PASSWORD> :schema test-schema})) (testing "can login to the database" (is (= [{:test 1}] (jdbc/query db-spec ["select 1 as test"])))) (testing "can view the tenant schema and the tables in it" (jdbc/with-db-transaction [conn db-spec] (is (jdbc/query conn [(str "select * from " test-schema ".territory")])) (is (jdbc/query conn [(str "select * from " test-schema ".congregation_boundary")])) (is (jdbc/query conn [(str "select * from " test-schema ".subregion")])) (is (jdbc/query conn [(str "select * from " test-schema ".card_minimap_viewport")])))) (testing "can modify data in the tenant schema" (jdbc/with-db-transaction [conn db-spec] (db/use-tenant-schema conn test-schema) (is (gis-db/create-territory! conn example-territory)) (is (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)) (is (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon)) (is (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)))) (testing "user ID is logged in GIS change log" (is (= [{:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "territory" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "congregation_boundary" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "subregion" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "card_minimap_viewport" :gis-change/user test-username}] (->> (db/with-db [conn {}] (gis-db/get-changes conn)) (map #(select-keys % [:gis-change/op :gis-change/schema :gis-change/table :gis-change/user])))))) (testing "cannot view the master schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema" (jdbc/query db-spec [(str "select * from " (:database-schema config/env) ".congregation")])))) (testing "cannot create objects in the public schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema public" (jdbc/execute! db-spec ["create table public.foo (id serial primary key)"])))) (testing "cannot login to database after user is deleted" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown-with-msg? PSQLException #"FATAL: password authentication failed for user" (jdbc/query db-spec ["select 1 as test"])))))) (deftest validate-grants-test (let [grants [{:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "DELETE"}]] (is (= {:username "test_gis_user" :schema "test_gis_schema"} (#'gis-db/validate-grants grants))) (is (nil? (#'gis-db/validate-grants (drop 1 grants)))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :grantee] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :privilege_type] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_name] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_schema] "foo")))))) (deftest get-present-users-test (with-tenant-schema test-schema2 (fn [] (testing "lists GIS users present in the database" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "<PASSWORD>" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username2 :password "<PASSWORD>" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username :password "<PASSWORD>" :schema test-schema2}) (is (= #{{:username test-username :schema test-schema} {:username test-username2 :schema test-schema} {:username test-username :schema test-schema2}} (set (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))) (testing "doesn't list GIS users with missing grants" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "<PASSWORD>" :schema test-schema}) (jdbc/execute! conn [(str "REVOKE DELETE ON TABLE " test-schema ".territory FROM " test-username)]) (is (= [] (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))))) (deftest get-present-schemas-test (with-tenant-schema test-schema2 (fn [] (testing "lists tenant schemas present in the database" (db/with-db [conn {}] (is (= [test-schema test-schema2] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))) (testing "doesn't list tenant schemas whose migrations are not up to date" (db/with-db [conn {}] (jdbc/execute! conn [(format "UPDATE %s.flyway_schema_history SET checksum = 42 WHERE version = '1'" test-schema2)]) (.commit ^Connection (:connection conn)) ; commit so that Flyway will see the changes, since it uses a new DB connection (is (= [test-schema] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))))))
true
;; Copyright © 2015-2021 PI:NAME:<NAME>END_PI ;; This software is released under the Apache License 2.0. ;; The license text is at http://www.apache.org/licenses/LICENSE-2.0 (ns ^:slow territory-bro.gis.gis-db-test (:require [clojure.java.jdbc :as jdbc] [clojure.string :as str] [clojure.test :refer :all] [territory-bro.domain.testdata :as testdata] [territory-bro.gis.gis-db :as gis-db] [territory-bro.infra.config :as config] [territory-bro.infra.db :as db] [territory-bro.infra.event-store :as event-store] [territory-bro.test.fixtures :refer [db-fixture]]) (:import (java.sql Connection SQLException) (java.util UUID) (java.util.regex Pattern) (org.postgresql.util PSQLException))) (def test-schema "test_gis_schema") (def test-schema2 "test_gis_schema2") (def test-username "test_gis_user") (def test-username2 "test_gis_user2") (defn- with-tenant-schema [schema-name f] (let [schema (db/tenant-schema schema-name (:database-schema config/env))] (try (.migrate schema) (f) (finally (db/with-db [conn {}] (jdbc/execute! conn ["DELETE FROM gis_change_log"])) (.clean schema))))) (defn test-schema-fixture [f] (with-tenant-schema test-schema f)) (use-fixtures :each (join-fixtures [db-fixture test-schema-fixture])) (def example-territory {:territory/number "123" :territory/addresses "Street 1 A" :territory/region "Somewhere" :territory/meta {:foo "bar", :gazonk 42} :territory/location testdata/wkt-multi-polygon}) (deftest regions-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "create & list congregation boundaries" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-congregation-boundaries conn))))) (testing "create & list regions" (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= [{:gis-feature/id id :gis-feature/name "the name" :gis-feature/location testdata/wkt-multi-polygon}] (gis-db/get-regions conn))))) (testing "create & list card minimap viewports" (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= [{:gis-feature/id id :gis-feature/location testdata/wkt-polygon}] (gis-db/get-card-minimap-viewports conn))))))) (deftest territories-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "create new territory" (is territory-id)) (testing "get territory by ID" (is (= {:gis-feature/id territory-id :gis-feature/number "123" :gis-feature/addresses "Street 1 A" :gis-feature/subregion "Somewhere" :gis-feature/meta {:foo "bar", :gazonk 42} :gis-feature/location testdata/wkt-multi-polygon} (gis-db/get-territory-by-id conn territory-id)))) (testing "get territories by IDs" (is (= [territory-id] (->> (gis-db/get-territories conn {:ids [territory-id]}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids []}) (map :gis-feature/id)))) (is (= [] (->> (gis-db/get-territories conn {:ids nil}) (map :gis-feature/id))))) (testing "list territories" (is (= ["123"] (->> (gis-db/get-territories conn) (map :gis-feature/number) (sort)))))))) (defn- init-stream! [conn id gis-schema, gis-table] (jdbc/execute! conn ["INSERT INTO stream (stream_id, gis_schema, gis_table) VALUES (?, ?, ?)" id gis-schema gis-table]) id) (deftest validate-gis-change-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "populates the stream table on insert" (let [id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "congregation_boundary"} (event-store/stream-info conn id)) "congregation boundary")) (let [id (gis-db/create-region! conn "the name" testdata/wkt-multi-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn id)) "region")) (let [id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "card_minimap_viewport"} (event-store/stream-info conn id)) "card minimap viewport")) (let [id (gis-db/create-territory! conn example-territory)] (is (= {:stream_id id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "territory"} (event-store/stream-info conn id)) "territory"))) (testing "populates the stream table on ID change" (let [old-id (gis-db/create-region! conn "test" testdata/wkt-multi-polygon) new-id (UUID/randomUUID)] (jdbc/execute! conn ["UPDATE subregion SET id = ? WHERE id = ?" new-id old-id]) (is (= {:stream_id old-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn old-id)) "old stream") (is (= {:stream_id new-id :entity_type nil :congregation nil :gis_schema test-schema :gis_table "subregion"} (event-store/stream-info conn new-id)) "new stream"))) (testing "stream ID conflict detection:" (testing "stream ID is used by current schema and table -> keeps ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another schema -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) "another_schema" "subregion") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by another table -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) test-schema "territory") new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id]))))) (testing "stream ID is used by non-GIS entity -> replaces ID" (let [old-id (init-stream! conn (UUID/randomUUID) nil nil) new-id (gis-db/create-region-with-id! conn old-id "reused" testdata/wkt-multi-polygon)] (is (uuid? new-id)) (is (not= old-id new-id)) (is (= [{:name "reused"}] (jdbc/query conn ["SELECT name FROM subregion WHERE id = ?" new-id])))))))) (deftest gis-change-log-test (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (db/use-tenant-schema conn test-schema) (testing "before making changes" (is (= [] (gis-db/get-changes conn))) (is (nil? (gis-db/next-unprocessed-change conn)))) (testing "territory table change log," (let [territory-id (gis-db/create-territory! conn example-territory)] (testing "insert" (let [changes (gis-db/get-changes conn)] (is (= 1 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "update" (jdbc/execute! conn ["UPDATE territory SET addresses = 'Another Street 2' WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 2 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :UPDATE :gis-change/old {:id territory-id :number "123" :addresses "Street 1 A" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "delete" (jdbc/execute! conn ["DELETE FROM territory WHERE id = ?" territory-id]) (let [changes (gis-db/get-changes conn)] (is (= 3 (count changes))) (is (= {:gis-change/table "territory" :gis-change/op :DELETE :gis-change/old {:id territory-id :number "123" :addresses "Another Street 2" :subregion "Somewhere" :meta {:foo "bar", :gazonk 42} :location testdata/wkt-multi-polygon} :gis-change/new nil :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))))) (testing "congregation_boundary table change log" (let [region-id (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 4 (count changes))) (is (= {:gis-change/table "congregation_boundary" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "region table change log" (let [region-id (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon) changes (gis-db/get-changes conn)] (is (= 5 (count changes))) (is (= {:gis-change/table "subregion" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :name "Somewhere" :location testdata/wkt-multi-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "card_minimap_viewport table change log" (let [region-id (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon) changes (gis-db/get-changes conn)] (is (= 6 (count changes))) (is (= {:gis-change/table "card_minimap_viewport" :gis-change/op :INSERT :gis-change/old nil :gis-change/new {:id region-id :location testdata/wkt-polygon} :gis-change/processed? false} (-> (last changes) (dissoc :gis-change/id :gis-change/schema :gis-change/user :gis-change/time)))))) (testing "get changes since X" (let [all-changes (gis-db/get-changes conn)] (is (= all-changes (gis-db/get-changes conn {:since 0})) "since beginning") (is (= (drop 1 all-changes) (gis-db/get-changes conn {:since 1})) "since first change") (is (= (take-last 1 all-changes) (gis-db/get-changes conn {:since (:gis-change/id (first (take-last 2 all-changes)))})) "since second last change") (is (= [] (gis-db/get-changes conn {:since (:gis-change/id (last all-changes))})) "since last change") ;; should probably be an error, but an empty result is safer than returning all events (is (= [] (gis-db/get-changes conn {:since nil})) "since nil"))) (testing "get changes, limit" (let [all-changes (gis-db/get-changes conn)] (is (= [] (gis-db/get-changes conn {:limit 0})) "limit 0") (is (= (take 1 all-changes) (gis-db/get-changes conn {:limit 1})) "limit 1") (is (= (take 2 all-changes) (gis-db/get-changes conn {:limit 2})) "limit 2") ;; in PostgreSQL, LIMIT NULL (or LIMIT ALL) is the same as omitting the LIMIT (is (= all-changes (gis-db/get-changes conn {:limit nil})) "limit nil"))) (testing "marking changes processed" (is (= [] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, before") (is (= [1 2 3 4 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, before") (is (= 1 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, before") (gis-db/mark-changes-processed! conn [1 2 4]) (is (= [1 2 4] (map :gis-change/id (gis-db/get-changes conn {:processed? true}))) "processed, after") (is (= [3 5 6] (map :gis-change/id (gis-db/get-changes conn {:processed? false}))) "unprocessed, after") (is (= 3 (:gis-change/id (gis-db/next-unprocessed-change conn))) "next unprocessed, after")))) (defn- gis-db-spec [username password] {:connection-uri (-> (:database-url config/env) (str/replace #"\?.*" "")) ; strip username and password :user username :password PI:PASSWORD:<PASSWORD>END_PI}) (defn- login-as [username password] (= [{:user username}] (jdbc/query (gis-db-spec username password) ["select session_user as user"]))) (deftest ensure-gis-user-present-or-absent-test (testing "create account" (db/with-db [conn {}] (is (false? (gis-db/user-exists? conn test-username))) (gis-db/ensure-user-present! conn {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema}) (is (true? (gis-db/user-exists? conn test-username)))) (is (login-as test-username "password1"))) (testing "update account / create is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema})) (is (login-as test-username "password2"))) (testing "delete account" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2")))) (testing "delete is idempotent" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown? PSQLException (login-as test-username "password2"))))) (deftest gis-user-database-access-test (let [password "PI:PASSWORD:<PASSWORD>END_PI" db-spec (gis-db-spec test-username password)] (db/with-db [conn {}] (gis-db/ensure-user-present! conn {:username test-username :password PI:PASSWORD:<PASSWORD>END_PI :schema test-schema})) (testing "can login to the database" (is (= [{:test 1}] (jdbc/query db-spec ["select 1 as test"])))) (testing "can view the tenant schema and the tables in it" (jdbc/with-db-transaction [conn db-spec] (is (jdbc/query conn [(str "select * from " test-schema ".territory")])) (is (jdbc/query conn [(str "select * from " test-schema ".congregation_boundary")])) (is (jdbc/query conn [(str "select * from " test-schema ".subregion")])) (is (jdbc/query conn [(str "select * from " test-schema ".card_minimap_viewport")])))) (testing "can modify data in the tenant schema" (jdbc/with-db-transaction [conn db-spec] (db/use-tenant-schema conn test-schema) (is (gis-db/create-territory! conn example-territory)) (is (gis-db/create-congregation-boundary! conn testdata/wkt-multi-polygon)) (is (gis-db/create-region! conn "Somewhere" testdata/wkt-multi-polygon)) (is (gis-db/create-card-minimap-viewport! conn testdata/wkt-polygon)))) (testing "user ID is logged in GIS change log" (is (= [{:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "territory" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "congregation_boundary" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "subregion" :gis-change/user test-username} {:gis-change/op :INSERT :gis-change/schema test-schema :gis-change/table "card_minimap_viewport" :gis-change/user test-username}] (->> (db/with-db [conn {}] (gis-db/get-changes conn)) (map #(select-keys % [:gis-change/op :gis-change/schema :gis-change/table :gis-change/user])))))) (testing "cannot view the master schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema" (jdbc/query db-spec [(str "select * from " (:database-schema config/env) ".congregation")])))) (testing "cannot create objects in the public schema" (is (thrown-with-msg? PSQLException #"ERROR: permission denied for schema public" (jdbc/execute! db-spec ["create table public.foo (id serial primary key)"])))) (testing "cannot login to database after user is deleted" (db/with-db [conn {}] (gis-db/ensure-user-absent! conn {:username test-username :schema test-schema})) (is (thrown-with-msg? PSQLException #"FATAL: password authentication failed for user" (jdbc/query db-spec ["select 1 as test"])))))) (deftest validate-grants-test (let [grants [{:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "territory", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "subregion", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "congregation_boundary", :privilege_type "DELETE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "SELECT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "INSERT"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "UPDATE"} {:grantee "test_gis_user", :table_schema "test_gis_schema", :table_name "card_minimap_viewport", :privilege_type "DELETE"}]] (is (= {:username "test_gis_user" :schema "test_gis_schema"} (#'gis-db/validate-grants grants))) (is (nil? (#'gis-db/validate-grants (drop 1 grants)))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :grantee] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :privilege_type] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_name] "foo")))) (is (nil? (#'gis-db/validate-grants (assoc-in grants [0 :table_schema] "foo")))))) (deftest get-present-users-test (with-tenant-schema test-schema2 (fn [] (testing "lists GIS users present in the database" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username2 :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema}) (gis-db/ensure-user-present! conn {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema2}) (is (= #{{:username test-username :schema test-schema} {:username test-username2 :schema test-schema} {:username test-username :schema test-schema2}} (set (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))) (testing "doesn't list GIS users with missing grants" (db/with-db [conn {}] (jdbc/db-set-rollback-only! conn) (gis-db/ensure-user-present! conn {:username test-username :password "PI:PASSWORD:<PASSWORD>END_PI" :schema test-schema}) (jdbc/execute! conn [(str "REVOKE DELETE ON TABLE " test-schema ".territory FROM " test-username)]) (is (= [] (gis-db/get-present-users conn {:username-prefix test-username :schema-prefix test-schema})))))))) (deftest get-present-schemas-test (with-tenant-schema test-schema2 (fn [] (testing "lists tenant schemas present in the database" (db/with-db [conn {}] (is (= [test-schema test-schema2] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))) (testing "doesn't list tenant schemas whose migrations are not up to date" (db/with-db [conn {}] (jdbc/execute! conn [(format "UPDATE %s.flyway_schema_history SET checksum = 42 WHERE version = '1'" test-schema2)]) (.commit ^Connection (:connection conn)) ; commit so that Flyway will see the changes, since it uses a new DB connection (is (= [test-schema] (sort (gis-db/get-present-schemas conn {:schema-prefix test-schema})))))))))
[ { "context": "t/map->ContactPersonType\n (merge {:FirstName \"Alice\"\n :LastName \"Bob\"\n :Roles", "end": 4447, "score": 0.9998587965965271, "start": 4442, "tag": "NAME", "value": "Alice" }, { "context": "merge {:FirstName \"Alice\"\n :LastName \"Bob\"\n :Roles [\"AUTHOR\"]}\n attr", "end": 4476, "score": 0.9998294115066528, "start": 4473, "tag": "NAME", "value": "Bob" }, { "context": "e\n (merge {:Type \"Email\"\n :Value \"alice@example.com\"}\n attribs))))\n\n(defn address\n \"Retur", "end": 4801, "score": 0.9999173879623413, "start": 4784, "tag": "EMAIL", "value": "alice@example.com" } ]
system-int-test/src/cmr/system_int_test/data2/umm_spec_tool.clj
brianalexander/Common-Metadata-Repository
0
(ns cmr.system-int-test.data2.umm-spec-tool "Contains tool data generators for example-based testing in system integration tests." (:require [cmr.common.mime-types :as mime-types] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.umm-spec.models.umm-tool-models :as umm-t] [cmr.umm-spec.test.location-keywords-helper :as lkt] [cmr.umm-spec.umm-spec-core :as umm-spec])) (def context (lkt/setup-context-for-test)) (def ^:private sample-umm-tool {:Name "USGS_TOOLS_LATLONG" :LongName "WRS-2 Path/Row to Latitude/Longitude Converter" :Type "Downloadable Tool" :Version "1.0" :Description "The USGS WRS-2 Path/Row to Latitude/Longitude Converter allows users to enter any Landsat path and row to get the nearest scene center latitude and longitude coordinates." :URL {:URLContentType "DistributionURL" :Type "DOWNLOAD SOFTWARE" :Description "Access the WRS-2 Path/Row to Latitude/Longitude Converter." :URLValue "http://www.scp.byu.edu/software/slice_response/Xshape_temp.html"} :ToolKeywords [{:ToolCategory "EARTH SCIENCE SERVICES" :ToolTopic "DATA MANAGEMENT/DATA HANDLING" :ToolTerm "DATA INTEROPERABILITY" :ToolSpecificTerm "DATA REFORMATTING"}] :Organizations [{:Roles ["SERVICE PROVIDER"] :ShortName "USGS/EROS" :LongName "US GEOLOGICAL SURVEY EARTH RESOURCE OBSERVATION AND SCIENCE (EROS) LANDSAT CUSTOMER SERVICES" :URLValue "http://www.usgs.gov"}] :PotentialAction {:Type "SearchAction" :Target {:Type "EntryPoint", :UrlTemplate "https://podaac-tools.jpl.nasa.gov/soto/#b=BlueMarble_ShadedRelief_Bathymetry&l={layers}&ve={bbox}&d={date}" :HttpMethod [ "GET" ] } :QueryInput [{:ValueName "layers" :Description "A comma-separated list of visualization layer ids, as defined by GIBS. These layers will be portrayed on the web application" :ValueRequired true :ValueType "https://wiki.earthdata.nasa.gov/display/GIBS/GIBS+API+for+Developers#GIBSAPIforDevelopers-LayerNaming"} {:ValueName "date" :ValueType "https://schema.org/startDate"} {:ValueName "bbox" :ValueType "https://schema.org/box"}]} :MetadataSpecification {:URL "https://cdn.earthdata.nasa.gov/umm/tool/v1.2.0" :Name "UMM-T" :Version "1.2.0"}}) (defn- tool "Returns a UMM-T record from the given attribute map." ([] (tool {})) ([attribs] (umm-t/map->UMM-T (merge sample-umm-tool attribs))) ([index attribs] (umm-t/map->UMM-T (merge sample-umm-tool {:Name (str "Name " index)} attribs)))) (defn- umm-t->concept "Returns a concept map from a UMM tool item or tombstone." [item] (let [format-key :umm-json format (mime-types/format->mime-type format-key)] (merge {:concept-type :tool :provider-id (or (:provider-id item) "PROV1") :native-id (or (:native-id item) (:Name item)) :metadata (when-not (:deleted item) (umm-spec/generate-metadata context (dissoc item :provider-id :concept-id :native-id) format-key)) :format format} (when (:concept-id item) {:concept-id (:concept-id item)}) (when (:revision-id item) {:revision-id (:revision-id item)})))) (defn tool-concept "Returns the tool for ingest with the given attributes" ([attribs] (let [{:keys [provider-id native-id]} attribs] (-> (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept))) ([attribs index] (let [{:keys [provider-id native-id]} attribs] (-> index (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept)))) (defn contact-person "Returns a ContactPersonType suitable as an element in a Persons collection." ([] (contact-person {})) ([attribs] (umm-t/map->ContactPersonType (merge {:FirstName "Alice" :LastName "Bob" :Roles ["AUTHOR"]} attribs)))) (defn contact-mechanism "Returns a ContactMechanismType suitable as an element in a ContactMechanisms collection." ([] (contact-mechanism {})) ([attribs] (umm-t/map->ContactMechanismType (merge {:Type "Email" :Value "alice@example.com"} attribs)))) (defn address "Returns a AddressType suitable as an element in an Addresses collection." ([] (address {})) ([attribs] (umm-t/map->AddressType (merge {:StreetAddresses ["101 S. Main St"] :City "Anytown" :StateProvince "ST"} attribs)))) (defn contact-info "Returns a ContactInformationType suitable as an element in a ContactInformation collection." ([] (contact-info {})) ([attribs] (umm-t/map->ContactInformationType (merge {:ContactMechanisms [(contact-mechanism)] :Addresses [(address)]} attribs)))) (defn contact-group "Returns a ContectGroupType suitable for inclusion in ContactGroups." ([] (contact-group {})) ([attribs] (umm-t/map->ContactGroupType (merge {:Roles ["SERVICE PROVIDER" "AUTHOR"] :ContactInformation (contact-info) :GroupName "Contact Group Name"} attribs)))) (defn tool-keywords "Returns a ToolKeywordType suitable as an element in a ToolKeywords collection." ([] (tool-keywords {})) ([attribs] (umm-t/map->ToolKeywordType (merge {:ToolCategory "A tool category" :ToolTopic "A tool topic" :ToolTerm "A tool term" :ToolSpecificTerm "A specific tool term"} attribs)))) (defn organization "Returns a OrganizationType suitable as an element in a Organizations collection." ([] (organization {})) ([attribs] (umm-t/map->OrganizationType (merge {:Roles ["SERVICE PROVIDER" "PUBLISHER"] :ShortName "tlorg1" :LongName "Tool Org 1" :URLValue "https://lpdaac.usgs.gov/"} attribs)))) (defn url "Returns a url suitable as an element." ([] (url {})) ([attribs] (umm-t/map->URLType (merge {:URLValue "http://example.com/file" :Description "description" :Type "GET SERVICE" :Subtype "SUBSETTER" :URLContentType "CollectionURL"} attribs)))) (defn related-url "Creates related url for online_only test" ([] (related-url {})) ([attribs] (umm-t/map->RelatedURLType (merge {:URL "http://example.com/file" :Description "description" :Type "GET SERVICE" :URLContentType "CollectionURL"} attribs))))
7795
(ns cmr.system-int-test.data2.umm-spec-tool "Contains tool data generators for example-based testing in system integration tests." (:require [cmr.common.mime-types :as mime-types] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.umm-spec.models.umm-tool-models :as umm-t] [cmr.umm-spec.test.location-keywords-helper :as lkt] [cmr.umm-spec.umm-spec-core :as umm-spec])) (def context (lkt/setup-context-for-test)) (def ^:private sample-umm-tool {:Name "USGS_TOOLS_LATLONG" :LongName "WRS-2 Path/Row to Latitude/Longitude Converter" :Type "Downloadable Tool" :Version "1.0" :Description "The USGS WRS-2 Path/Row to Latitude/Longitude Converter allows users to enter any Landsat path and row to get the nearest scene center latitude and longitude coordinates." :URL {:URLContentType "DistributionURL" :Type "DOWNLOAD SOFTWARE" :Description "Access the WRS-2 Path/Row to Latitude/Longitude Converter." :URLValue "http://www.scp.byu.edu/software/slice_response/Xshape_temp.html"} :ToolKeywords [{:ToolCategory "EARTH SCIENCE SERVICES" :ToolTopic "DATA MANAGEMENT/DATA HANDLING" :ToolTerm "DATA INTEROPERABILITY" :ToolSpecificTerm "DATA REFORMATTING"}] :Organizations [{:Roles ["SERVICE PROVIDER"] :ShortName "USGS/EROS" :LongName "US GEOLOGICAL SURVEY EARTH RESOURCE OBSERVATION AND SCIENCE (EROS) LANDSAT CUSTOMER SERVICES" :URLValue "http://www.usgs.gov"}] :PotentialAction {:Type "SearchAction" :Target {:Type "EntryPoint", :UrlTemplate "https://podaac-tools.jpl.nasa.gov/soto/#b=BlueMarble_ShadedRelief_Bathymetry&l={layers}&ve={bbox}&d={date}" :HttpMethod [ "GET" ] } :QueryInput [{:ValueName "layers" :Description "A comma-separated list of visualization layer ids, as defined by GIBS. These layers will be portrayed on the web application" :ValueRequired true :ValueType "https://wiki.earthdata.nasa.gov/display/GIBS/GIBS+API+for+Developers#GIBSAPIforDevelopers-LayerNaming"} {:ValueName "date" :ValueType "https://schema.org/startDate"} {:ValueName "bbox" :ValueType "https://schema.org/box"}]} :MetadataSpecification {:URL "https://cdn.earthdata.nasa.gov/umm/tool/v1.2.0" :Name "UMM-T" :Version "1.2.0"}}) (defn- tool "Returns a UMM-T record from the given attribute map." ([] (tool {})) ([attribs] (umm-t/map->UMM-T (merge sample-umm-tool attribs))) ([index attribs] (umm-t/map->UMM-T (merge sample-umm-tool {:Name (str "Name " index)} attribs)))) (defn- umm-t->concept "Returns a concept map from a UMM tool item or tombstone." [item] (let [format-key :umm-json format (mime-types/format->mime-type format-key)] (merge {:concept-type :tool :provider-id (or (:provider-id item) "PROV1") :native-id (or (:native-id item) (:Name item)) :metadata (when-not (:deleted item) (umm-spec/generate-metadata context (dissoc item :provider-id :concept-id :native-id) format-key)) :format format} (when (:concept-id item) {:concept-id (:concept-id item)}) (when (:revision-id item) {:revision-id (:revision-id item)})))) (defn tool-concept "Returns the tool for ingest with the given attributes" ([attribs] (let [{:keys [provider-id native-id]} attribs] (-> (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept))) ([attribs index] (let [{:keys [provider-id native-id]} attribs] (-> index (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept)))) (defn contact-person "Returns a ContactPersonType suitable as an element in a Persons collection." ([] (contact-person {})) ([attribs] (umm-t/map->ContactPersonType (merge {:FirstName "<NAME>" :LastName "<NAME>" :Roles ["AUTHOR"]} attribs)))) (defn contact-mechanism "Returns a ContactMechanismType suitable as an element in a ContactMechanisms collection." ([] (contact-mechanism {})) ([attribs] (umm-t/map->ContactMechanismType (merge {:Type "Email" :Value "<EMAIL>"} attribs)))) (defn address "Returns a AddressType suitable as an element in an Addresses collection." ([] (address {})) ([attribs] (umm-t/map->AddressType (merge {:StreetAddresses ["101 S. Main St"] :City "Anytown" :StateProvince "ST"} attribs)))) (defn contact-info "Returns a ContactInformationType suitable as an element in a ContactInformation collection." ([] (contact-info {})) ([attribs] (umm-t/map->ContactInformationType (merge {:ContactMechanisms [(contact-mechanism)] :Addresses [(address)]} attribs)))) (defn contact-group "Returns a ContectGroupType suitable for inclusion in ContactGroups." ([] (contact-group {})) ([attribs] (umm-t/map->ContactGroupType (merge {:Roles ["SERVICE PROVIDER" "AUTHOR"] :ContactInformation (contact-info) :GroupName "Contact Group Name"} attribs)))) (defn tool-keywords "Returns a ToolKeywordType suitable as an element in a ToolKeywords collection." ([] (tool-keywords {})) ([attribs] (umm-t/map->ToolKeywordType (merge {:ToolCategory "A tool category" :ToolTopic "A tool topic" :ToolTerm "A tool term" :ToolSpecificTerm "A specific tool term"} attribs)))) (defn organization "Returns a OrganizationType suitable as an element in a Organizations collection." ([] (organization {})) ([attribs] (umm-t/map->OrganizationType (merge {:Roles ["SERVICE PROVIDER" "PUBLISHER"] :ShortName "tlorg1" :LongName "Tool Org 1" :URLValue "https://lpdaac.usgs.gov/"} attribs)))) (defn url "Returns a url suitable as an element." ([] (url {})) ([attribs] (umm-t/map->URLType (merge {:URLValue "http://example.com/file" :Description "description" :Type "GET SERVICE" :Subtype "SUBSETTER" :URLContentType "CollectionURL"} attribs)))) (defn related-url "Creates related url for online_only test" ([] (related-url {})) ([attribs] (umm-t/map->RelatedURLType (merge {:URL "http://example.com/file" :Description "description" :Type "GET SERVICE" :URLContentType "CollectionURL"} attribs))))
true
(ns cmr.system-int-test.data2.umm-spec-tool "Contains tool data generators for example-based testing in system integration tests." (:require [cmr.common.mime-types :as mime-types] [cmr.system-int-test.data2.umm-spec-common :as data-umm-cmn] [cmr.umm-spec.models.umm-tool-models :as umm-t] [cmr.umm-spec.test.location-keywords-helper :as lkt] [cmr.umm-spec.umm-spec-core :as umm-spec])) (def context (lkt/setup-context-for-test)) (def ^:private sample-umm-tool {:Name "USGS_TOOLS_LATLONG" :LongName "WRS-2 Path/Row to Latitude/Longitude Converter" :Type "Downloadable Tool" :Version "1.0" :Description "The USGS WRS-2 Path/Row to Latitude/Longitude Converter allows users to enter any Landsat path and row to get the nearest scene center latitude and longitude coordinates." :URL {:URLContentType "DistributionURL" :Type "DOWNLOAD SOFTWARE" :Description "Access the WRS-2 Path/Row to Latitude/Longitude Converter." :URLValue "http://www.scp.byu.edu/software/slice_response/Xshape_temp.html"} :ToolKeywords [{:ToolCategory "EARTH SCIENCE SERVICES" :ToolTopic "DATA MANAGEMENT/DATA HANDLING" :ToolTerm "DATA INTEROPERABILITY" :ToolSpecificTerm "DATA REFORMATTING"}] :Organizations [{:Roles ["SERVICE PROVIDER"] :ShortName "USGS/EROS" :LongName "US GEOLOGICAL SURVEY EARTH RESOURCE OBSERVATION AND SCIENCE (EROS) LANDSAT CUSTOMER SERVICES" :URLValue "http://www.usgs.gov"}] :PotentialAction {:Type "SearchAction" :Target {:Type "EntryPoint", :UrlTemplate "https://podaac-tools.jpl.nasa.gov/soto/#b=BlueMarble_ShadedRelief_Bathymetry&l={layers}&ve={bbox}&d={date}" :HttpMethod [ "GET" ] } :QueryInput [{:ValueName "layers" :Description "A comma-separated list of visualization layer ids, as defined by GIBS. These layers will be portrayed on the web application" :ValueRequired true :ValueType "https://wiki.earthdata.nasa.gov/display/GIBS/GIBS+API+for+Developers#GIBSAPIforDevelopers-LayerNaming"} {:ValueName "date" :ValueType "https://schema.org/startDate"} {:ValueName "bbox" :ValueType "https://schema.org/box"}]} :MetadataSpecification {:URL "https://cdn.earthdata.nasa.gov/umm/tool/v1.2.0" :Name "UMM-T" :Version "1.2.0"}}) (defn- tool "Returns a UMM-T record from the given attribute map." ([] (tool {})) ([attribs] (umm-t/map->UMM-T (merge sample-umm-tool attribs))) ([index attribs] (umm-t/map->UMM-T (merge sample-umm-tool {:Name (str "Name " index)} attribs)))) (defn- umm-t->concept "Returns a concept map from a UMM tool item or tombstone." [item] (let [format-key :umm-json format (mime-types/format->mime-type format-key)] (merge {:concept-type :tool :provider-id (or (:provider-id item) "PROV1") :native-id (or (:native-id item) (:Name item)) :metadata (when-not (:deleted item) (umm-spec/generate-metadata context (dissoc item :provider-id :concept-id :native-id) format-key)) :format format} (when (:concept-id item) {:concept-id (:concept-id item)}) (when (:revision-id item) {:revision-id (:revision-id item)})))) (defn tool-concept "Returns the tool for ingest with the given attributes" ([attribs] (let [{:keys [provider-id native-id]} attribs] (-> (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept))) ([attribs index] (let [{:keys [provider-id native-id]} attribs] (-> index (tool attribs) (assoc :provider-id provider-id :native-id native-id) umm-t->concept)))) (defn contact-person "Returns a ContactPersonType suitable as an element in a Persons collection." ([] (contact-person {})) ([attribs] (umm-t/map->ContactPersonType (merge {:FirstName "PI:NAME:<NAME>END_PI" :LastName "PI:NAME:<NAME>END_PI" :Roles ["AUTHOR"]} attribs)))) (defn contact-mechanism "Returns a ContactMechanismType suitable as an element in a ContactMechanisms collection." ([] (contact-mechanism {})) ([attribs] (umm-t/map->ContactMechanismType (merge {:Type "Email" :Value "PI:EMAIL:<EMAIL>END_PI"} attribs)))) (defn address "Returns a AddressType suitable as an element in an Addresses collection." ([] (address {})) ([attribs] (umm-t/map->AddressType (merge {:StreetAddresses ["101 S. Main St"] :City "Anytown" :StateProvince "ST"} attribs)))) (defn contact-info "Returns a ContactInformationType suitable as an element in a ContactInformation collection." ([] (contact-info {})) ([attribs] (umm-t/map->ContactInformationType (merge {:ContactMechanisms [(contact-mechanism)] :Addresses [(address)]} attribs)))) (defn contact-group "Returns a ContectGroupType suitable for inclusion in ContactGroups." ([] (contact-group {})) ([attribs] (umm-t/map->ContactGroupType (merge {:Roles ["SERVICE PROVIDER" "AUTHOR"] :ContactInformation (contact-info) :GroupName "Contact Group Name"} attribs)))) (defn tool-keywords "Returns a ToolKeywordType suitable as an element in a ToolKeywords collection." ([] (tool-keywords {})) ([attribs] (umm-t/map->ToolKeywordType (merge {:ToolCategory "A tool category" :ToolTopic "A tool topic" :ToolTerm "A tool term" :ToolSpecificTerm "A specific tool term"} attribs)))) (defn organization "Returns a OrganizationType suitable as an element in a Organizations collection." ([] (organization {})) ([attribs] (umm-t/map->OrganizationType (merge {:Roles ["SERVICE PROVIDER" "PUBLISHER"] :ShortName "tlorg1" :LongName "Tool Org 1" :URLValue "https://lpdaac.usgs.gov/"} attribs)))) (defn url "Returns a url suitable as an element." ([] (url {})) ([attribs] (umm-t/map->URLType (merge {:URLValue "http://example.com/file" :Description "description" :Type "GET SERVICE" :Subtype "SUBSETTER" :URLContentType "CollectionURL"} attribs)))) (defn related-url "Creates related url for online_only test" ([] (related-url {})) ([attribs] (umm-t/map->RelatedURLType (merge {:URL "http://example.com/file" :Description "description" :Type "GET SERVICE" :URLContentType "CollectionURL"} attribs))))
[ { "context": "{:entity ~person-table :tuples ~(repeat 2 {:Name \"asdf\" :Address {:Address1 \"asdf\" :City \"asdf\"}})})\n ", "end": 2566, "score": 0.9865843653678894, "start": 2562, "tag": "NAME", "value": "asdf" } ]
test/blutwurst/tuple_generator_test.clj
michaeljmcd/blutwurst
0
(ns blutwurst.tuple-generator-test (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [taoensso.timbre :as timbre :refer [trace]] [blutwurst.logging-fixture :refer :all] [blutwurst.value-generators :as vg] [blutwurst.tuple-generator :refer :all])) (def fixed-generators ^{:private true} [{:name "Random String Generator" :determiner #(= (:type %) :string) :generator (fn [x] "asdf")} {:name "Random Integer Generator" :determiner #(= (:type %) :integer) :generator (fn [c] 100)} {:name "Random Decimal Generator" :determiner #(= (:type %) :decimal) :generator (fn [c] 1.7)}]) (use-fixtures :each logging-fixture) (deftest generate-tuples-from-plan-test (testing "Multiple data types." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table-spec '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})}) spec {:number-of-rows 10}] (is (= `({:entity ~(first table-spec) :tuples ~(repeat 10 {:Address1 "asdf" :ID 100})}) (generate-tuples-for-plan spec table-spec))))))) (deftest generate-tuples-with-foreign-keys (testing "Passing an unknown type." (let [a-table '{:name "ASDF" :type :complex :schema "foo" :properties ({:name "BAZ" :type :ixian})} result (generate-tuples-for-plan {} (list a-table))] (is (thrown? NullPointerException (pr-str (seq result)))))) (testing "Embeds full objects for that kind of dependency." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [person-table {:name "Person" :type :complex :schema nil :properties [{:name "Address" :schema nil :properties [{:name "Address1" :type :string :constraints {:maximum-length 10}} {:name "City" :type :string :constraints {:maximum-length 10}}] :type :complex} {:name "Name" :type :string}] :dependencies []} spec {:number-of-rows 2} result (generate-tuples-for-plan spec (list person-table))] (is (= `({:entity ~person-table :tuples ~(repeat 2 {:Name "asdf" :Address {:Address1 "asdf" :City "asdf"}})}) result))))) (testing "Foreign key values are all found in source table." (let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-value 255 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-value 255}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 100} result (generate-tuples-for-plan spec (list weapon-table hero-table)) generated-weapons (-> result first :tuples)] (is (reduce (fn [a b] (and a b)) (map #(some (fn [c] (= (:ID c) (:PrimaryWeaponID %))) generated-weapons) (-> result second :tuples))))))) (deftest generator-overrides (testing "Ignores columns that are passed in the ignore list." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} spec {:number-of-rows 2 :ignored-columns ["I.*"]}] (is (= `({:entity ~weapon-table :tuples ~(repeat 2 {:Name "asdf"})}) (generate-tuples-for-plan spec (list weapon-table))))))) (testing "Ignores columns that are passed in the ignore list when they are also foreign keys." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-length 3}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 1 :ignored-columns ["PrimaryWeaponID"]} result (generate-tuples-for-plan spec (list weapon-table hero-table))] (is (= (list {:Name "asdf"}) (:tuples (nth result 1))))))) (testing "Generator override is used." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:column-generator-overrides (list {:column-pattern "^ID$" :generator-name "Random Decimal Generator"}) :number-of-rows 5} tables '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})})] (is (= `({:entity ~(first tables) :tuples ~(repeat 5 {:Address1 "asdf" :ID 1.7})}) (generate-tuples-for-plan spec tables))))))) (deftest simple-generation (testing "Generates simple string values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table {:name "foo" :type :string} result (generate-tuples-for-plan {:number-of-rows 2} (list table))] (is (= `({:entity ~table :tuples ~(repeat 2 {:foo "asdf"})}) result)))))) (deftest complex-generation (testing "Generates a list of primitve values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:format :csv :number-of-rows 2} plan '({:name "foo" :type :complex :schema nil :properties ({:name "nums" :type :sequence :properties ({:name "items" :type "string"})})}) result (generate-tuples-for-plan spec plan)] (is (= `({:entity ~(first plan) :tuples ~(repeat 2 {:nums [1 2 3]})}) result))))))
4966
(ns blutwurst.tuple-generator-test (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [taoensso.timbre :as timbre :refer [trace]] [blutwurst.logging-fixture :refer :all] [blutwurst.value-generators :as vg] [blutwurst.tuple-generator :refer :all])) (def fixed-generators ^{:private true} [{:name "Random String Generator" :determiner #(= (:type %) :string) :generator (fn [x] "asdf")} {:name "Random Integer Generator" :determiner #(= (:type %) :integer) :generator (fn [c] 100)} {:name "Random Decimal Generator" :determiner #(= (:type %) :decimal) :generator (fn [c] 1.7)}]) (use-fixtures :each logging-fixture) (deftest generate-tuples-from-plan-test (testing "Multiple data types." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table-spec '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})}) spec {:number-of-rows 10}] (is (= `({:entity ~(first table-spec) :tuples ~(repeat 10 {:Address1 "asdf" :ID 100})}) (generate-tuples-for-plan spec table-spec))))))) (deftest generate-tuples-with-foreign-keys (testing "Passing an unknown type." (let [a-table '{:name "ASDF" :type :complex :schema "foo" :properties ({:name "BAZ" :type :ixian})} result (generate-tuples-for-plan {} (list a-table))] (is (thrown? NullPointerException (pr-str (seq result)))))) (testing "Embeds full objects for that kind of dependency." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [person-table {:name "Person" :type :complex :schema nil :properties [{:name "Address" :schema nil :properties [{:name "Address1" :type :string :constraints {:maximum-length 10}} {:name "City" :type :string :constraints {:maximum-length 10}}] :type :complex} {:name "Name" :type :string}] :dependencies []} spec {:number-of-rows 2} result (generate-tuples-for-plan spec (list person-table))] (is (= `({:entity ~person-table :tuples ~(repeat 2 {:Name "<NAME>" :Address {:Address1 "asdf" :City "asdf"}})}) result))))) (testing "Foreign key values are all found in source table." (let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-value 255 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-value 255}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 100} result (generate-tuples-for-plan spec (list weapon-table hero-table)) generated-weapons (-> result first :tuples)] (is (reduce (fn [a b] (and a b)) (map #(some (fn [c] (= (:ID c) (:PrimaryWeaponID %))) generated-weapons) (-> result second :tuples))))))) (deftest generator-overrides (testing "Ignores columns that are passed in the ignore list." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} spec {:number-of-rows 2 :ignored-columns ["I.*"]}] (is (= `({:entity ~weapon-table :tuples ~(repeat 2 {:Name "asdf"})}) (generate-tuples-for-plan spec (list weapon-table))))))) (testing "Ignores columns that are passed in the ignore list when they are also foreign keys." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-length 3}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 1 :ignored-columns ["PrimaryWeaponID"]} result (generate-tuples-for-plan spec (list weapon-table hero-table))] (is (= (list {:Name "asdf"}) (:tuples (nth result 1))))))) (testing "Generator override is used." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:column-generator-overrides (list {:column-pattern "^ID$" :generator-name "Random Decimal Generator"}) :number-of-rows 5} tables '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})})] (is (= `({:entity ~(first tables) :tuples ~(repeat 5 {:Address1 "asdf" :ID 1.7})}) (generate-tuples-for-plan spec tables))))))) (deftest simple-generation (testing "Generates simple string values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table {:name "foo" :type :string} result (generate-tuples-for-plan {:number-of-rows 2} (list table))] (is (= `({:entity ~table :tuples ~(repeat 2 {:foo "asdf"})}) result)))))) (deftest complex-generation (testing "Generates a list of primitve values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:format :csv :number-of-rows 2} plan '({:name "foo" :type :complex :schema nil :properties ({:name "nums" :type :sequence :properties ({:name "items" :type "string"})})}) result (generate-tuples-for-plan spec plan)] (is (= `({:entity ~(first plan) :tuples ~(repeat 2 {:nums [1 2 3]})}) result))))))
true
(ns blutwurst.tuple-generator-test (:require [clojure.test :refer :all] [clojure.pprint :refer :all] [taoensso.timbre :as timbre :refer [trace]] [blutwurst.logging-fixture :refer :all] [blutwurst.value-generators :as vg] [blutwurst.tuple-generator :refer :all])) (def fixed-generators ^{:private true} [{:name "Random String Generator" :determiner #(= (:type %) :string) :generator (fn [x] "asdf")} {:name "Random Integer Generator" :determiner #(= (:type %) :integer) :generator (fn [c] 100)} {:name "Random Decimal Generator" :determiner #(= (:type %) :decimal) :generator (fn [c] 1.7)}]) (use-fixtures :each logging-fixture) (deftest generate-tuples-from-plan-test (testing "Multiple data types." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table-spec '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})}) spec {:number-of-rows 10}] (is (= `({:entity ~(first table-spec) :tuples ~(repeat 10 {:Address1 "asdf" :ID 100})}) (generate-tuples-for-plan spec table-spec))))))) (deftest generate-tuples-with-foreign-keys (testing "Passing an unknown type." (let [a-table '{:name "ASDF" :type :complex :schema "foo" :properties ({:name "BAZ" :type :ixian})} result (generate-tuples-for-plan {} (list a-table))] (is (thrown? NullPointerException (pr-str (seq result)))))) (testing "Embeds full objects for that kind of dependency." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [person-table {:name "Person" :type :complex :schema nil :properties [{:name "Address" :schema nil :properties [{:name "Address1" :type :string :constraints {:maximum-length 10}} {:name "City" :type :string :constraints {:maximum-length 10}}] :type :complex} {:name "Name" :type :string}] :dependencies []} spec {:number-of-rows 2} result (generate-tuples-for-plan spec (list person-table))] (is (= `({:entity ~person-table :tuples ~(repeat 2 {:Name "PI:NAME:<NAME>END_PI" :Address {:Address1 "asdf" :City "asdf"}})}) result))))) (testing "Foreign key values are all found in source table." (let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-value 255 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-value 255}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 100} result (generate-tuples-for-plan spec (list weapon-table hero-table)) generated-weapons (-> result first :tuples)] (is (reduce (fn [a b] (and a b)) (map #(some (fn [c] (= (:ID c) (:PrimaryWeaponID %))) generated-weapons) (-> result second :tuples))))))) (deftest generator-overrides (testing "Ignores columns that are passed in the ignore list." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} spec {:number-of-rows 2 :ignored-columns ["I.*"]}] (is (= `({:entity ~weapon-table :tuples ~(repeat 2 {:Name "asdf"})}) (generate-tuples-for-plan spec (list weapon-table))))))) (testing "Ignores columns that are passed in the ignore list when they are also foreign keys." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [weapon-table '{:name "Weapon" :type :complex :schema "asdf" :properties ({:name "ID" :type :integer :constraints {:maximum-length 3 :nullable false}} {:name "Name" :type :string :constraints {:maximum-length 3 :nullable false}})} hero-table '{:name "Hero" :type :complex :schema "asdf" :properties ({:name "Name" :type :string :constraints {:maximum-length 200}} {:name "PrimaryWeaponID" :type :integer :constraints {:maximum-length 3}}) :dependencies [{:target-name "Weapon" :target-schema "asdf" :links {"PrimaryWeaponID" "ID"}}]} spec {:number-of-rows 1 :ignored-columns ["PrimaryWeaponID"]} result (generate-tuples-for-plan spec (list weapon-table hero-table))] (is (= (list {:Name "asdf"}) (:tuples (nth result 1))))))) (testing "Generator override is used." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:column-generator-overrides (list {:column-pattern "^ID$" :generator-name "Random Decimal Generator"}) :number-of-rows 5} tables '({:name "Destination" :schema "foo" :type :complex :properties ({:name "Address1" :type :string :constraints {:maximum-length 20 :nullable false}} {:name "ID" :type :integer :constraints {:maximum-length 3 :nullable true}})})] (is (= `({:entity ~(first tables) :tuples ~(repeat 5 {:Address1 "asdf" :ID 1.7})}) (generate-tuples-for-plan spec tables))))))) (deftest simple-generation (testing "Generates simple string values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [table {:name "foo" :type :string} result (generate-tuples-for-plan {:number-of-rows 2} (list table))] (is (= `({:entity ~table :tuples ~(repeat 2 {:foo "asdf"})}) result)))))) (deftest complex-generation (testing "Generates a list of primitve values." (with-redefs-fn {#'vg/create-generators #(do % fixed-generators)} #(let [spec {:format :csv :number-of-rows 2} plan '({:name "foo" :type :complex :schema nil :properties ({:name "nums" :type :sequence :properties ({:name "items" :type "string"})})}) result (generate-tuples-for-plan spec plan)] (is (= `({:entity ~(first plan) :tuples ~(repeat 2 {:nums [1 2 3]})}) result))))))
[ { "context": " \"cm\"\n :data-key \"depth\"\n :id \"depth", "end": 1365, "score": 0.8939319252967834, "start": 1360, "tag": "KEY", "value": "depth" } ]
src/main/app/ui/dashboard/depth.cljs
joshuawood2894/fulcro_postgresql_mqtt_template
0
(ns app.ui.dashboard.depth (:require [app.model.dashboard.depth :as md] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.depth :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc DepthChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Water Depth in Centimeters" md/toggle-depth-settings! (:toggle-settings props)) :cover (if (empty? (:depth props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:depth props) :x-axis-label "Time" :y-axis-label "Depth in Centimeters" :unit-symbol "cm" :data-key "depth" :id "depth-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) md/set-depth-start-end-datetime! md/set-depth-color! md/set-depth-min-bound! md/set-depth-max-bound! md/redo-depth-min-max-bound! (:chart-type props) md/set-depth-chart-type!)})) (def ui-depth-chart (comp/factory DepthChart)) (defsc DepthData [this {:depth-data/keys [depth start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:depth-data/depth (comp/get-query dl/DepthReading)} :depth-data/start-date :depth-data/end-date :depth-data/toggle-settings :depth-data/color :depth-data/min-bound :depth-data/max-bound :depth-data/chart-type] :ident (fn [] [:component/id :depth-data]) :initial-state {:depth-data/toggle-settings false :depth-data/min-bound js/NaN :depth-data/max-bound js/NaN :depth-data/chart-type "line" :depth-data/color ant/blue-primary :depth-data/start-date (js/Date.) :depth-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :depth-data/depth [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :depth 393} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :depth 295} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :depth 300} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :depth 400} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :depth 450} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :depth 380} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :depth 375}]}} (ui-depth-chart {:depth depth :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-depth-data (comp/factory DepthData))
39475
(ns app.ui.dashboard.depth (:require [app.model.dashboard.depth :as md] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.depth :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc DepthChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Water Depth in Centimeters" md/toggle-depth-settings! (:toggle-settings props)) :cover (if (empty? (:depth props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:depth props) :x-axis-label "Time" :y-axis-label "Depth in Centimeters" :unit-symbol "cm" :data-key "<KEY>" :id "depth-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) md/set-depth-start-end-datetime! md/set-depth-color! md/set-depth-min-bound! md/set-depth-max-bound! md/redo-depth-min-max-bound! (:chart-type props) md/set-depth-chart-type!)})) (def ui-depth-chart (comp/factory DepthChart)) (defsc DepthData [this {:depth-data/keys [depth start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:depth-data/depth (comp/get-query dl/DepthReading)} :depth-data/start-date :depth-data/end-date :depth-data/toggle-settings :depth-data/color :depth-data/min-bound :depth-data/max-bound :depth-data/chart-type] :ident (fn [] [:component/id :depth-data]) :initial-state {:depth-data/toggle-settings false :depth-data/min-bound js/NaN :depth-data/max-bound js/NaN :depth-data/chart-type "line" :depth-data/color ant/blue-primary :depth-data/start-date (js/Date.) :depth-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :depth-data/depth [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :depth 393} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :depth 295} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :depth 300} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :depth 400} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :depth 450} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :depth 380} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :depth 375}]}} (ui-depth-chart {:depth depth :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-depth-data (comp/factory DepthData))
true
(ns app.ui.dashboard.depth (:require [app.model.dashboard.depth :as md] [app.ui.dashboard.config :as dc] [app.ui.antd.components :as ant] [app.ui.data-logger.depth :as dl] [com.fulcrologic.fulcro.components :as comp :refer [defsc]] [com.fulcrologic.fulcro.dom :as dom :refer [div ul li h3 p]] [com.fulcrologic.fulcro.mutations :as m :refer [defmutation]])) (defsc DepthChart [this props] (ant/card {:style {:width 500 :textAlign "center"} :bodyStyle {:margin "0px" :padding "0px"} :headStyle {:backgroundColor "#001529" :color "white"} :title (dc/create-card-title "Water Depth in Centimeters" md/toggle-depth-settings! (:toggle-settings props)) :cover (if (empty? (:depth props)) (div {:style {:width 485 :height 275}} (ant/ant-empty {:style {:paddingTop "15%"}})) (dc/create-rechart (:chart-type props) {:data (:depth props) :x-axis-label "Time" :y-axis-label "Depth in Centimeters" :unit-symbol "cm" :data-key "PI:KEY:<KEY>END_PI" :id "depth-id" :color (:color props) :min-bound (:min-bound props) :max-bound (:max-bound props)})) :actions (dc/create-dropdown-settings (:toggle-settings props) md/set-depth-start-end-datetime! md/set-depth-color! md/set-depth-min-bound! md/set-depth-max-bound! md/redo-depth-min-max-bound! (:chart-type props) md/set-depth-chart-type!)})) (def ui-depth-chart (comp/factory DepthChart)) (defsc DepthData [this {:depth-data/keys [depth start-date end-date toggle-settings color min-bound max-bound chart-type] :as props}] {:query [{:depth-data/depth (comp/get-query dl/DepthReading)} :depth-data/start-date :depth-data/end-date :depth-data/toggle-settings :depth-data/color :depth-data/min-bound :depth-data/max-bound :depth-data/chart-type] :ident (fn [] [:component/id :depth-data]) :initial-state {:depth-data/toggle-settings false :depth-data/min-bound js/NaN :depth-data/max-bound js/NaN :depth-data/chart-type "line" :depth-data/color ant/blue-primary :depth-data/start-date (js/Date.) :depth-data/end-date (js/Date. (.setHours (js/Date.) (- (.getHours (js/Date.)) 24))) :depth-data/depth [{:id 1 :time (js/Date. "March 17, 2021 15:24:00") :depth 393} {:id 2 :time (js/Date. "March 17, 2021 15:25:00") :depth 295} {:id 3 :time (js/Date. "March 17, 2021 15:26:00") :depth 300} {:id 4 :time (js/Date. "March 17, 2021 15:27:00") :depth 400} {:id 5 :time (js/Date. "March 17, 2021 15:28:00") :depth 450} {:id 6 :time (js/Date. "March 17, 2021 15:29:00") :depth 380} {:id 7 :time (js/Date. "March 17, 2021 15:30:00") :depth 375}]}} (ui-depth-chart {:depth depth :toggle-settings toggle-settings :color color :min-bound min-bound :max-bound max-bound :chart-type chart-type})) (def ui-depth-data (comp/factory DepthData))
[ { "context": "acc))\n acc))))\n\n(def my-acc (make-new-acc \"Ben\" 5000))\n\n(defn my-loop [] (let [the-acc my-acc]\n ", "end": 465, "score": 0.9682021737098694, "start": 462, "tag": "NAME", "value": "Ben" } ]
lang/java7developer/clojure/listing_10_12.clj
zizhizhan/jvm-snippets
0
(defn make-new-acc [account-name opening-balance] (ref {:name account-name :bal opening-balance})) (defn alter-acc [acc new-name new-balance] (assoc acc :bal new-balance :name new-name)) (defn loop-and-debit [account] (loop [acc account] (let [balance (:bal @acc) my-name (:name @acc)] (Thread/sleep 1) (if (> balance 0) (recur (dosync (alter acc alter-acc my-name (dec balance)) acc)) acc)))) (def my-acc (make-new-acc "Ben" 5000)) (defn my-loop [] (let [the-acc my-acc] (loop-and-debit the-acc))) (pcalls my-loop my-loop my-loop my-loop my-loop)
30444
(defn make-new-acc [account-name opening-balance] (ref {:name account-name :bal opening-balance})) (defn alter-acc [acc new-name new-balance] (assoc acc :bal new-balance :name new-name)) (defn loop-and-debit [account] (loop [acc account] (let [balance (:bal @acc) my-name (:name @acc)] (Thread/sleep 1) (if (> balance 0) (recur (dosync (alter acc alter-acc my-name (dec balance)) acc)) acc)))) (def my-acc (make-new-acc "<NAME>" 5000)) (defn my-loop [] (let [the-acc my-acc] (loop-and-debit the-acc))) (pcalls my-loop my-loop my-loop my-loop my-loop)
true
(defn make-new-acc [account-name opening-balance] (ref {:name account-name :bal opening-balance})) (defn alter-acc [acc new-name new-balance] (assoc acc :bal new-balance :name new-name)) (defn loop-and-debit [account] (loop [acc account] (let [balance (:bal @acc) my-name (:name @acc)] (Thread/sleep 1) (if (> balance 0) (recur (dosync (alter acc alter-acc my-name (dec balance)) acc)) acc)))) (def my-acc (make-new-acc "PI:NAME:<NAME>END_PI" 5000)) (defn my-loop [] (let [the-acc my-acc] (loop-and-debit the-acc))) (pcalls my-loop my-loop my-loop my-loop my-loop)
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 29, "score": 0.9998742341995239, "start": 18, "tag": "NAME", "value": "Rich Hickey" }, { "context": "tice, or any other, from this software.\n\n; Author: Frantisek Sodomka\n\n\n(ns clojure.test-clojure.parallel\n (:use cloju", "end": 491, "score": 0.9998869299888611, "start": 474, "tag": "NAME", "value": "Frantisek Sodomka" } ]
ThirdParty/clojure-1.1.0/test/clojure/test_clojure/parallel.clj
allertonm/Couverjure
3
; Copyright (c) Rich Hickey. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: Frantisek Sodomka (ns clojure.test-clojure.parallel (:use clojure.test)) ;; !! Tests for the parallel library will be in a separate file clojure_parallel.clj !! ; future-call ; future ; pmap ; pcalls ; pvalues ;; pmap ;; (deftest pmap-does-its-thing ;; regression fixed in r1218; was OutOfMemoryError (is (= '(1) (pmap inc [0]))))
10203
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: <NAME> (ns clojure.test-clojure.parallel (:use clojure.test)) ;; !! Tests for the parallel library will be in a separate file clojure_parallel.clj !! ; future-call ; future ; pmap ; pcalls ; pvalues ;; pmap ;; (deftest pmap-does-its-thing ;; regression fixed in r1218; was OutOfMemoryError (is (= '(1) (pmap inc [0]))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Author: PI:NAME:<NAME>END_PI (ns clojure.test-clojure.parallel (:use clojure.test)) ;; !! Tests for the parallel library will be in a separate file clojure_parallel.clj !! ; future-call ; future ; pmap ; pcalls ; pvalues ;; pmap ;; (deftest pmap-does-its-thing ;; regression fixed in r1218; was OutOfMemoryError (is (= '(1) (pmap inc [0]))))
[ { "context": "defmacro fast-get-in\n \"In his ClojuTre 2019 talk, Tommi Riemann says that `->` is\n signifantly faster than `get-", "end": 763, "score": 0.9975454211235046, "start": 750, "tag": "NAME", "value": "Tommi Riemann" } ]
modules/deprecated/src/juxt/apex/alpha2/util.clj
SevereOverfl0w/apex
123
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha2.util (:require [juxt.jinx-alpha.resolve :refer [resolve-ref]])) (defn to-rfc-1123-date-time [instant] (.format java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME (java.time.ZonedDateTime/ofInstant instant (java.time.ZoneId/of "GMT")))) (defn from-rfc-1123-date-time [s] (some->> s (.parse java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME) (java.time.Instant/from))) (defn resolve-json-ref "Resolve a json reference. If ref is already resolved, then return it unchanged." [ref {:keys [base-document]}] (if (contains? ref "$ref") (resolve-ref ref base-document {}) [ref nil])) (defmacro fast-get-in "In his ClojuTre 2019 talk, Tommi Riemann says that `->` is signifantly faster than `get-in`." ([m args] `(fast-get-in ~m ~args nil)) ([m args not-found] `(let [res# (-> ~m ~@(for [i args] (if (keyword? i) `~i `(get ~i))))] (if res# res# ~not-found))))
111090
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha2.util (:require [juxt.jinx-alpha.resolve :refer [resolve-ref]])) (defn to-rfc-1123-date-time [instant] (.format java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME (java.time.ZonedDateTime/ofInstant instant (java.time.ZoneId/of "GMT")))) (defn from-rfc-1123-date-time [s] (some->> s (.parse java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME) (java.time.Instant/from))) (defn resolve-json-ref "Resolve a json reference. If ref is already resolved, then return it unchanged." [ref {:keys [base-document]}] (if (contains? ref "$ref") (resolve-ref ref base-document {}) [ref nil])) (defmacro fast-get-in "In his ClojuTre 2019 talk, <NAME> says that `->` is signifantly faster than `get-in`." ([m args] `(fast-get-in ~m ~args nil)) ([m args not-found] `(let [res# (-> ~m ~@(for [i args] (if (keyword? i) `~i `(get ~i))))] (if res# res# ~not-found))))
true
;; Copyright © 2020, JUXT LTD. (ns juxt.apex.alpha2.util (:require [juxt.jinx-alpha.resolve :refer [resolve-ref]])) (defn to-rfc-1123-date-time [instant] (.format java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME (java.time.ZonedDateTime/ofInstant instant (java.time.ZoneId/of "GMT")))) (defn from-rfc-1123-date-time [s] (some->> s (.parse java.time.format.DateTimeFormatter/RFC_1123_DATE_TIME) (java.time.Instant/from))) (defn resolve-json-ref "Resolve a json reference. If ref is already resolved, then return it unchanged." [ref {:keys [base-document]}] (if (contains? ref "$ref") (resolve-ref ref base-document {}) [ref nil])) (defmacro fast-get-in "In his ClojuTre 2019 talk, PI:NAME:<NAME>END_PI says that `->` is signifantly faster than `get-in`." ([m args] `(fast-get-in ~m ~args nil)) ([m args not-found] `(let [res# (-> ~m ~@(for [i args] (if (keyword? i) `~i `(get ~i))))] (if res# res# ~not-found))))