clojure,pedestal , How does one configure sibling Pedestal routes so that all are accessible when using :constraints?

How does one configure sibling Pedestal routes so that all are accessible when using :constraints?


Tag: clojure,pedestal

I am creating a toy Pedestal service intended to have the following resources:

The constraint for the last route is defined with the following snippet:

^:constraints {:iso-date #"\d{4}-\d{2}-\d{2}"}

Whenever the route containing this constraint is present in the route table I am unable to GET its sibling route /movies/today; instead I am getting a "Not Found" response instead. When the constraint-having route is removed, however, a GET of /movies/today succeeds.

The Pedestal routes I have defined using terse format look like so:

(defroutes routes
  [[["/" {:get root-page}
     ["/movies" ^:interceptors [fetch-movies]
      {:get movies-page}
      ["/today" {:get movies-for-today-page}]
      ["/:iso-date" ^:constraints {:iso-date #"\d{4}-\d{2}-\d{2}"}
       {:get movies-for-date-page}]]]]])

Have I constructed this route table correctly in order to achieve the routing behaviour that I want?

NB: Printing the compiled routes gives me the result that I would expect in that all of the routes are present the generated :path-re regexes match as expected at the REPL:

({:path-parts [""],
  :path-params [],
  [{:name :foobar.service/root-page,
    #object[io.pedestal.interceptor.helpers$before$fn__7359 0x14501070 "[email protected]"],
    :leave nil,
    :error nil}],
  :path "/",
  :method :get,
  :path-re #"/\Q\E",
  :route-name :foobar.service/root-page}
 {:path-parts ["" "movies"],
  :path-params [],
  [{:name :foobar.service/fetch-movies,
    #object[io.pedestal.interceptor.helpers$on_request$fn__7401 0x2aa85cc4 "[email protected]"],
    :leave nil,
    :error nil}
   {:name :foobar.service/movies-page,
    #object[io.pedestal.interceptor.helpers$before$fn__7359 0x30ffc3c0 "[email protected]"],
    :leave nil,
    :error nil}],
  :path "/movies",
  :method :get,
  :path-re #"/\Qmovies\E",
  :route-name :foobar.service/movies-page}
 {:path-parts ["" "movies" "today"],
  :path-params [],
  [{:name :foobar.service/fetch-movies,
    #object[io.pedestal.interceptor.helpers$on_request$fn__7401 0x2aa85cc4 "[email protected]"],
    :leave nil,
    :error nil}
   {:name :foobar.service/movies-for-today-page,
    #object[io.pedestal.interceptor.helpers$before$fn__7359 0x3726fc3b "[email protected]"],
    :leave nil,
    :error nil}],
  :path "/movies/today",
  :method :get,
  :path-re #"/\Qmovies\E/\Qtoday\E",
  :route-name :foobar.service/movies-for-today-page}
 {:path-parts ["" "movies" :iso-date],
  :path-params [:iso-date],
  [{:name :foobar.service/fetch-movies,
    #object[io.pedestal.interceptor.helpers$on_request$fn__7401 0x2aa85cc4 "[email protected]"],
    :leave nil,
    :error nil}
   {:name :foobar.service/movies-for-date-page,
    #object[io.pedestal.interceptor.helpers$before$fn__7359 0x93fb20b "[email protected]"],
    :leave nil,
    :error nil}],
  :path "/movies/:iso-date",
  :path-constraints {:iso-date "(\\d{4}-\\d{2}-\\d{2})"},
  :query-constraints {},
  :method :get,
  :path-re #"/\Qmovies\E/(\d{4}-\d{2}-\d{2})",
  :route-name :foobar.service/movies-for-date-page})


I solved this problem in pedestal version 0.4.1-SNAPSHOT.

(io.pedestal.http.route/router my-routes :linear-search)

Use :linear-search, instead of :prefix-tree.


How to specify max memory for clojure heroku app?

Running a clojure app on Heroku, I've specified this in my leiningen profiles.clj :jvm-opts ^:replace ["-Xms128m" "-Xmx350m" "-Xss512k" "-XX:MaxMetaspaceSize=150m"] And I'm running my worker with lein trampoline run But, I get these errors currently: 2015-06-20T14:38:14.652680+00:00 heroku[worker.1]: Error R14 (Memory quota exceeded) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Process running mem=552M(107.8%) 2015-06-20T14:38:34.779145+00:00 heroku[worker.1]: Error R14...

ImageIO import not working Clojure

I'm a bit of a Clojure novice, but I don't understand what's wrong about my code. The code bellow to my knowledge should set imgto a new BufferedImage object. (import javax.imageio.ImageIO) (import (def img (ImageIO/read (File. "C:\\input.png"))) However, when I execute lein run I get this exception: Exception in...

Querying the number of elements in a buffered core.async/chan

Having a buffered chan, say (def c (clojure.core.async/chan 100)) is it possible to query how many elements are currently inside the chan?...

Why such implementation of partial in clojure.core

I stumbled across implementation of partial function in cojure.core. It looks like this: (defn partial "Takes a function f and fewer than the normal arguments to f, and returns a fn that takes a variable number of additional args. When called, the returned function calls f with args + additional...

Group vectors with same first element into lists of vectors

I have ([AA moo foo boo][AA soo doo foo][BB woo roo too][BB koo ooo yoo]) I need to group it so I get lists of vectors with the same first element: ([AA moo foo boo][AA soo doo foo])([BB woo roo too][BB koo ooo yoo]) Is there a grouping function? Thanks...

Build macro result with loops

I'm building a macro that should be called like this: (myMacro MyController something otherthing (defn onFoo [this event] (println "ok")) (defn onBar [this event] (println "ok")) ) After the first three parameters I want to be able to pass a few functions that should be used to build the function...

Generator pattern code can't return value

I want to create a generator to do, 1 2 3 4. (defn getNums [] (loop [i 4 r []] (when (<= i 0) r ;<--- point A (recur (dec i) (conj r i))))) (getNums) ;Eval to nil. Nothing get return, why ? Would the code in point A return...

Clarifying Clojure “Use as” semantics

The effect of (use '[clojure.string :as str]) seems to be loading everything from clojure.string into the current namespace without namespace qualification. The effect of (use '[clojure.string :as str :only (join)]) seems to be loading only join into the current namespace, making the rest of the clojure.string namespace accessible with the...

Clojure - apply to all but nth element

I have a vector that looks like: [ "1" "2" "3" "4" ] I wish to write a function returns the vector to: [ 1 "2" 3 4 ] ; Note that the second element is still a string Note that nothing is changed, an entirely new vector is returned....

Converting vector to indexed map in Clojure?

Let's say I have the following vector of maps: [{:name "Jack" :age 5} {:name "Joe" :age 15} {:name "Mare" :age 34} {:name "William" :age 64} {:name "Adolf" :age 34}] I want to convert this to an indexed map, like: {1 {:name "Jack" :age 5} 2 {:name "Joe" :age 15} 3...

Sequentially calling a function with elements from a vector

Suppose I have a function f that accepts two arguments x & y. I also have a vector X composed of elements x1, x2, ... xn. How can I write a function g, where g(X, y) calls f(xi, y) for all x? Further specification: I would like g to return...

Immutant2 server logs showing fishy error message

I got this error message a couple of times 21:36:01,172 ERROR [io.undertow.request] (default task-18) Undertow request failed HttpServerExchange{ CONNECT}: java.lang.IllegalArgumentException: UT000068: Servlet path match failed at io.undertow.servlet.handlers.ServletPathMatchesData.getServletHandlerByPath( at io.undertow.servlet.handlers.ServletPathMatches.getServletHandlerByPath( at...

Clojure avoid repetition on tests

In my tests I need repeat this a block of tests for each function. In this case I'm testing bad-request function, the things that need change between each test is the bad-request call, code, and error. (deftest t-bad-request ... (testing "with data" (equal (merge error code message DATA) (bad-request MESSAGE...

How can I use single or double quote in Clojure Macro?

I am making a macro which uses single quotes. However, whenever I parse the macro the single quote text like: 'java' :is expanded to: (quote java') Does anyone know a way around this so that it doesn't expand to the quoted form? Update I have a kind of working workaround...

Datomic and HornetQException “unable to validate user”

I'm trying to connect to Datomic "dev" running on a separate host, but get the following error: "Error communicating with HOST (some-IP-address) on PORT (some-port-number) ...." Then further down the stack trace: Caused by: HornetQException[errorType=SECURITY_EXCEPTION ... Unable to validate user: (some-string) This is with "Seattle" sample schema that comes with...

Leiningen REPL not autoloading project.core namespace [duplicate]

This question already has an answer here: how to load ns by default when starting repl 2 answers I'm new to Clojure so this could very well be an easy question. I'm having an issue with the REPL while using Leiningen. Previously, I had created an app project while...

Brand new Luminus app giving Error: Could not find or load main class clojure.main

I just created a Luminus app by running: lein new luminus foobar and when I try to run it with foreman like this: foreman start the way the docs describe, I get this error: Error: Could not find or load main class clojure.main which is also the same error I...

in clojure, function argument type mismatch

clojure, function argument is vector, but it takes a map without problem. (defn flower-colors [colors] (str "The flowers are " (:flower1 colors) " and " (:flower2 colors))) (flower-colors {:flower1 "red" :flower2 "blue"}) ;; -> "The flowers are red and blue" Function flower-colors suppose to take vector type argument, but with...

How to add keys to a map / create keys in current map clojure

I have the following map from a get request :form-params {"qu" ["2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4" "2015 Q2" "2015 Q3" "2015 Q4"], "sh" ["2580" "2580" "2580" "2983" "2983" "2983" "53" "53" "53" "4558" "4558" "4558"], "prin" ["191"...

Simple runscript example with jclouds and clojure (or even just jclouds)

I have this clojure code (let [group-name "my-test-group" compute (compute-service provider user password) node (create-node compute group-name) node-id (.getId node)] (.runScriptOnNode compute node-id ??) (destroy-node compute node-id)) and I would like to run ls on my instance just as an example. What do I put in the ?? to make...

clojure - take-while to include last item when predicate is false

I have the following function that uses take-while (defn process [[cash amount wrappers]] (let [bought (int (Math/floor (/ cash amount))) free (->> (iterate (partial unwrapper wrappers) bought) (take-while (partial (fn [w a] (prn (str "a = " a)) (>= a w) ) wrappers)))] The problem I have is that I...

Why does ^metadata 'symbol not work?

The documentation on metadata claims that ^{:hi 10} 'x is equivalent to (with-meta 'x {:hi 10}), but I can't see that. Evaluating the following on a repl, (binding [*print-meta* true] (prn ^{:hi 10} 'x) (prn (with-meta 'x {:hi 10}))) prints the following, which shows that the first case doesn't get...

How to require dependencies in Clojure?

I have two questions regarding dependencies in Clojure project. Is there something like :dev-dependencies or :test-dependencies so that I don't have to download them all on lein run? So until I run my tests I don't need to have these extra libraries. Can I load dependencies in one file and...

ePassport Problems reagrding MAC creation in ICAO 9303 “worked examples” in Java/Clojure

i work on a application where I need to read Data from epassports. I'm working through the "worked examples" in ICAO Doc 9303 Part 3 Volume 2 (Third Edition). There is a section in the worked examples, where they put together the MUTAUAL_AUTHENTICATE apdu. It involves calculating the MAC of...

Loop in clojure with or condition

I'm trying to write a function in clojure that calls a condition for each value in a vector; the function should return the OR of the result of the condition applied to each value. Eg I have a vector [1 2 3 4] and a condition (>= x 3) where...

Apply a sequence of functions to data

I wish apply a sequence of functions to a data, like pipe: I know it has ->>and ->, also I have difficulty in defining the internal functions (defn create ([code error] {:statusCode code :error error}) ([code error & [message data]] (create code error) - I want pipe it result...

What does clojure 'val' return this value?

I'm just starting to learn clojure and have been reading some simple examples and then doing my best to rtfm for concepts. However I'm a bit confused by what val is doing in the example below. This has been taken from the Clojure doc examples for val. (first {:one :two})...

clojure and ctags, catching def* forms

So I found the following snippet from a Gist a while back: --langdef=Clojure --langmap=Clojure:.clj --langmap=Clojure:+.cljx --langmap=Clojure:+.cljs --regex-clojure=/\([ \t]*create-ns[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/n,namespace/ --regex-clojure=/\([ \t]*def[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/d,definition/ --regex-clojure=/\([ \t]*defn-?[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/f,function/ --regex-clojure=/\([ \t]*defmacro[ \t]+([-[:alnum:]*+!_:\/.?]+)/\1/m,macro/ --regex-clojure=/\([ \t]*definline[...

Mutable tree to persistent tree

Learning Clojure (and Functional Programming) I have stumbled upon the problem of converting a mutable n-ary tree represented as nested java.util.ArrayLists into a persistent tree. Using non-functional programming you would normally create the tree from the root to the leaves. This does not seem to be possible using persistent data...

Clojure loop receiving IllegalArgumentException Key must be integer clojure.lang.APersistentVector.invoke

I'm stuck trying to get a simple loop in Clojure to work and I don't know how to proceed to get rid of the exception. I'm trying to write an arrange function to exchange items in a vector. Here is the code. (defn exchange [v i] (let [[src dst] i]...

clojure performance on badly performing code

I have completed this problem on hackerrank and my solution passes most test cases but it is not fast enough for 4 out of the 11 test cases. My solution looks like this: (ns scratch.core (require [clojure.string :as str :only (split-lines join split)])) (defn ascii [char] (int (.charAt (str char)...

Clojure throws an exception when I don't expect it to

I have this code to get data from sumo logic and other services. core.clj has this, which parses the arguments and routes it to the right function in route.clj (def cli-options [ ["-a" "--app APPNAME" "set app. app can be: sumologic or jira"] ["-?" "--help"] ]) (defn -main [& args]...

How can I create a global object, and attach a string and a function to that object, in ClojureScript?

How can I create a global object, attached to the window, and attach a string and a function to that object, in ClojureScript? For example, an myobject that looks like: {"foo": function () {..}, "bar": "somestring"} => function () { .. } => "somestring"...

What is clojure.core equivalent of lodash _.pluck

Lodash _.pluck does this var users = [ { 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 } ]; _.pluck(users, 'user'); // → ['barney', 'fred'] Good thing about it is it can also go deep like this: var users = [ { 'user': {name: 'barney'}, 'age': 36 },...

Clojure: wrap-ssl-redirect on heroku?

I've just tried add this wrapper (-> routes (wrap-ssl-redirect)) for auto redirecting http to https, but when I deploy to heroku, the https:// doesn't get green in my browser, and the website doesn't load. Isn't the default heroku port 443, which should also be the default from wrap-ssl-redirectfunction? What is...

AngularJS $http GET method to backend server: Request Method:OPTIONS 405

$http GET request to a clojure backend, to get a list of services. I get is an OPTIONS request (???), which gets a 405 response... <code> var config = {headers: { 'Authorization': 'Bearer d2VudHdvYW5nZV9tZQ', "X-Testing" : "testing" } }; $http.get(SERVER.MESSAGE_SERVICES, config) .success(function(successCallback) { $ = successCallback; }) .error(function(errorCallback) { console.log(errorCallback.toString);...

Clojure interop with Java: how to call a class?

I have a Java app that has a class at this address, inside a standard Maven layout: src/main/java/com/ollio/nlp/ The class and method that I want looks like this: package com.ollio.nlp; public class Transformer { public String transform(String JSONInput) { I store the jar artifact locally in my Clojure app at...

Clojure: difference between applying directly or by way of a function

The aim is to play with a slight modification of the Caesar cipher. First a function to move a character: (defn move-char [c shift idx encode-or-decode] (let [ch (int c) val (mod (* encode-or-decode (+ shift idx)) 26)] (cond (and (>= ch (int \A)) (<= ch (int \Z))) (char (+...

Accessing argument's metadata in Clojure macro

Is there a way to retrieve the metadata of the arguments inside a clojure macro without using eval? The only thing I could come up with so far is this: (def ^{:a :b} my-var) (defmacro my-macro [s] (prn (eval `(meta (var ~s))))) (my-macro my-var) ;; Prints {:a :b, :name my-var,...

Why is my streamparse topology definition complaining about a wrong number of arguments to thrift$mk-topology?

I'm trying to get a very simple streamparse (i.e. Apache Storm) spout working, but I'm getting the error below when running sparse run -t 120: Caught exception: Wrong number of args (1) passed to: thrift$mk-topology clojure.lang.ArityException: Wrong number of args (1) passed to: thrift$mk-topology at clojure.lang.AFn.throwArity ( clojure.lang.AFn.invoke ( clojure.lang.AFn.applyToHelper...

clojure quoting inside let

Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

How to perform synchronous parallel functions in Clojure?

I have an application which has an initial flow that can be done in parallel: Fetch two JSON documents (I use clj-http for that) Parse these documents (extract only required data) Join the results Dump them into a one file So there's something like that: some-entry-point /\ / \ /...

deploy compojure app that is also a CLI app

I have a Clojure app that I can use both from the command-line, and as a Compojure app. I did that by putting a ring handler and a main function ( in my leiningen project.clj. {... :main my-app.core :ring {:handler my-app.handler/handler }} The handler is defined (defroutes handler ...). Now...

Clojure: Idiomatic/clean way to avoid NPE in a monad-like way

I'm a little chagrinned that some of the built-in Clojure functions have what seems to me to be an inconsistent behavior. I'm trying to do this: (let [kwns (namespace (keyword v))] ...) in a context where v might be nil. The keyword function works as I'd expect (returns nil), but...

Does the Zookeeper Watches system have a bug, or is this a limitation of the CAP theorem?

The Zookeeper Watches documentation states: "A client will see a watch event for a znode it is watching before seeing the new data that corresponds to that znode." Furthermore, "Because watches are one time triggers and there is latency between getting the event and sending a new request to get...

Is there a formal way of proposing/discussing changes to Clojure?

Is there a formal way of proposing/discussing changes to Clojure?

More readable messages with :pre and :post?

In clojure I am using :pre like this user=> (defn cannot-take-empty [x] {:pre [((complement empty?) x)]} 1) #'user/cannot-take-empty user=> (cannot-take-empty #{}) AssertionError Assert failed: ((complement empty?) x) user/cannot-take-empty (NO_SOURCE_FILE:186) That's great, but it doesn't explain the business reason why it doesn't make sense to pass in an empty collection. (Or...

Clojure invokeLater null pointer

This code: (import 'javax.swing.SwingUtilities) (SwingUtilities/invokeLater (print "hi")) Causes this error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at java.awt.event.InvocationEvent.dispatch( ... I don't know if this is a problem, since the code itself actually works (printing to the REPL) despite the error. However, modifying swing components does not seem to work properly: a...

Append to clojure vector from within loop

I have: (defn keep? (def sum []) (loop [i 0] (when (< i 10) (conj sum 10) (recur (inc i)))) sum ) This just gives me and empty vector even though I am conj-ing 10 onto sum. Is this because it is not in-scope within the Loop? How would I...

Questions about Vars Clojure

I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable? I can change the value of the var after, so is it really that different...