Permalink
Browse files

Use context classloader for fulfilling resource responses

  • Loading branch information...
1 parent 00cae9b commit 6cb0ac59198bcda35822b57beec7c15f2d46456c Tero Parviainen committed with weavejester Nov 21, 2010
Showing with 26 additions and 3 deletions.
  1. +3 −2 ring-core/src/ring/util/response.clj
  2. +23 −1 ring-core/test/ring/util/response_test.clj
View
5 ring-core/src/ring/util/response.clj
@@ -61,8 +61,9 @@
:root - take the resource relative to this root"
[path & [opts]]
(let [path (str (:root opts "") "/" path)
- path (.replace path "//" "/")]
- (if-let [resource (.getResourceAsStream System path)]
+ path (.replace path "//" "/")
+ path (.replaceAll path "^/" "")]
+ (if-let [resource (.. Thread currentThread getContextClassLoader (getResourceAsStream path))]
(response resource))))
(defn status
View
24 ring-core/test/ring/util/response_test.clj
@@ -2,6 +2,20 @@
(:use clojure.test
ring.util.response))
+(defmacro with-classloader
+ "Temporarily replaces the current context classloader with one that
+ includes everything in dir"
+ [[dir] & forms]
+ `(let [current-thread# (Thread/currentThread)
+ original-loader# (.getContextClassLoader current-thread#)
+ new-loader# (java.net.URLClassLoader. (into-array [(.toURL ~dir)])
+ original-loader#)]
+ (try
+ (.setContextClassLoader current-thread# new-loader#)
+ ~@forms
+ (finally
+ (.setContextClassLoader current-thread# original-loader#)))))
+
(deftest test-redirect
(is (= {:status 302 :headers {"Location" "http://google.com"} :body ""}
(redirect "http://google.com"))))
@@ -28,6 +42,14 @@
(let [resp (resource-response "response_test.clj" {:root "/ring/util"})]
(is (.startsWith (slurp (resp :body))
"(ns ring.util.response-test"))))
-
+
+(deftest test-resource-with-child-classloader
+ (let [resource (java.io.File/createTempFile "response_test" nil)]
+ (org.apache.commons.io.FileUtils/writeStringToFile resource "just testing")
+ (with-classloader [(.getParentFile resource)]
+ (let [resp (resource-response (.getName resource))]
+ (is (= (slurp (resp :body))
+ "just testing"))))))
+
(deftest test-missing-resource
(is (nil? (resource-response "/missing/resource.clj"))))

0 comments on commit 6cb0ac5

Please sign in to comment.