001 (ns ^{:doc "Route which serves and handles the rules page."
002 :author "Simon Brooke"}
003 mw-ui.routes.rules
004 (:require [clojure.walk :refer [keywordize-keys]]
005 [mw-parser.bulk :as compiler]
006 [mw-ui.layout :as layout]
007 [noir.io :as io]
008 [noir.session :as session]))
009
010 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
011 ;;;;
012 ;;;; mw-ui: a servlet user/visualisation interface for MicroWorld.
013 ;;;;
014 ;;;; This program is free software; you can redistribute it and/or
015 ;;;; modify it under the terms of the GNU General Public License
016 ;;;; as published by the Free Software Foundation; either version 2
017 ;;;; of the License, or (at your option) any later version.
018 ;;;;
019 ;;;; This program is distributed in the hope that it will be useful,
020 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
021 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
022 ;;;; GNU General Public License for more details.
023 ;;;;
024 ;;;; You should have received a copy of the GNU General Public License
025 ;;;; along with this program; if not, write to the Free Software
026 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
027 ;;;; USA.
028 ;;;;
029 ;;;; Copyright (C) 2014 Simon Brooke
030 ;;;;
031 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
032
033
034 (defn process-rules-request
035 [request]
036 (let [src (:src (keywordize-keys (:form-params request)))]
037 (try
038 (cond src
039 (let [rules (compiler/compile-string src)]
040 {:rule-text src
041 :rules rules
042 :message (str "Successfully compiled "
043 (count rules)
044 " rules") })
045 :else {:rule-text (or
046 (session/get :rule-text)
047 (io/slurp-resource "/rulesets/basic.txt"))
048 :message "No rules found in request; loading defaults"})
049 (catch Exception e
050 {:rule-text src
051 :message "An error occurred during compilation"
052 :error (str (.getName (.getClass e)) ": " (.getMessage e))}))))
053
054
055 (defn rules-page
056 "Request handler for the `rules` request. If the `request` contains a value
057 for `:src`, treat that as rule source and try to compile it. If compilation
058 succeeds, stash the compiled rules and the rule text on the session, and
059 provide feedback; if not, provide feedback.
060
061 If `request` doesn't contain a value for `:src`, load basic rule source from
062 the session or from `resources/rulesets/basic.txt` and pass that back."
063 ([request]
064 (let [processed (process-rules-request request)]
065 (when (:rules processed)
066 (session/put! :rules (:rules processed)))
067 (when (:rule-text processed)
068 (session/put! :rule-text (:rule-text processed)))
069 (layout/render "rules.html"
070 (merge {:title "Edit Rules"} processed))))
071 ([]
072 (rules-page nil)))