EzDevInfo.com

ring

Clojure web application library: abstracts HTTP to allow modular and concise webapps

How to convert map to URL query string in Clojure/Compojure/Ring?

In Clojure / Compojure, how do I convert a map to a URL query string?

{:foo 1 :bar 2 :baz 3}

to

foo=1&bar=2&baz=3

Is there any utility method to do this in compojure?


Source: (StackOverflow)

How do I stop jetty server in clojure?

I am writing a web application using ring and clojure. I am using the jetty adapter for the development server and emacs/SLIME for IDE. While wrap-reload does help, run-jetty blocks my slime session and I would like to be able to start/stop it at will without having to run it in a separate terminal session. Ideally, I would like to define a server agent and functions start-server and stop-server that would start/stop the server inside the agent. Is this possible?


Source: (StackOverflow)

Advertisements

CPU Privilege Rings: Why rings 1 and 2 aren't used?

A couple of questions regarding the x86 CPU privilege rings:

  • Why aren't rings 1 and 2 used by most operating systems? Is it just to maintain code compatibility with other architectures, or is there a better reason?

  • Are there any operating systems which actually use those rings? Or are they completely unused?


Source: (StackOverflow)

In clojure/ring, how do I delete a cookie?

Suppose I want to delete a cookie (for example ring's session cookie):

Making a response map like this:

{:cookies {"ring-session" {:value "kill", :max-age 1}}}

seems to work, but it's a bit hacky.

Is there a clean way to just delete it?


Source: (StackOverflow)

ring/compojure without jetty

I know it's possible to create a war file using lein ring war, but it seems to still include jetty dependencies. Is there a way to exclude the jetty dependencies when I'm building the war (and deploying on tomcat)?

If I can't does this matter at all or is it just extra jars/class files that are packaged up into the war but never actually used?


Source: (StackOverflow)

a directory explorer middleware for ring clojure [closed]

Are there any available middleware for ring that would mimic the way a standard file server like apache handles routes

so the handler would look something like this:

(wrap-dir "resources/public/")

which is very similar to

(wrap-file "resources/public/")

but will also output directory listings.


Source: (StackOverflow)

how I can start lein ring server in background?

Now what I do is:

$ lein ring server &

Then what I see is: [1]+ Stopped lein ring server. Then I'm trying to use:

$ fg 1

And also see that it's stopped. What do I do wrong and how can I run ring as a background process?


Source: (StackOverflow)

Missing *out* in Clojure with Lein and Ring

I am running Lein 2 and cider 0.7.0. I made a sample ring app that uses ring/run-jetty to start.

(ns nimbus-admin.handler
  (:require [compojure.core :refer :all]
            [compojure.handler :as handler]
            [clojure.tools.nrepl.server :as nrepl-server]
            [cider.nrepl :refer (cider-nrepl-handler)]
            [ring.adapter.jetty :as ring]
            [clojure.tools.trace :refer [trace]]
            [ring.util.response :refer [resource-response response redirect content-type]]
            [compojure.route :as route])
  (:gen-class))


(defroutes app-routes 
  (GET "/blah" req "blah")
  (route/resources "/")
  (route/not-found (trace "not-found" "Not Found")))

(def app (handler/site app-routes))

(defn start-nrepl-server []
  (nrepl-server/start-server :port 7888 :handler cider-nrepl-handler))

(defn start-jetty [ip port]
  (ring/run-jetty app {:port port :ip ip}))

(defn -main
  ([] (-main 8080 "0.0.0.0"))
  ([port ip & args] 
     (let [port (Integer. port)]
       (start-nrepl-server)
       (start-jetty ip port))))

then connect to it with cider like:

cider-connect 127.0.0.1 7888

I can navigate to my site and eval forms in emacs and it will update what is running live in my nrepl session, so that is great.

I cannot see output, either with (print "test") (println "test") (trace "out" 1)

Finally, my project file:

(defproject nimbus-admin "0.1.0"
  :description ""
  :url ""
  :min-lein-version "2.0.0"
  :dependencies [[org.clojure/clojure "1.6.0"]
                 [com.climate/clj-newrelic "0.1.1"]
                 [com.ashafa/clutch "0.4.0-RC1"]
                 [ring "1.3.1"]
                 [clj-time "0.8.0"]
                 [midje "1.6.3"]
                 [org.clojure/tools.nrepl "0.2.6"]
                 [ring/ring-json "0.3.1"]
                 [org.clojure/tools.trace "0.7.8"]
                 [compojure "1.1.9"]
                 [org.clojure/data.json "0.2.5"]
                 [org.clojure/core.async "0.1.346.0-17112a-alpha"]
                 ]
  :plugins [[lein-environ "1.0.0"]
            [cider/cider-nrepl "0.7.0"]]
  :main nimbus-admin.handler)

I start the site with lein run

Edit I CAN see output, ONLY when using (.println System/out msg)


Source: (StackOverflow)

How to build clojure application with ring server

I got clojure project with ring library in it. This is project.clj:

(defproject words "1.0.0-SNAPSHOT"
:description "Websocket handler for sessions"
:dependencies [[org.clojure/clojure "1.4.0"]
  [org.clojure/clojure-contrib "1.2.0"]
  [aleph "0.3.0-alpha1"]
  [org.clojure/data.json "0.1.2"]
  [clj-redis "0.0.13-SNAPSHOT"]
  [compojure "0.6.2"]
  [clj-http "0.1.3"]]
:main words.play
;; Lein ring plugin will provide `lein ring server` functionality
;; (and some other relative to ring actions)
:plugins [[lein-ring "0.6.6"]]
:ring {:handler words.api/engine})

In development environment I run it with 2 commands: lein run server lein ring server and it's works.

For production environment I want to minimize dependencies and build it into standalone jar with:

lein uberjar

How can I build it and run both of servers from one jar file?


Source: (StackOverflow)

how do i mock a json post request in ring?

I'm using peridot - https://github.com/xeqi/peridot to test my ring application, and its working fine until I try to mock a post request with json data:

(require '[cheshire.core :as json])
(use 'compojure.core)

(defn json-post [req]
  (if (:body req)
    (json/parse-string (slurp (:body req)))))

(defroutes all-routes
  (POST "/test/json" req  (json-response (json-post req))))

(def app (compojure.handler/site all-routes))

(use 'peridot.core)

(-> (session app)
    (request "/test/json"
             :request-method :post
             :body (java.io.ByteArrayInputStream. (.getBytes "hello" "UTF-8")))

gives IOException: stream closed.

Is there a better way to do this?


Source: (StackOverflow)

Clojure/Ring: How can I integrate my clojure app with a java build process that is out of my control?

I have a unique build situation. I am using lein uberwar to build a war out of my ring application and deploy to beanstalk. This is all working great. Now it comes up as a requirement that we need to push code to an svn repo where they will manage the build, which knows nothing about clojure (only java). It is a huge bureaucratic organization and their build process is already in place, so having them install lein on their servers is currently out of the question. I know that lein uses maven underneath the hood so I know this could work in theory, yet I am still in doubt on a couple steps of this process.

I went through the war-building process in lein-ring and the main hangups I see are that the servlet and listener classes are generated, along with the web.xml. I feel like I could provide java files that do this task, but am unclear on what those java files would contain and where they would ultimately live inside the structure of the project. Looking at the servlet.clj and listener.clj files that get generated in the ultimate war they seem very simple, possibly examples already exist for this?

The other big hurdle I see is that the war process calls clojure.core/compile on the project namespace, which generates all the class files from the clojure source. Is there some way to trigger this compilation during the build from maven? I am almost imagining a java class that farms out compilation to clojure.core/compile, but I am not sure of the ins and outs of calling clojure from java, rather than vice versa (the usual direction of flow), or how to insert this step into a basic maven build process.

Any insights into where to start on any of this would be most welcome! Thanks all.


Source: (StackOverflow)

Reloading code on a production ring-clojure server

What's the best way to push new code to a production ring server without restarting the whole JVM?

Currently I use wrap-reload in production, but this doesn't quite work for me because sometimes I want to run commands in the repl (doing database migrations for example) before ring starts handling requests with the new code. Also various blogs and tutorials out there say not to use wrap-reload in production, though I don't understand why not.

I have come up with the following solution, but I confess I don't have a deep understanding of what's going on under the hood. I was wondering if I could get a sanity check by someone who does. Does this technique seem reasonable?

The idea is to have a path (/admin/reload-clj) that causes all the clojure code to be reloaded.

(defonce ^:dynamic *jetty*)
(declare reload-clj)

(defn app [req]
 ...
 (when (= (req :uri) "/admin/reload-clj") (reload-clj req))
 ...)

(defn start-jetty []
 (let [j (run-jetty app {:port (http-port) :join? false :max-threads 16})]
   (dosync (ref-set *jetty* j))
   j))

(defn reload-clj [req]
 (future
    (log/info "Reloading clojure code...")
    (require '(whrusrv admin main utils wdb) :reload-all)
    (.stop @*jetty*)
    (start-jetty)
    (log/info "Clojure reload success!"))
 {:status 200
  :headers {"Content-Type" "text/plain"}
  :body "Reloading..."})

(defn -main [& args]
 (start-jetty))

Source: (StackOverflow)

Serving app and api routes with different middleware using Ring and Compojure

I have a ring+compojure application and I want to apply different middleware depending on whether the route is part of the web application or part of the api (which is json based).

I found some answers to this question on stack overflow and other forums, but these answers seem more complicated than the solution I've been using. I wanted to know if there are drawbacks with how I'm doing it and what I may be missing in my solution. A very simplified version of what I'm doing is

  (defroutes app-routes
    (GET "/" [req] dump-req)
    (route/not-found "Not Found"))

(defroutes api-routes
  (GET "/api" [req] dump-req))

(def app
  (routes (-> api-routes
              (wrap-defaults api-defaults))
          (-> app-routes
              (wrap-defaults site-defaults))))

Note that there is more middleware than I have shown here.

The only 'restriction' I've encountered is that as the app-routes has the not-found route, it needs to come last or it will be triggered before finding the api routes.

This seems simpler and more flexible than some of the other solutions I've found, which appear to either use additional conditional middleware, such as ring.middleware.conditional or what seems to me as more complex routing definitions where there is an additional defroutes layer and the need to define defroutes with ANY "*" etc.

I suspect there is something subtle I'm missing here and while my approach seems to work, it will cause unexpected behaviour or results in some situations etc.


Source: (StackOverflow)

ring-json's wrap-json-response middleware and compojure returns text/plain?

I'm trying to use ring-json's wrap-json-response middleware within my compojure app. I have a simple GET handler that returns a map, like {:foo 1}, and when I hit the URL, ring responds with text/plain and an empty response body. I can't seem to get it to respond with the JSON version of the map.

Here's my handler code:

(ns localshop.handler
  (:use compojure.core)
  (:require [localshop.routes.api.items :as routes-api-items]
            [ring.middleware.json :as middleware]
            [compojure.handler :as handler]
            [compojure.route :as route]))

;; map the route handlers
(defroutes app-routes
  (context "/api/item" [] routes-api-items/routes))

;; define the ring application
(def app
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-params)
      (middleware/wrap-json-response)))

The route handler function literally just returns a map, so the code for that is simple enough that I think I could leave out. If returning a map from a compojure route handler is the problem then perhaps thats it?

Thanks


Source: (StackOverflow)

idiomatic way to catch exceptions in ring apps

What is the idiomatic way to handle exceptions in ring apps. I would like to capture the exception and return a 500 page. How do I do that ?

I am using moustache for the code below, however it doesnt work -

(def my-app (try
              (app
               (wrap-logger true)
               wrap-keyword-params
               wrap-params
               wrap-file-info
               (wrap-file "resources/public/")
               [""]  (index-route @prev-h nil)
               ["getContent"] (fetch-url)
               ["about"] "We are freaking cool man !!"
               [&] (-> "Nothing was found" response (status 404) constantly))
              (catch Exception e
                (app
                 [&] (-> "This is an error" response (status 500) constantly)))

Source: (StackOverflow)