<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Tech behind Tech</title>
	<atom:link href="http://techbehindtech.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://techbehindtech.com</link>
	<description>Raw information. No finesse :)</description>
	<lastBuildDate>Sat, 21 Jan 2012 00:12:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='techbehindtech.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/ea259bd3a901b0e5c68149ed7392c564?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Tech behind Tech</title>
		<link>http://techbehindtech.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://techbehindtech.com/osd.xml" title="Tech behind Tech" />
	<atom:link rel='hub' href='http://techbehindtech.com/?pushpress=hub'/>
		<item>
		<title>Introduction to Clojure Web Development using Ring, Compojure and Sandbar</title>
		<link>http://techbehindtech.com/2011/01/19/introduction-to-clojure-web-development-using-ring-compojure-and-sandbar/</link>
		<comments>http://techbehindtech.com/2011/01/19/introduction-to-clojure-web-development-using-ring-compojure-and-sandbar/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 08:36:50 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[ring]]></category>
		<category><![CDATA[sandbar]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=224</guid>
		<description><![CDATA[I gave an introduction to clojure web development presentation to bay area clojure user group. As my slides do not have much information, I am writing this blog so everyone can follow and get started with a sample clojure web application using compojure. Introduction to Clojure web developmenthttp://static.slidesharecdn.com/swf/ssplayer2.swf?doc=compojure-110119172228-phpapp01&#38;stripped_title=introduction-to-clojure-web-development&#38;userName=sivajag View more presentations from sivajag. Setting Up: [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=224&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I gave an introduction to clojure web development presentation to bay area clojure user group. As my slides do not have much information, I am writing this blog so everyone can follow and get started with a sample clojure web application using compojure.</p>
<div id="__ss_6631730" style="width:425px;"><strong><a title="Introduction to Clojure web development" href="http://www.slideshare.net/sivajag/introduction-to-clojure-web-development">Introduction to Clojure web development</a></strong><a href="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=compojure-110119172228-phpapp01&amp;stripped_title=introduction-to-clojure-web-development&amp;userName=sivajag">http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=compojure-110119172228-phpapp01&amp;stripped_title=introduction-to-clojure-web-development&amp;userName=sivajag</a></p>
<div style="padding:5px 0 12px;">View more <a href="http://www.slideshare.net/">presentations</a> from <a href="http://www.slideshare.net/sivajag">sivajag</a>.</div>
</div>
<p>Setting Up:</p>
<p><pre class="brush: plain;"> lein new address_book </pre></p>
<p>Add Compojure to Project:</p>
<p>Edit project.clj</p>
<p><pre class="brush: plain;">
(defproject address_book &quot;1.0.0-SNAPSHOT&quot;
  :description &quot;Runnering log&quot;
  :dependencies [[org.clojure/clojure &quot;1.2.0&quot;]
                 [org.clojure/clojure-contrib &quot;1.2.0&quot;]
                 [ring/ring-jetty-adapter &quot;0.2.5&quot;]
                 [compojure &quot;0.4.1&quot;]
                 [hiccup &quot;0.2.6&quot;]
                 [sandbar &quot;0.3.0-SNAPSHOT&quot;]
                 [clj-json &quot;0.3.1&quot;]]
  :dev-dependencies [[swank-clojure &quot;1.3.0-SNAPSHOT&quot;]])
</pre></p>
<p>Run</p>
<p><pre class="brush: plain;">
lein deps
</pre></p>
<p>Test whether our setup works:</p>
<p>Edit src/address_book/core.clj</p>
<p><pre class="brush: plain;">
(ns address-book.core
  (:use [compojure.core]
        [ring.adapter.jetty])
  (:require [compojure.route :as route]))

(defroutes rts
  (GET &quot;/&quot; [] &quot;Address Book!!&quot;)
  (route/not-found &quot;Page not found&quot;))

(def application-routes
     rts)

(defn start []
  (run-jetty application-routes {:port 8080
                                 :join? false}))

</pre></p>
<p>Goto http://localhost:8080 and you should see &#8220;Address Book&#8221;</p>
<p>Interactive Development:</p>
<p>In core.clj, change start function to</p>
<p><pre class="brush: plain;">
(defn start []
  (run-jetty application-routes {:port 8080
                                 :join? false}))
</pre></p>
<p>Add Static Folders:</p>
<p><pre class="brush: plain;">
mkdir -p public/{css,js}
</pre></p>
<p>Create public/index.html</p>
<p><pre class="brush: plain;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;	&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;'
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;&gt;	
 &lt;head&gt;		
   &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;		
   &lt;title&gt;My Address book&lt;/title&gt;		
   &lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;&gt;&lt;/script&gt;	
 &lt;/head&gt;
 &lt;body id=&quot;main&quot;&gt;    
    &lt;p&gt;      My Address Book    &lt;/p&gt;  
 &lt;body&gt;
&lt;/html&gt;

</pre></p>
<p>Try to access http://localhost:8080/index.html. This will fail, as we never told compojure how to handle static files.</p>
<p>Edit core.clj and replace rts</p>
<p><pre class="brush: plain;">
(defroutes rts
  (GET &quot;/&quot; [] &quot;Address Book!!&quot;)
   (route/files &quot;/&quot;)
  (route/not-found &quot;Page not found&quot;))
</pre></p>
<p>Now when you access http://localhost:8080/index.html, it should display correctly.</p>
<p>Ring:</p>
<p>Three components</p>
<p>1) Handlers:<br />
Handlers are main functions that  process a request. We define handlers using defroutes macro.</p>
<p>2) Middleware:<br />
Middleware are functions that could be chained together to process a request. Middleware functions can take any number of arguments, but the spec stats that first argument should be an handler and function should return an handler. An example for middleware is logging all requests that comes to your webserver.  Ring and compojure comes with some standard middleware. We will see in next part how to create our own middleware.</p>
<p>3) Adapters:<br />
Adapters are functions could adapt our handler to a web server. We are using jetty adapter to tie our handler to jetty server.</p>
<p>Lets create our Middleware:</p>
<p>Create src/address_book/middleware.clj</p>
<p><pre class="brush: plain;">
(ns address-book.middleware)

(defn- log [msg &amp; vals]
  (let [line (apply format msg vals)]
    (locking System/out (println line))))

(defn wrap-request-logging [handler]
  (fn [{:keys [request-method uri] :as req}]
    (let [resp (handler req)]
      (log &quot;Processing %s %s&quot; request-method uri)
      resp)))

</pre></p>
<p>Edit core.clj ns form</p>
<p><pre class="brush: plain;">
(ns address-book.core
  (:use [compojure.core]
        [ring.adapter.jetty])
  (:require [compojure.route :as route]
			[address-book.middleware :as mdw]))
</pre></p>
<p>Edit core.clj application-routes def</p>
<p><pre class="brush: plain;">
(def application-routes
     (-&gt; rts
	     mdw/wrap-request-logging))
</pre></p>
<p>Now when you access your server, you should see request log messages.</p>
<p>Main sourcecode:</p>
<p>Create address_book/address.clj</p>
<p><pre class="brush: plain;">
(ns address-book.address
  (:import [java.util Date])
  (:refer-clojure :exclude (find create)))

(def STORE (atom {:1 {:id :1 :name &quot;Siva Jagadeesan&quot; :street1 &quot;88 7th&quot; :street2 &quot;#203&quot; :city &quot;Cupertino&quot; :country &quot;USA&quot; :zipsourcecode 98802}}))

(defn to-keyword [num]
  (if-not (keyword? num)
    (keyword (str num))
    num))

(defn random-number []
  (to-keyword (.getTime (Date.))))

(defn create [attrs]
  (let [id (random-number)
        new-attrs (merge {:id id} attrs)]
    (swap! STORE merge {id new-attrs})
    new-attrs))

(defn find-all []
  (vals @STORE))

(defn find [id]
  ((to-keyword id) @STORE))

(defn update [id attrs]
  (let [updated-attrs (merge (find id) attrs)]
    (swap! STORE assoc id updated-attrs)
    updated-attrs))

(defn delete [id]
  (let [old-attrs (find id)]
    (swap! STORE dissoc id)
    old-attrs))

</pre></p>
<p>Edit core.clj ns form</p>
<p><pre class="brush: plain;">
(ns address-book.core
  (:use [compojure.core]
        [ring.adapter.jetty])
  (:require [compojure.route :as route]
			[address-book.middleware :as mdw]
            [address-book.address :as address]
            [clj-json.core :as json]))
</pre></p>
<p>Add this function to core.clj</p>
<p><pre class="brush: plain;">
(defn json-response [data &amp; [status]]
  {:status (or status 200)
   :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
   :body (json/generate-string data)})
</pre></p>
<p>Add these routes to core.clj</p>
<p><pre class="brush: plain;">
(GET &quot;/addresses&quot; [] (json-response (address/find-all)))
(GET &quot;/addresses/:id&quot; [id] (json-response (address/find id)))
(POST &quot;/addresses&quot; {params :params}  (json-response (address/create params)))
</pre></p>
<p>Replace your public folder with <a href="https://files.me.com/sivajag/sh35fq">https://files.me.com/sivajag/sh35fq</a></p>
<p>This folder has needed css and js files.</p>
<p>Now go to http://localhost:8080/index.html and you should see a address book webapp. You can add and view addresses.</p>
<p>Authentication:</p>
<p>Create src/address_book/auth.clj</p>
<p><pre class="brush: plain;">
(ns address-book.auth
  (:use [sandbar.form-authentication ]
        [sandbar.validation]))

(defrecord AuthAdapter []
  FormAuthAdapter
  (load-user [this username password]
             (cond (= username &quot;example&quot;)
                   {:username &quot;example&quot; :password &quot;password&quot; :roles #{:user}}))
  (validate-password [this]
                     (fn [m]
                       (if (= (:password m) &quot;password&quot;)
                         m
                         (add-validation-error m &quot;Unable to authenticate user.&quot;)))))

(defn form-authentication-adapter []
  (merge
   (AuthAdapter.)
   {:username &quot;Username&quot;
    :password &quot;Password&quot;
    :username-validation-error &quot;You must supply a valid username.&quot;
    :password-validation-error &quot;You must supply a password.&quot;
    :logout-page &quot;/&quot;}))
</pre></p>
<p>Edit core.clj ns form</p>
<p><pre class="brush: plain;">

(ns address-book.core
  (:use [compojure.core]
        [ring.adapter.jetty]
        [sandbar.auth]
        [sandbar.form-authentication ]
        [sandbar.validation ])
  (:require [compojure.route :as route]
			[address-book.middleware :as mdw]
            [address-book.address :as address]
            [address-book.auth :as auth]
            [clj-json.core :as json]))

</pre></p>
<p>Add this def to core.clj</p>
<p><pre class="brush: plain;">
(def security-policy
  [#&quot;.*\.(css|js|png|jpg|gif|ico)$&quot; :any
   #&quot;/login.*&quot; :any
   #&quot;/logout.*&quot; :any
   #&quot;/permission-denied.*&quot; :any
   #&quot;/addresses&quot; :user
   #&quot;/index.html&quot; :user
   #&quot;/&quot; #{:user}])
</pre></p>
<p>Add this route to core.clj</p>
<p><pre class="brush: plain;">
 (form-authentication-routes (fn [_ c] (html c)) (auth/form-authentication-adapter))
</pre></p>
<p>Change application routes function in core.clj</p>
<p><pre class="brush: plain;">
(def application-routes
     (-&gt; rts
        (with-security security-policy form-authentication)  		 
        wrap-stateful-session
	mdw/wrap-request-logging))
</pre></p>
<p>Now when you access http://localhost:8080/index.html it will take you to login page. You can login using &#8220;example&#8221; and &#8220;password&#8221;.</p>
<p>That is it folks. A simple web app using clojure.</p>
<p>I am sure this blog could be improved a lot. Please leave comments I will update this blog with your feedback.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/ring/'>ring</a>, <a href='http://techbehindtech.com/tag/sandbar/'>sandbar</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/224/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/224/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/224/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=224&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2011/01/19/introduction-to-clojure-web-development-using-ring-compojure-and-sandbar/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Leiningen &#8211; Adding git submodule to Leiningen project</title>
		<link>http://techbehindtech.com/2010/12/11/leiningen-adding-git-submodule-to-leiningen-project/</link>
		<comments>http://techbehindtech.com/2010/12/11/leiningen-adding-git-submodule-to-leiningen-project/#comments</comments>
		<pubDate>Sat, 11 Dec 2010 21:39:51 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[Leiningen]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=221</guid>
		<description><![CDATA[With git, sometimes it easy to use git submodule for dependency management. In Leiningen, for some reason the only &#8220;advertised&#8221; way of dependency management is using maven. After some poking around, there is a way in Leiningen to use git submodules for dependency management. Are you ready? ( drumroll &#8230;) It is very simple actually [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=221&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>With git, sometimes it easy to use git submodule for dependency management. In Leiningen, for some reason the only &#8220;advertised&#8221; way of dependency management is using maven. After some poking around, there is a way in Leiningen to use git submodules for dependency management.</p>
<p>Are you ready? ( drumroll &#8230;)</p>
<p>It is very simple actually <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>You have to checkout your submodules to &#8220;checkouts&#8221; folder. Leiningen will automatically add your submodule&#8217;s src directory to your classpath.</p>
<p>That&#8217;s it folks <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/dependency/'>dependency</a>, <a href='http://techbehindtech.com/tag/git/'>git</a>, <a href='http://techbehindtech.com/tag/leiningen/'>Leiningen</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/221/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/221/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/221/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=221&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/12/11/leiningen-adding-git-submodule-to-leiningen-project/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Clojure &#8211; good coding guidelines</title>
		<link>http://techbehindtech.com/2010/12/09/clojure-good-coding-guidelines/</link>
		<comments>http://techbehindtech.com/2010/12/09/clojure-good-coding-guidelines/#comments</comments>
		<pubDate>Fri, 10 Dec 2010 07:04:22 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[guidelines]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=214</guid>
		<description><![CDATA[Naming : - only lower case letters separated by hyphens except types and protocols should be named in camelcase - predicates ends with ? - destructive functions ends with ! - variables that are meant for be re-binding should have earmuffs - use &#8220;_&#8221; for names that will be ignored by the code Code Structure [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=214&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Naming :</strong></p>
<p>- only lower case letters separated by hyphens except types and protocols should be named in camelcase<br />
- predicates ends with ?<br />
- destructive functions ends with !<br />
- variables that are meant for be re-binding should have earmuffs<br />
- use &#8220;_&#8221; for names that will be ignored by the code</p>
<p><strong>Code Structure :</strong></p>
<p>- when there is only &#8220;then&#8221; clause in a conditional statement use &#8220;when&#8221; instead of &#8220;if&#8221;<br />
- put all trailing parenthesis in one line<br />
- for dependency use &#8220;:only&#8221;<span style="font-family:monospace;"> </span>for &#8220;use&#8221; and &#8220;require&#8221;<br />
- use two spaces for indentation<br />
- destructure arg list only when you want to explain the structure of arg to caller otherwise destructure in first let binding</p>
<p><strong>Coding Style:</strong></p>
<p>- try to solve a problem by using function before trying with macro<br />
- be lazy when possible<br />
- use keywords as keys for map entries<br />
- use keyword-first syntax to access properties on objects<br />
- prefer sequence library functions instead of loop/recurr<br />
- only use anonymous functions for short function definitions that fit comfortably on a single line. Otherwise create a private, named function.<br />
- short functions</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/guidelines/'>guidelines</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/214/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/214/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/214/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=214&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/12/09/clojure-good-coding-guidelines/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Clojure defrecord deftype</title>
		<link>http://techbehindtech.com/2010/11/15/clojure-defrecord-deftype/</link>
		<comments>http://techbehindtech.com/2010/11/15/clojure-defrecord-deftype/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 18:58:01 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[protocols]]></category>
		<category><![CDATA[record]]></category>
		<category><![CDATA[structure]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=208</guid>
		<description><![CDATA[There are different ways to create a struct in clojure. 1) Using Clojure built in data structures keyword-access nested-access 2) Using defrecord keyword-access nested-access As you can see, accessing map and defrecord is very similar. defrecord provides implementation of a persistent map. 3) Using deftype PS: bad example ( I will explain why later ) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=208&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>There are different ways to create a struct in clojure.</p>
<p><strong>1) Using Clojure built in data structures</strong></p>
<p><pre class="brush: plain;">
user&gt; (def lotr {:title &quot;Book title&quot;
                 :author {
                          :first-name &quot;first&quot;
                          :last-name &quot;last&quot;}})
#'user/lotr
	</pre></p>
<p>keyword-access</p>
<p><pre class="brush: plain;">
user&gt; (:title lotr)
&quot;Book title&quot;
</pre></p>
<p>nested-access</p>
<p><pre class="brush: plain;">
user&gt; (-&gt; lotr :author :first-name)
&quot;first&quot;
</pre></p>
<p><strong>2) Using defrecord</strong></p>
<p><pre class="brush: plain;">
user&gt; (defrecord Book [title author])
user.Book
user&gt; (defrecord Person [first-name last-name])
user.Person
user&gt; (def lotr (Book. &quot;Book Title&quot;
                       (Person. &quot;first&quot; &quot;last&quot;)))
#'user/lotr
</pre></p>
<p>keyword-access</p>
<p><pre class="brush: plain;">
user&gt; (:title lotr)
&quot;Book title&quot;
</pre></p>
<p>nested-access</p>
<p><pre class="brush: plain;">
user&gt; (-&gt; lotr :author :first-name)
&quot;first&quot;
</pre></p>
<p>As you can see, accessing map and defrecord is very similar. defrecord provides implementation of a persistent map.</p>
<p><strong>3) Using deftype</strong></p>
<p><em>PS: bad example ( I will explain why later )</em></p>
<p><pre class="brush: plain;">
user&gt; (deftype Book [title author])
user.Book
user&gt; (deftype Person [first-name last-name])
user.Person
user&gt; (def lotr (Book. &quot;Book Title&quot;
                       (Person. &quot;first&quot; &quot;last&quot;)))
#'user/lotr
</pre></p>
<p>Unlike defrecord, deftype does not provide implementation of a persistent map. So when you try to keyword-access , it won&#8217;t work</p>
<p>keyword-access</p>
<p><pre class="brush: plain;">
user&gt; (:title lotr)
nil
</pre></p>
<p>It provides field access only</p>
<p><pre class="brush: plain;">
user&gt; (.title lotr)
&quot;Book Title&quot;
</pre></p>
<p>I mentioned the above example for deftype is a bad example. Let me explain why. In OO, we have two set of classes. One set that defines language constructs like String and other that defines domain like Book. As defrecord provides implementation of a persistent map, it is better to use defrecord for realizing domain.  Use deftype for realizing programming constructs.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/protocols/'>protocols</a>, <a href='http://techbehindtech.com/tag/record/'>record</a>, <a href='http://techbehindtech.com/tag/structure/'>structure</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/208/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/208/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/208/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=208&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/11/15/clojure-defrecord-deftype/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Testing Clojure Code &#8211; Awesome &#8220;are&#8221;</title>
		<link>http://techbehindtech.com/2010/10/19/testing-clojure-code-awesome-are/</link>
		<comments>http://techbehindtech.com/2010/10/19/testing-clojure-code-awesome-are/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 19:55:56 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[test-is]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=205</guid>
		<description><![CDATA[test-is a great library for testing clojure. Thanks to Philippe, I recently discover &#8220;are&#8221; in test-is. This is most underrated/underused macro in test-is library. Lets take an example, where I want to test a function given a date, it will return end of month. Without are, With are, The version without &#8220;are&#8221; has, so many [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=205&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>test-is a great library for testing clojure. Thanks to <a href="http://ph7spot.com/">Philippe</a>, I recently discover &#8220;are&#8221; in test-is. This is most underrated/underused macro in test-is library.</p>
<p>Lets take an example, where I want to test a function given a date, it will return end of month.</p>
<p>Without are,</p>
<p><pre class="brush: plain;">
(deftest test-end-of-month
        (is (= &quot;2010-01-31 23:59&quot; (end-of-month &quot;2010-01-03 01:12&quot;)))
        (is (= &quot;2010-01-31 23:59&quot; (end-of-month &quot;2010-01-03 21:59&quot;)))
        (is (= &quot;2010-02-28 23:59&quot; (end-of-month &quot;2011-02-03 13:01&quot;)))
        (is (= &quot;2016-02-29 23:59&quot; (end-of-month &quot;2016-02-03 03:01&quot;)))
        (is (= &quot;2011-04-30 23:59&quot; (end-of-month &quot;2011-04-03 00:02&quot;))))
</pre></p>
<p>With are,</p>
<p><pre class="brush: plain;">
(deftest test-end-of-month
        (are [expected ts] (= expected (end-of-month ts))

             &quot;2010-01-31 23:59&quot; &quot;2010-01-03 01:12&quot;
             &quot;2010-01-31 23:59&quot; &quot;2010-01-03 21:59&quot;
             &quot;2011-02-28 23:59&quot; &quot;2011-02-03 13:01&quot;
             &quot;2016-02-29 23:59&quot; &quot;2016-02-03 03:01&quot;
             &quot;2011-04-30 23:59&quot; &quot;2011-04-03 00:02&quot;))
</pre></p>
<p>The version without &#8220;are&#8221; has, so many duplications. It is difficult to read as it is cluttered. The version with &#8220;are&#8221; is easy to read, and it is so easy to add more test cases without much duplication.</p>
<p>Thanks <a href="http://ph7spot.com/">Philippe</a> for introducing me to wonders of &#8220;are&#8221;.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/test-is/'>test-is</a>, <a href='http://techbehindtech.com/tag/testing/'>testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/205/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/205/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/205/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=205&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/10/19/testing-clojure-code-awesome-are/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Calling java from Clojure</title>
		<link>http://techbehindtech.com/2010/10/11/calling-java-from-clojure/</link>
		<comments>http://techbehindtech.com/2010/10/11/calling-java-from-clojure/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 05:43:26 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[interopability]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=197</guid>
		<description><![CDATA[&#160; Importing Java Class In repl, when you want to import one Java class you can do When you want to import more Java classes from a same package you can do Creating Instances Calling Java instance methods Calling Java static methods Sugar sytax: Doto: You want to write a function that will return UTC [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=197&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&nbsp;</p>
<p><strong>Importing Java Class</strong></p>
<p>In repl, when you want to import one Java class you can do</p>
<p><pre class="brush: plain;">
(import 'java.util.Date)
</pre></p>
<p>When you want to import more Java classes from a same package you can do</p>
<p><pre class="brush: plain;">
(import [java.util Date HashMap])
</pre></p>
<p><pre class="brush: plain;">
(ns com.techbehindtech.java
        (:import [java.util Date HashMap]))
</pre></p>
<p><strong>Creating Instances</strong></p>
<p><pre class="brush: plain;">
(import 'java.util.Date)

(def today (new Date))

;; or

(def today (Date.))
</pre></p>
<p><strong>Calling Java instance methods</strong></p>
<p><pre class="brush: plain;">
user&gt; (import 'java.util.Date)
java.util.Date
user&gt; (let [today (Date.)]
        (.getTime today))
1286749020847
</pre></p>
<p><strong>Calling Java static methods</strong></p>
<p><pre class="brush: plain;">
user&gt; (System/currentTimeMillis)
1286847946813
</pre></p>
<p><strong>Sugar sytax:</strong></p>
<p><em><strong>Doto:</strong></em></p>
<p>You want to write a function that will return UTC Java Calendar object set at a specific time.</p>
<p><pre class="brush: plain;">
user&gt; (import [java.util Calendar TimeZone Date])
user&gt; (defn utc-time [d]
        (let [cal (Calendar/getInstance)]
              (.setTimeZone cal (TimeZone/getTimeZone &quot;UTC&quot;))
              (.setTime cal d)
          cal))

#'user/utc-time
</pre></p>
<p>The let block is ugly. We could use doto to make this code better.</p>
<p><pre class="brush: plain;">
user&gt; (import [java.util Calendar TimeZone Date])	
user&gt; (defn utc-time [d]        
         (doto (Calendar/getInstance)
              (.setTimeZone (TimeZone/getTimeZone &quot;UTC&quot;))
              (.setTime d)))

#'user/utc-time
	</pre></p>
<p><em><strong>Dot Dot:</strong></em></p>
<p>Sometimes in java you want to make calls in chain</p>
<p><em>Bad way</em></p>
<p><pre class="brush: plain;">
user&gt; (.length (.getProperty (System/getProperties) &quot;user.country&quot;))
2
	</pre></p>
<p><em>Better way</em></p>
<p><pre class="brush: plain;">
user&gt; (. (. (System/getProperties) getProperty &quot;user.country&quot;) length)
2
</pre></p>
<p><em>Even Better</em></p>
<p><pre class="brush: plain;">
user&gt; (..
       (System/getProperties)
       (getProperty &quot;user.country&quot;)
       (length))
2
</pre></p>
<p><strong>Avoiding Reflection</strong></p>
<p>By default jvm will be using reflection to identify type. Reflection is slow. But we can give type hints that way jvm does not have to use reflection. For example we can rewrite utc-time with type-hints like this</p>
<p><pre class="brush: plain;">
user&gt; (set! *warn-on-reflection* true)
true
user&gt; (defn str-length [s] (.length s))
Reflection warning, NO_SOURCE_FILE:1 - reference to field length can't be resolved.
#'user/str-length
user&gt; (defn str-length [#^String s] (.length s))
#'user/str-length
	</pre></p>
<p><strong>Implementing interfaces and extending classes</strong></p>
<p>Let us implement Java Runnable interface</p>
<p><pre class="brush: plain;">
user&gt; (proxy [Runnable] []
        (run []
             (println &quot;running ...&quot;)))
#&lt;Object$Runnable$36fc6471 user.proxy$java.lang.Object$Runnable$36fc6471@6dd33544&gt;
</pre></p>
<p>In clojure 1.2, you could use reify macro to implement. In fact it is better than using proxy.</p>
<p><pre class="brush: plain;">
user&gt; (reify Runnable
             (run [this]
                  (println &quot;running ...&quot;)))
#&lt;user$eval1664$reify__1665 user$eval1664$reify__1665@574f7121&gt;
</pre></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/interopability/'>interopability</a>, <a href='http://techbehindtech.com/tag/java/'>java</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/197/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/197/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/197/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=197&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/10/11/calling-java-from-clojure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Clojure Macros Simplified</title>
		<link>http://techbehindtech.com/2010/09/28/clojure-macros-simplified/</link>
		<comments>http://techbehindtech.com/2010/09/28/clojure-macros-simplified/#comments</comments>
		<pubDate>Wed, 29 Sep 2010 06:32:57 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[macros]]></category>

		<guid isPermaLink="false">http://techbehindtech.com/2010/09/28/clojure-macros-simplified/</guid>
		<description><![CDATA[One of the powerful features of clojure ( or any other LISP) is macros. Macros are so powerful that will allow you do things that you can never do in any other language. There is a classic example of implementing &#8220;unless&#8221; functionality using macros. I am not going to talk about why we need macros [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=189&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the powerful features of clojure ( or any other LISP) is macros. Macros are so powerful that will allow you do things that you can never do in any other language. There is a classic example of implementing &#8220;unless&#8221; functionality using macros. I am not going to talk about why we need macros and when to use them. There is so much literature out there discussing about Macros. Also checkout Clojure in Action book for in depth look on Macros. I have read both Joy of Clojure and Clojure in Action, when it comes to Macros I will recommend Clojure in Action. The idea behind this blog to simplify macros as much as possible.</p>
<p>As you know in Clojure code is data and data is code. Our code is a clojure List. So we can programmatically create a list and execute it.</p>
<p><pre class="brush: plain;">
user&gt; (def my-code '(println &quot;techbehindtech&quot;))
#'user/my-code
user&gt; my-code
(println &quot;techbehindtech&quot;)
user&gt; (eval my-code)
techbehindtech
</pre></p>
<p>In above example, we created a list my-code. This list could be created dynamically. And using eval function we could execute that list as a clojure code.</p>
<p>So to create code in clojure, all we have to do is create a clojure list. In clojure, before a code is evaluated we have hook to introduce our own code using Macros system.</p>
<p>In Macros we are basically creating a list of code similar to my-code. Lets create a simple macro that will allow us to write functions with some log message.</p>
<p><pre class="brush: plain;">
(defmacro def-logged-fn [fn-name args &amp; body]
        `(defn ~fn-name ~args
           (println &quot;Calling ...&quot;)
           ~@body))
</pre></p>
<p><pre class="brush: plain;">
user&gt; (def-logged-fn say[name]
        (println (str &quot;hello &quot; name)))
#'user/say
user&gt; (say &quot;siva&quot;)
Calling ...
hello siva
nil
</pre></p>
<p><strong>macroexpand and macroexpand-1:</strong></p>
<p>macroexpand and macroexpand-1 are useful functions to know about when using<br />
writing macros. These functions expand our macro forms.</p>
<p><pre class="brush: plain;">
user&gt; (macroexpand-1 '(def-logged-fn say[name]
        (println (str &quot;hello &quot; name))))

(clojure.core/defn
 say
 [name]
 (clojure.core/println &quot;Calling ...&quot;)
 (println (str &quot;hello &quot; name)))
</pre></p>
<p>You can see that our macro created a fn called &#8220;say&#8221; that calls println first before the original body. That is pretty cool huh.</p>
<p>The difference between macroexpand-1 and macroexpand is macroexpand-1<br />
will expand only one level of macros and macroexpand calls macroexpand-1<br />
until all macro forms are expanded.</p>
<p>The same macro expanded with macroexpand will look like</p>
<p><pre class="brush: plain;">
(macroexpand '(def-logged-fn say[name]
        (println (str &quot;hello &quot; name))))

(def
 say
 (clojure.core/fn
  ([name]
   (clojure.core/println &quot;Calling ...&quot;)
   (println (str &quot;hello &quot; name)))))
</pre></p>
<p>As you can see macroexpand expanded defn macro also.</p>
<p>Coming back to our macro, there are 3 reader macros that we have used</p>
<p>- Backtick `<br />
- Tilda ~<br />
- Tilda Ampersand ~@</p>
<p><strong>Backtick ` (syntax-quote):</strong></p>
<p>This is called as syntax-quote. This quotes the whole expression that way you do not have to quote each one of them</p>
<p><strong>Tilda ~ (unquote):</strong></p>
<p>This is called as unquote. This unquotes (substitutes) the value. For<br />
instance, we wanted to replace fn-name with its value, so we tilda<br />
before fn-name.</p>
<p><strong>Tilda Ampersand ~@ (unquote-splicing):</strong></p>
<p>It is easy to show with an example. Lets take our macro that we wrote and change unquote-splicing to unquote before body and let us what happens.</p>
<p><pre class="brush: plain;">
user&gt; (defmacro def-logged-fn [fn-name args &amp; body]
        `(defn ~fn-name ~args
           (println &quot;Calling ...&quot;)
           ~body))
#'user/def-logged-fn
user&gt; (macroexpand-1 '(def-logged-fn say[name]
        (println (str &quot;hello &quot; name))))

(clojure.core/defn
 say
 [name]
 (clojure.core/println &quot;Calling ...&quot;)
 ((println (str &quot;hello &quot; name))))

</pre></p>
<p>You can see the last line looks wierd. It is trying to call output of<br />
println as a function. This will obiviously fail.</p>
<p><pre class="brush: plain;">

user&gt; (def-logged-fn say[name]
         (println (str &quot;hello &quot; name)))
#'user/say
user&gt; (say &quot;techbehindtech&quot;)
Calling ...
hello techbehindtech
; Evaluation aborted.

No message.
  [Thrown class java.lang.NullPointerException]

</pre></p>
<p>As body is a list ( we are using varible args) when we just unquote it<br />
is putting body inside a single list. To avoid that we have to<br />
unquote-splicing.</p>
<p><strong>Auto-gensym</strong></p>
<p>Inside a macro, sometimes you want to create unqualified symbol to use<br />
in a let block. We can do this easily by appending # in end of symbol.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/example/'>example</a>, <a href='http://techbehindtech.com/tag/functional/'>functional</a>, <a href='http://techbehindtech.com/tag/macros/'>macros</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/189/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/189/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/189/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=189&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/09/28/clojure-macros-simplified/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 6</title>
		<link>http://techbehindtech.com/2010/09/16/compojure-demystified-with-an-example-part-6/</link>
		<comments>http://techbehindtech.com/2010/09/16/compojure-demystified-with-an-example-part-6/#comments</comments>
		<pubDate>Fri, 17 Sep 2010 06:09:58 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=183</guid>
		<description><![CDATA[In this part we will start implementing edit and delete functionalities. We are going to build these services, Edit address &#8211; PUT &#8211; http://localhost:8080/addresses/:id Delete address &#8211; DELETE &#8211; http://localhost:8080/addresses/:id 1) Adding PUT and DELETE route Edit routes.clj As you can see it is pretty straight forward to add PUT and DELETE route. What is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=183&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this part we will start implementing edit and delete functionalities.</p>
<p>We are going to build these services,</p>
<p><em>Edit address &#8211; PUT &#8211; http://localhost:8080/addresses/:id</em><br />
<em>Delete address &#8211; DELETE &#8211; http://localhost:8080/addresses/:id</em></p>
<p><em><strong>1) Adding PUT and DELETE route</strong></em></p>
<p>Edit routes.clj</p>
<p><pre class="brush: plain;">
(ns address_book.routes
  (:use [compojure.core])
  (:require [address-book.address :as address]
            [address-book.middleware :as mdw]
            [compojure.route :as route]
            [clj-json.core :as json]))

(defn json-response [data &amp; [status]]
  {:status (or status 200)
   :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
   :body (json/generate-string data)})

(defroutes handler
  (GET &quot;/addresses&quot; [] (json-response (address/find-all)))
  (GET &quot;/addresses/:id&quot; [id] (json-response (address/find id)))
  (POST &quot;/addresses&quot; {params :params}  (json-response (address/create params)))
  (PUT &quot;/addresses/:id&quot; {params :params} (json-response (address/update (params &quot;id&quot;)  params)))
  (DELETE &quot;/addresses/:id&quot; [id] (json-response (address/delete id )))

  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))

(def address-book
     (-&gt; handler
         mdw/wrap-request-logging))
</pre></p>
<p>As you can see it is pretty straight forward to add PUT and DELETE route.</p>
<p><em><strong>What is up with params?</strong></em></p>
<p>In previous version of Compojure there were some magic variables, like params, session etc. From version 0.4 there are no more magic variables. Instead Compojure provides a map &#8220;params&#8221;. &#8220;params&#8221; map will contain all request information. For some reason, params map have a key :params which contains request parameters. That is why we have do {params :params}. I wish they will rename &#8220;params&#8221; to something else.</p>
<p>Instead of doing {params :params}, the compojure document states that we could do [params id] and when compojure detects a vector, instead of a map it will assign the parameters to each value of the vector. But for some reason, I was not able to make it work.</p>
<p><em><strong> Front End code </strong><em> </em></em></p>
<p><em><em>Checkout from <a href="http://github.com/sivajag/Address-Book">github</a> for front end code. Warning: front end code is bad, do not take this as an example.</em></em></p>
<p><em><em><span style="font-style:normal;">In next part we will see how to send flash messages.</span></p>
<p><span style="font-style:normal;">Source code is now available at </span><a href="http://github.com/sivajag/Address-Book"><span style="font-style:normal;">github</span></a><span style="font-style:normal;">. Created branches for each part.</span></p>
<p><span style="font-style:normal;"><em>Next <a href="http://techbehindtech.com/2010/09/16/compojure-demystified-with-an-example-part-6/">part</a> is posted.</em></span></p>
<p></em></em></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/jquery/'>jquery</a>, <a href='http://techbehindtech.com/tag/rest/'>REST</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/183/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/183/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/183/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=183&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/09/16/compojure-demystified-with-an-example-part-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>MQL &#8211; A Clojure library for querying Nested Maps</title>
		<link>http://techbehindtech.com/2010/09/08/mql-a-clojure-library-for-querying-nested-maps/</link>
		<comments>http://techbehindtech.com/2010/09/08/mql-a-clojure-library-for-querying-nested-maps/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 05:43:18 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[libraries]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=179</guid>
		<description><![CDATA[I was working on a feature that needed me to query nested map structure. I wanted to do it in a generic way. Amit pointed me to rql, a library for dealing with collections of records in clojure. I thought it will be helpful if I have something similar to rql for querying map, so [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=179&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was working on a feature that needed me to query nested map structure. I wanted to do it in a generic way. Amit pointed me to <a href="http://github.com/MrHus/rql">rql</a>, a library for dealing with collections of records in clojure. I thought it will be helpful if I have something similar to rql for querying map, so I created <a href="http://github.com/sivajag/mql">mql</a>.</p>
<p>Given a map</p>
<p><pre class="brush: plain;">
(def m
     {:cid
      {
       :visits {
                :id-1 {
                       :last-ts &quot;1284166000040&quot;
                       :first-ts &quot;1274166000000&quot;
                       :duration &quot;40&quot;}
                :id-2 {
                       :last-ts &quot;1274166000040&quot;
                       :first-ts &quot;1274166000000&quot;
                       :duration &quot;40&quot;}
                :id-3 {
                       :last-ts &quot;1264166000040&quot;
                       :first-ts &quot;1274166000000&quot;
                       :duration &quot;40&quot;}}

       :promo{
              :id-1 {:promo &quot;p2&quot;}
              :id-2 {:promo &quot;p1&quot;}}

       :purchase {
                  :id-1
                  {:order-id &quot;order-id-1&quot;
                   :total-dollars &quot;970.00&quot;
                   :purchase? &quot;true&quot;,
                   :merchant-total-dollars &quot;1000.00&quot;}
                  :id-3
                  {:order-id &quot;order-id-2&quot;
                   :total-dollars &quot;1000.00&quot;
                   :purchase? &quot;&quot;
                   :merchant-total-dollars &quot;1000.00&quot;}}}})
</pre></p>
<p><strong>Select: simple select</strong></p>
<p><pre class="brush: plain;">
mql.core&gt; (select [:cid :promo] m)
{:id-1 {:promo &quot;p2&quot;}, :id-2 {:promo &quot;p1&quot;}}
</pre></p>
<p><strong>Select: with filtering</strong></p>
<p><pre class="brush: plain;">
mql.core&gt; (select [:cid :purchase] (where [* :total-dollars] :gt 980) m)
([:id-3 {:order-id &quot;order-id-2&quot;, :total-dollars &quot;1000.00&quot;, :purchase? &quot;&quot;, :merchant-total-dollars &quot;1000.00&quot;}])
</pre></p>
<p>You can currently use :gt,:ge,:lt,:le and :eq as logical operators in where clause. In where clause for key-seq you can use * if a key is dynamic. The last key in where clause key-seq should not be *.</p>
<p><strong>Limitations:</strong></p>
<ul>
<li>There could be only one * in Where Clause</li>
<li>Select clause cannot have * now</li>
</ul>
<p>This is an early version of this library. It is doing what I need for now. So if you have any requirements/idea, you can send me a patch or let me know, I will hack when I get some free time.</p>
<p>Please feel free to send me your feedback on syntax, code style &#8230; etc</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/data-structure/'>data structure</a>, <a href='http://techbehindtech.com/tag/libraries/'>libraries</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/179/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/179/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/179/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=179&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/09/08/mql-a-clojure-library-for-querying-nested-maps/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 5</title>
		<link>http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/</link>
		<comments>http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 07:19:37 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=173</guid>
		<description><![CDATA[In this part lets write our own middleware. From part4 you will remember, &#8220;Middleware are functions that could be chained together to process a request. Middleware functions can take any number of arguments, but the spec stats that first argument should be a handler and function should return a handler. An example for middleware is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=173&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this part lets write our own middleware.</p>
<p>From <a href="http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/">part4</a> you will remember,</p>
<p>&#8220;Middleware are functions that could be chained together to process a request. Middleware functions can take any number of arguments, but the spec stats that first argument should be a handler and function should return a handler. An example for middleware is logging all requests that comes to your webserver.&#8221;</p>
<p><em>1) Create a namespace for middleware </em></p>
<p>Create src/address_book/middleware.clj</p>
<p><pre class="brush: plain;">
(ns address-book.middleware)

(defn- log [msg &amp; vals]
  (let [line (apply format msg vals)]
    (locking System/out (println line))))

(defn wrap-request-logging [handler]
  (fn [{:keys [request-method uri] :as req}]
    (let [resp (handler req)]
      (log &quot;Processing %s %s&quot; request-method uri)
      resp)))
</pre></p>
<p>Our wrap-request-logging is a middleware which takes a handler and returns an handler.</p>
<p><em>2) Add our middleware to our chain of handlers </em></p>
<p>Edit routes.clj</p>
<p><pre class="brush: plain; highlight: [4,22,23];">
(ns address_book.routes
  (:use [compojure.core])
  (:require [address-book.address :as address]
            [address-book.middleware :as mdw]
            [compojure.route :as route]
            [clj-json.core :as json]))

(defn json-response [data &amp; [status]]
  {:status (or status 200)
   :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
   :body (json/generate-string data)})

(defroutes handler
  (GET &quot;/addresses&quot; [] (json-response (address/find-all)))
  (GET &quot;/addresses/:id&quot; [id] (json-response (address/find id)))
  (POST &quot;/addresses&quot; {params :params}  (json-response (address/create params)))

  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))

(def address-book
     (-&gt; handler
         mdw/wrap-request-logging))
</pre></p>
<p><em>3) Test our middleware </em></p>
<p>Now start your server and you can see all requests are getting logged. This is very powerful feature. We can do security etc using middleware. Ring and Compojure comes with some useful middleware. Check them out.</p>
<p>In next part we will implement edit  and delete functionalities.</p>
<p><strong><em>Source code is now available at </em></strong><a href="http://github.com/sivajag/Address-Book"><strong><em>github</em></strong></a><strong><em>. </em></strong> <strong><em>Created branches for each part.</em></strong></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/jquery/'>jquery</a>, <a href='http://techbehindtech.com/tag/rest/'>REST</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/173/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/173/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/173/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=173&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 4</title>
		<link>http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/</link>
		<comments>http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/#comments</comments>
		<pubDate>Tue, 24 Aug 2010 23:25:25 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=146</guid>
		<description><![CDATA[In this part we will start implementing Add,  View and View all functionalities. The services we are going to build are View All Addresses &#8211; GET &#8211; http://localhost:8080/addresses View single address &#8211; GET &#8211; http://localhost:8080/addresses/:id Add Address &#8211; POST &#8211; http://localhost:8080/addresses Interactive Development using slime I mentioned in last part that after every change to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=146&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:left;">In this part we will start implementing Add,  View and View all functionalities.</p>
<p>The services we are going to build are</p>
<p><em>View All Addresses &#8211; GET &#8211; http://localhost:8080/addresses<br />
View single address &#8211; GET &#8211; http://localhost:8080/addresses/:id<br />
Add Address &#8211; POST &#8211; http://localhost:8080/addresses</em></p>
<p><strong>Interactive Development using slime </strong></p>
<p>I mentioned in last part that after every change to our code we need to restart our server for our changes to be reflected. This is a pain and against clojure (lisp) philosophy . It would be great if we could eval our modified buffers in emacs and those changes reflected immediately in our jetty server. Thankfully there is very easy way to do this.</p>
<p>In core.clj we are starting jetty adapter. We can start this jetty server in background using future and reload the namespace that we changed. This way we can do interactive development without restarting our server.</p>
<p>PS: Make sure you have emacs setup with slime. I feel emacs is the best IDE for clojure. Again this is my opinion. There are lot of information on how to do this.</p>
<p>I talked about jetty adapter. It is time for us to look at some what little deeper in Compojure.</p>
<p><strong>Compojure</strong></p>
<p>Compojure is based on a library  called <strong><a href="http://github.com/mmcgrana/ring">Ring</a></strong>. In fact most of clojure web frameworks are based on Ring. So to understand Compojure, it is important to understand Ring.</p>
<p>Ring has three components.</p>
<p><em>1) Handlers:</em></p>
<p>Handlers are main functions that  process a request. We define handlers using defroutes macro.</p>
<p><em>2) Middleware:</em></p>
<p>Middleware are functions that could be chained together to process a request. Middleware functions can take any number of arguments, but the spec stats that first argument should be an handler and function should return an handler. An example for middleware is logging all requests that comes to your webserver.  Ring and compojure comes with some standard middleware. We will see in next part how to create our own middleware.</p>
<p><em>3) Adapters:</em></p>
<p>Adapters are functions could adapt our handler to a web server. We are using jetty adapter to tie our handler to jetty server.</p>
<p><strong>Refactor code to make it easy for interactive development</strong></p>
<p>Edit core.clj</p>
<p><pre class="brush: plain; highlight: [11];">
(ns address_book.core
  (:use [compojure.core]
        [ring.adapter.jetty])
  (:require [compojure.route :as route]))

(defroutes example
  (GET &quot;/&quot; [] &quot;&lt;h1&gt;My Address Book!&lt;/h1&gt;&quot;)
  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))

(future (run-jetty (var address-book) {:port 8080}))
</pre></p>
<p><em><strong>1) Add swank-clojure to our project</strong></em></p>
<p>swank-clojure comes with lein plugin which will allow us to start a swank server and from emacs you can connect using slime. There are lot of documentation about swank-clojure and slime. Let me know if you need more information. If I see enough interest, I could blog about it or at least point to some good resources.</p>
<p>Edit project.clj</p>
<p><pre class="brush: plain; highlight: [3,4,7];">
(defproject address_book &quot;1.0.0-SNAPSHOT&quot;
  :description &quot;Address Book&quot;
  :dependencies [[org.clojure/clojure &quot;1.2.0&quot;]
                 [org.clojure/clojure-contrib &quot;1.2.0&quot;]
                 [compojure &quot;0.4.1&quot;]
                 [ring/ring-jetty-adapter &quot;0.2.3&quot;]]
  :dev-dependencies [[swank-clojure &quot;1.2.1&quot;]])
</pre></p>
<p>and run</p>
<p><pre class="brush: plain;">lein deps</pre></p>
<p>Now you should be able to start swank server using</p>
<p><pre class="brush: plain;">lein swank</pre></p>
<p><strong><em>2) Break core.clj into different namespaces</em></strong></p>
<p>Current core.clj is doing two things. Setting up routes and starting jetty server. Lets break it into web_server.clj and routes.clj</p>
<p><pre class="brush: plain;">rm src/address_book/core.clj</pre></p>
<p>create src/address_book/routes.clj</p>
<p><pre class="brush: plain;">
(ns address_book.routes
  (:use [compojure.core])
  (:require [compojure.route :as route]))

(defroutes address-book
  (GET &quot;/&quot; [] &quot;&lt;h1&gt;My Address Book!&lt;/h1&gt;&quot;)
  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))
</pre></p>
<p>create src/address_book/webserver.clj</p>
<p><pre class="brush: plain;">
(ns address_book.webserver
  (:use [compojure.core]
        [ring.adapter.jetty]
        [address_book.routes :as routes]))

(future (run-jetty (var address-book) {:port 8080}))
</pre></p>
<p><strong><em>3) At last lets create our Address namespace</em></strong></p>
<p>In this code, I am going to use atoms for persistence. In future I will probably show how we can persist in mysql db using clj-records.</p>
<p>create src/address_book/address.clj</p>
<p><pre class="brush: plain;">
(ns address-book.address
  (:use [address-book.utils number])
  (:refer-clojure :exclude (find create)))

(def STORE (atom {:1 {:id :1 :name &quot;Siva Jagadeesan&quot; :street1 &quot;88 7th&quot; :street2 &quot;#203&quot; :city &quot;Cupertino&quot; :country &quot;USA&quot; :zipcode 98802}}))

(defn create [attrs]
  (let [id (random-number)
        new-attrs (merge {:id id} attrs)]
    (swap! STORE merge {id new-attrs})
    new-attrs))

(defn find-all []
  (vals @STORE))

(defn find [id]
  ((to-keyword id) @STORE))

(defn update [id attrs]
  (let [updated-attrs (merge (find id) attrs)]
    (swap! STORE assoc id updated-attrs)
    updated-attrs))

(defn delete [id]
  (let [old-attrs (find id)]
    (swap! STORE dissoc id)
    old-attrs))
</pre></p>
<p>Create utils/number.clj</p>
<p><pre class="brush: plain;">
(ns address-book.utils.number
  (:import [java.util Date]))

(defn to-keyword [num]
  (if-not (keyword? num)
    (keyword (str num))
    num))

(defn random-number []
  (to-keyword (.getTime (Date.))))
</pre></p>
<p>PS: I am not writing tests to keep this blog short. But I would advice everyone to write tests.</p>
<p><strong><em>4)   Lets update routes for add, view and view all functionalities</em></strong></p>
<p><span style="font-family:Consolas, Monaco, 'Courier New', Courier, monospace;line-height:18px;font-size:12px;white-space:pre;"> </span></p>
<p><pre class="brush: plain;">&lt;/span&gt;
&lt;pre&gt;(ns address_book.routes
  (:use [compojure.core])
  (:require [address-book.address :as address]
            [compojure.route :as route]
            [clj-json.core :as json]))

(defn json-response [data &amp; [status]]
  {:status (or status 200)
   :headers {&quot;Content-Type&quot; &quot;application/json&quot;}
   :body (json/generate-string data)})

(defroutes handler
  (GET &quot;/addresses&quot; [] (json-response (address/find-all)))
  (GET &quot;/addresses/:id&quot; [id] (json-response (address/find id)))
  (POST &quot;/addresses&quot; {params :params}  (json-response (address/create params)))

  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))

(def address-book
     handler)
</pre></p>
<p>Compojure comes with GET, POST, PUT, DELETE, HEAD and ANY macro to define routes. These macros are self explanatory. Currently we have used GET and POST to define our routes.</p>
<p><em>Parsing Parameters </em></p>
<p>Compojure binds request parameters to params.</p>
<p>To get all parameters from request you can destructure map like we did in</p>
<p><pre class="brush: plain;">POST &quot;/addresses&quot; {params :params}  (json-response (address/create params)))</pre></p>
<p>To get particular parameters from request you can use Compojure sugar syntax like we did in<br />
[sourceode](GET &#8220;/addresses/:id&#8221; [id] (json-response (address/find id)))[/sourcecode]</p>
<p><em><strong>5)  Lets build our front end</strong></em><br />
<em>PS: front end code is a hack. Please don&#8217;t follow these codes as a good practice.</em></p>
<p><strong><em><span style="font-style:normal;font-weight:normal;">Edit public/index.html</span></em></strong></p>
<p><strong><em><span style="font-style:normal;font-weight:normal;"> </span></em></strong></p>
<p><strong><em> </em></strong></p>
<p><strong><em> </em></strong></p>
<p><strong><em> </em></strong></p>
<p><pre class="brush: xml;">
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot;
        &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
	&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
	&lt;title&gt;My Address Book&lt;/title&gt;
        &lt;link href=&quot;/css/address.css&quot; media=&quot;screen&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
        &lt;script src=&quot;/js/jquery-1.4.2.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;/js/jquery-ui-1.8.1.custom.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;/js/jquery.form.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;/js/address_book.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
        &lt;script src=&quot;/js/address_list.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div id=&quot;wrap&quot;&gt;
	&lt;div id=&quot;header&quot;&gt;&lt;h1&gt;My Address Book&lt;/h1&gt;&lt;/div&gt;

	&lt;div id=&quot;main&quot;&gt;
          &lt;table id=&quot;address&quot;&gt;
            &lt;tr&gt;&lt;td&gt;Name&lt;/td&gt;&lt;td id=&quot;name&quot;/&gt;&lt;/tr&gt;
            &lt;tr&gt;&lt;td&gt;Street1&lt;/td&gt;&lt;td id=&quot;street1&quot;/&gt;&lt;/tr&gt;
            &lt;tr&gt;&lt;td&gt;Street2&lt;/td&gt;&lt;td id=&quot;street2&quot;/&gt;&lt;/tr&gt;
            &lt;tr&gt;&lt;td&gt;City&lt;/td&gt;&lt;td id=&quot;city&quot;/&gt;&lt;/tr&gt;
            &lt;tr&gt;&lt;td&gt;Country&lt;/td&gt;&lt;td id=&quot;country&quot;/&gt;&lt;/tr&gt;
            &lt;tr&gt;&lt;td&gt;ZipCode&lt;/td&gt;&lt;td id=&quot;zipcode&quot;/&gt;&lt;/tr&gt;
          &lt;/table&gt;
	  &lt;table id=&quot;address-list&quot; border=&quot;1&quot; width=&quot;100%&quot; rules=&quot;rows&quot; align=&quot;center&quot;&gt;
            &lt;tr&gt;
              &lt;th&gt;Name&lt;/th&gt;
              &lt;th&gt;Action&lt;/th&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
              &lt;td &gt;row 1, cell 1&lt;/td&gt;
              &lt;td align=&quot;center&quot;&gt;row 1, cell 2&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/table&gt;
	&lt;/div&gt;
	&lt;div id=&quot;sidebar&quot;&gt;
          &lt;form id=&quot;address-form&quot; class=&quot;formular&quot; method=&quot;post&quot; action=&quot;/addresses&quot;&gt;
	    &lt;fieldset class=&quot;login&quot;&gt;
	      &lt;legend&gt;New Address&lt;/legend&gt;
	      &lt;div&gt;
		&lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot;&gt;
	      &lt;/div&gt;
              &lt;div&gt;
		&lt;label for=&quot;street1&quot;&gt;Street1&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;street1&quot; name=&quot;street1&quot;&gt;
	      &lt;/div&gt;
               &lt;div&gt;
		&lt;label for=&quot;street2&quot;&gt;Street2&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;street2&quot; name=&quot;street2&quot;&gt;
	      &lt;/div&gt;
              &lt;div&gt;
		&lt;label for=&quot;city&quot;&gt;City&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;city&quot; name=&quot;city&quot;&gt;
	      &lt;/div&gt;
              &lt;div&gt;
		&lt;label for=&quot;country&quot;&gt;Country&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;country&quot; name=&quot;country&quot;&gt;
	      &lt;/div&gt;
               &lt;div&gt;
		&lt;label for=&quot;zipcode&quot;&gt;ZipCode&lt;/label&gt; &lt;input type=&quot;text&quot; id=&quot;zipcode&quot; name=&quot;zipcode&quot;&gt;
	      &lt;/div&gt;

              &lt;input class=&quot;submit&quot; type=&quot;submit&quot; value=&quot;Create&quot;/&gt;
	    &lt;/fieldset&gt;
          &lt;/form&gt;
	&lt;/div&gt;
	&lt;div id=&quot;footer&quot;&gt;
	  &lt;p&gt;&lt;a href=&quot;TechbehindTech.com&quot;&gt;TechBehindTech&lt;/a&gt; -- Siva Jagadeesan&lt;/p&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

</pre></p>
<p>Create public/css/address.css</p>
<p><pre class="brush: css;">
body,html {
    margin:0;
    padding:0;
    color:#000;
    background:#a7a09a;
}
#wrap {
    width:970px;
    margin:0 auto;
    background: #fffeff;
}
#header {
    padding:5px 10px;
    background: #054477;
	text-align: right;
	color: #fffeff;
}
h1 {
    margin:0;
}
#main {
    float:left;
    width:580px;
    padding:10px;
	background-color: #fffeff;
}
h2 {
    margin:0 0 1em;
	background-color: #fffeff;
}
#sidebar {
    float:right;
    width:350px;
    padding:10px;
    background-color: #fffeff;
}
#footer {
    clear:both;
    padding:5px 10px;
    background: #fed47f;
}
#footer p {
    margin:0;
}
* html #footer {
    height:1px;
}

form * {margin:0;padding:0;} /* Standard margin and padding reset, normally done on the body */

legend {
	color:#000; /* IE styles legends with blue text by default */
	*margin-left:-7px;
	font-weight: bold;
	font-size: 20px;
}
fieldset {
	border:1px solid #dedede; /* Default fieldset borders vary cross browser, so make them the same */
}
fieldset div {
	overflow:hidden; /* Contain the floating elements */
	display:inline-block;
	padding: 10px;
}
fieldset div {display:block;} /* Reset element back to block leaving layout in ie */
label {
	float:left; /* Take out of flow so the input starts at the same height */
	width:8em; /* Set a width so the inputs line up */
}
</pre></p>
<p>Create public/js/address_book.js</p>
<p><pre class="brush: jscript;">

$(document).ready(function() {
    $(&quot;#address&quot;).hide();
    $(&quot;#address-list&quot;).showAddressList();

    $(&quot;.address-link&quot;).live(&quot;click&quot;,function(e){
        $.getJSON($(this).attr(&quot;href&quot;), function(json) {
            $(&quot;#address&quot;).showAddress(json);
        });
        e.preventDefault();
    });

    $('#address-form').submit(function(event){
        event.preventDefault();
        var $this = $(this);
        var url = $this.attr('action');
        var dataToSend = $this.serialize();
        var callback = function(data){
            $(&quot;#address-list&quot;).addAddress(data);
        };
        var options = {
            success:   callback,
            url: url,
            type:     &quot;POST&quot;,
            dataType: &quot;json&quot;,
            clearForm: true
        };
        $(this).ajaxSubmit(options);
    });

});
</pre></p>
<p>Create public/js/address_list.js</p>
<p><pre class="brush: jscript;">
function action_links(data){
    var link = &quot;&lt;a href=\&quot;\&quot;&gt;edit&lt;/a&gt; &quot;;
    link += &quot; | &lt;a href=\&quot;\&quot;&gt;delete&lt;/a&gt;&quot;;
    return &quot;edit | delete&quot;;
}

$.fn.showAddressList = function(){
    return this.each(function(){
        var that = this;
        $.getJSON(&quot;addresses&quot;, function(json) {
            $(that).html(&quot; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/tr&gt;&quot;);
            $.each(json,function(i,data) {
                $(that).append(&quot;&lt;tr id=\&quot;address-&quot;+ data.id +&quot; \&quot;&gt;&lt;td&gt;&lt;a class=\&quot;address-link\&quot; href=\&quot;addresses/&quot; + data.id +&quot;\&quot;&gt;&quot; + data.name + &quot;&lt;/a&gt;&lt;/td&gt;&lt;td align='center'&gt;&quot; + action_links(data) + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;);
            });
        });
    });
};

$.fn.addAddress = function(json){
    var data = json;
    var that = this;
    return this.each(function(){
        var that = this;
        $(that).append(&quot;&lt;tr id=\&quot;address-&quot;+ data.id +&quot; \&quot;&gt;&lt;td&gt;&lt;a class=\&quot;address-link\&quot; href=\&quot;addresses/&quot; + data.id +&quot;\&quot;&gt;&quot; + data.name + &quot;&lt;/a&gt;&lt;/td&gt;&lt;td align='center'&gt;&quot; + action_links(data) + &quot;&lt;/td&gt;&lt;/tr&gt;&quot;);
    });
};

$.fn.showAddress = function(json){
    var data = json;
    var that = this;
    return this.each(function(){
        $(that).slideDown('slow');
        $(that).find(&quot;#name&quot;).html(data.name);
        $(that).find(&quot;#street1&quot;).html(data.street1);
        $(that).find(&quot;#street2&quot;).html(data.street2);
        $(that).find(&quot;#city&quot;).html(data.city);
        $(that).find(&quot;#country&quot;).html(data.country);
        $(that).find(&quot;#zipcode&quot;).html(data.zipcode);
    });
};

</pre></p>
<p>Download jquery-1.4.2.min.js, jquery-ui-1.8.1.custom.min.js and jquery.form.js to public/js folder.<br />
<strong><em> </em></strong></p>
<p><strong><em>6)  Start the web server</em></strong></p>
<p>[/sourcecode]<span style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;line-height:19px;white-space:normal;font-size:13px;">lein repl src/address_book/webserver.clj [/sourceode]</span></p>
<p><span style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;line-height:19px;white-space:normal;font-size:13px;"><a href="http://sivajag.files.wordpress.com/2010/08/screen-shot-2010-08-24-at-10-38-18-pm.png"><img class="alignnone size-full wp-image-164" title="My Address book Part 4" src="http://sivajag.files.wordpress.com/2010/08/screen-shot-2010-08-24-at-10-38-18-pm.png?w=700&#038;h=274" alt="" width="700" height="274" /></a></span></p>
<p>Wow that was lot of stuff.  We will look more into writing our own middlewares in next <a href="http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/">part</a>.</p>
<p><strong><em>Source code is now available at </em></strong><a href="http://github.com/sivajag/Address-Book"><strong><em>github</em></strong></a><strong><em>. Created branches for each part.</em></strong></p>
<p><strong><em><span style="font-style:normal;font-weight:normal;"><a href="http://techbehindtech.com/2010/09/02/compojure-demystified-with-an-example-part-5/">Part 5</a> is posted.</span></em></strong></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/jquery/'>jquery</a>, <a href='http://techbehindtech.com/tag/rest/'>REST</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/146/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/146/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/146/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=146&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>

		<media:content url="http://sivajag.files.wordpress.com/2010/08/screen-shot-2010-08-24-at-10-38-18-pm.png" medium="image">
			<media:title type="html">My Address book Part 4</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 3</title>
		<link>http://techbehindtech.com/2010/08/16/compojure-demystified-with-an-example-part-3/</link>
		<comments>http://techbehindtech.com/2010/08/16/compojure-demystified-with-an-example-part-3/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 04:04:27 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=131</guid>
		<description><![CDATA[In part2 we saw how to setup a skeleton project with Compojure. In this part we will see how to add static files to a Compojure project. For our application, we will use JQuery as front end and Clojure as a backend. I will concentrate more on Compojure. 1) Create folders for static files. It [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=131&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://techbehindtech.com/2010/08/15/compojure-demystified-with-an-example-part-2/">part2</a> we saw how to setup a skeleton project with Compojure. In this part we will see how to add static files to a Compojure project.</p>
<p>For our application, we will use JQuery as front end and Clojure as a backend. I will concentrate more on Compojure.</p>
<p>1) Create folders for static files.</p>
<p><pre class="brush: plain;">
mkdir public
mkdir public/css
mkdir public/js
</pre></p>
<p>It is better to have static files under a seperate directory that way you could use your webserver to serve these files. For now we will use Compojure to serve these files.</p>
<p>2) Create index.html under public folder</p>
<p><pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;
	&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
		&lt;title&gt;My Address book&lt;/title&gt;
		&lt;script type=&quot;text/javascript&quot; src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;&gt;&lt;/script&gt;
	&lt;/head&gt;

  &lt;body id=&quot;main&quot;&gt;
    &lt;p&gt;
      My Address Book
    &lt;/p&gt;
  &lt;body&gt;
&lt;/html&gt;
</pre></p>
<p>3) Start your server</p>
<p><pre class="brush: plain;">
lein repl src/address_book/core.clj
</pre></p>
<p>4) Access index.html</p>
<p>Go to http://localhost:8080/index.html . You will get &#8220;Page not found&#8221; instead of &#8220;My Address Book&#8221;. This is happening because we have not told compojure about our static files folder.</p>
<h3><span style="text-decoration:underline;">Route helper functions in Compojure</span></h3>
<p>In Compojure we have two route helper functions. We have seen one already in core.clj file.</p>
<h4>1) <span style="text-decoration:underline;">not-found </span>:</h4>
<p>This function is used to capture all other routes that are not defined in Compojure. As we still have not defined index.html we got &#8220;Page not found&#8221;.</p>
<h4>2) <span style="text-decoration:underline;">files </span>:</h4>
<p>This function is used to inform Compojure where static files are present.</p>
<p>Lets change our core.clj to handle static files</p>
<p><pre class="brush: plain; highlight: [8];">
(ns address_book.core
  (:use [compojure.core]
        [ring.adapter.jetty])
  (:require [compojure.route :as route]))

(defroutes example
  (GET &quot;/&quot; [] &quot;&lt;h1&gt;My Address Book!&lt;/h1&gt;&quot;)
  (route/files &quot;/&quot; {:root &quot;public&quot;})
  (route/not-found &quot;Page not found&quot;))

(run-jetty example {:port 8080})
</pre></p>
<p>Restart your server (there is a way to avoid restarting using futures. I will show that in a later blog) and access http://localhost:8080/index.html .  Now you should see &#8220;My Address Book&#8221;.</p>
<p>In this part we saw how we can handle static files. In next part we will implement Add , View and View All functionalities.</p>
<p>PS: Using <a href="http://github.com/weavejester/hiccup">Hiccup</a> you can create HTML and css in clojure. I will try to cover this in future blogs.</p>
<p><strong><em>Source code is now available at </em></strong><a href="http://github.com/sivajag/Address-Book"><strong><em>github</em></strong></a><strong><em> . Created branches for each part.</em></strong></p>
<p><strong><em>Checkout <a href="http://techbehindtech.com/2010/08/24/compojure-demystified-with-an-example-part-4/">PART4</a></em><em> &#8230;</em></strong></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/131/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/131/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/131/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=131&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/08/16/compojure-demystified-with-an-example-part-3/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 2</title>
		<link>http://techbehindtech.com/2010/08/15/compojure-demystified-with-an-example-part-2/</link>
		<comments>http://techbehindtech.com/2010/08/15/compojure-demystified-with-an-example-part-2/#comments</comments>
		<pubDate>Mon, 16 Aug 2010 01:49:59 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=104</guid>
		<description><![CDATA[In part 1 I introduced the address book application that we are going to build. In this part we will setup our skeleton project with compojure. 1) Install Leiningen http://github.com/technomancy/leiningen/blob/master/README.md 2) Create a new project using Leiningen 3) Add Compojure to our project: a) Edit project.clj b) Install dependencies lein deps This should install all [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=104&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://techbehindtech.com/2010/08/14/compojure-demystified-with-an-example-part-1/">part 1 </a> I introduced the address book application that we are going to build.</p>
<p>In this part we will setup our skeleton project with compojure.</p>
<p>1) Install Leiningen</p>
<p><a href="http://github.com/technomancy/leiningen/blob/master/README.md">http://github.com/technomancy/leiningen/blob/master/README.md</a></p>
<p>2) Create a new project using Leiningen</p>
<p><pre class="brush: plain;">lein new address_book</pre></p>
<p>3) Add Compojure to our project:</p>
<p>a) Edit project.clj</p>
<p><pre class="brush: plain;">
(defproject address_book &quot;1.0.0-SNAPSHOT&quot;
  :description &quot;Address Book&quot;
  :dependencies [[org.clojure/clojure &quot;1.1.0&quot;]
                 [org.clojure/clojure-contrib &quot;1.1.0&quot;]
                 [compojure &quot;0.4.1&quot;]
                 [ring/ring-jetty-adapter &quot;0.2.3&quot;]])
</pre></p>
<p>b) Install dependencies</p>
<p><code>lein deps</code></p>
<p>This should install all dependencies of compojure</p>
<p>c) Test whether our setup is working</p>
<p>Edit src/address_book/core.clj</p>
<p><pre class="brush: plain;">
(ns address_book.core
  (:use [compojure.core]
           [ring.adapter.jetty])
  (:require [compojure.route :as route]))

(defroutes example
  (GET &quot;/&quot; [] &quot;My Address Book!&quot;)
  (route/not-found &quot;Page not found&quot;))

(run-jetty example {:port 8080})
</pre></p>
<p>Run the server</p>
<p><pre class="brush: plain;">lein repl src/address_book/core.clj</pre></p>
<p>Goto http://localhost:8080 and you should see &#8220;My Address Book!&#8221;</p>
<p>In next <a href="http://techbehindtech.com/2010/08/16/compojure-demystified-with-an-example-part-3/">part</a> we will start implementing our functionalities.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/104/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=104&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/08/15/compojure-demystified-with-an-example-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Compojure Demystified with an example &#8211; Part 1</title>
		<link>http://techbehindtech.com/2010/08/14/compojure-demystified-with-an-example-part-1/</link>
		<comments>http://techbehindtech.com/2010/08/14/compojure-demystified-with-an-example-part-1/#comments</comments>
		<pubDate>Sat, 14 Aug 2010 19:15:25 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[compojure]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=100</guid>
		<description><![CDATA[In this part, I am going to talk about what application we are going to implement. Lets build a simple address book web application using compojure. This will be a RESTFUL application. As we go through this example we will see some interesting aspects of compojure. Functionalities Add / Edit / Delete Address book View [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=100&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this part, I am going to talk about what application we are going to implement.</p>
<p>Lets build a simple address book web application using compojure. This will be a RESTFUL application. As we go through this example we will see some interesting aspects of compojure.</p>
<p><strong>Functionalities </strong></p>
<ul>
<li>Add / Edit / Delete Address book</li>
<li>View All Addresses</li>
<li>View a single Address</li>
</ul>
<p><strong>Domain</strong></p>
<p><strong></strong> <strong><em>Address</em></strong></p>
<ul>
<li>Name</li>
<li>Street1</li>
<li>Street2</li>
<li>City</li>
<li>Country</li>
<li>ZipCode</li>
</ul>
<p><strong>REST interfaces we will implement</strong></p>
<ul>
<li>View All Addresses  &#8211; <strong>GET</strong> &#8211; http://localhost:8080/addresses</li>
<li>View single address &#8211; <strong>GET</strong> &#8211; http://localhost:8080/addresses/:id</li>
<li>Add Address 		- <strong>POST</strong> &#8211; http://localhost:8080/addresses</li>
<li>Edit Address		- <strong>PUT</strong> &#8211; http://localhost:8080/addresses/:id</li>
<li>Delete Address      &#8211; <strong>DELETE</strong> &#8211; http://localhost:8080/addresses/:id</li>
</ul>
<p>Next <a href="http://techbehindtech.com/2010/08/15/compojure-demystified-with-an-example-part-2/">part 2</a> we will setup our base project with compojure.</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/compojure/'>compojure</a>, <a href='http://techbehindtech.com/tag/web/'>web</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/100/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/100/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/100/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=100&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/08/14/compojure-demystified-with-an-example-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Map, Reduce and Filter in Clojure</title>
		<link>http://techbehindtech.com/2010/07/26/map-reduce-and-filter-in-clojure/</link>
		<comments>http://techbehindtech.com/2010/07/26/map-reduce-and-filter-in-clojure/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 22:00:13 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=91</guid>
		<description><![CDATA[Map Map applies a function to each element in a collection and returns a new collection with the results of each function. Reduce Reduce applies a function on all elements of a collection and returns a value. This value could also be another collection. Filter Filter applies a predicate function to each element in a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=91&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Map</strong></p>
<p>Map applies a function to each element in a collection and returns a new collection with the results of each function.</p>
<div style="text-align:center;"><img src="http://sivajag.files.wordpress.com/2010/07/map.png?w=319&#038;h=121" border="0" alt="map.png" width="319" height="121" /></div>
<p><pre class="brush: plain;">user&gt; (map #(+ 10 %1) [ 1 3 5 7 ])
(11 13 15 17)</pre></p>
<p><strong>Reduce</strong></p>
<p>Reduce applies a function on all elements of a collection and returns a value. This value could also be another collection.</p>
<div style="text-align:center;"><img src="http://sivajag.files.wordpress.com/2010/07/reduce1.png?w=424&#038;h=130" border="0" alt="reduce.png" width="424" height="130" /></div>
<p><pre class="brush: plain;">user&gt; (reduce * [2 3 4])
24</pre></p>
<p><strong>Filter</strong></p>
<p>Filter applies a predicate function to each element in a collection and returns a new filtered collection.</p>
<div style="text-align:center;"><img src="http://sivajag.files.wordpress.com/2010/07/filter.png?w=319&#038;h=117" border="0" alt="filter.png" width="319" height="117" /></div>
<p><pre class="brush: plain;">user&gt; (filter even? [1 2 3 4 5 6])
(2 4 6)</pre></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/functional/'>functional</a>, <a href='http://techbehindtech.com/tag/snippet/'>snippet</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/91/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=91&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/07/26/map-reduce-and-filter-in-clojure/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>

		<media:content url="http://sivajag.files.wordpress.com/2010/07/map.png" medium="image">
			<media:title type="html">map.png</media:title>
		</media:content>

		<media:content url="http://sivajag.files.wordpress.com/2010/07/reduce1.png" medium="image">
			<media:title type="html">reduce.png</media:title>
		</media:content>

		<media:content url="http://sivajag.files.wordpress.com/2010/07/filter.png" medium="image">
			<media:title type="html">filter.png</media:title>
		</media:content>
	</item>
		<item>
		<title>Different tools to help you test your clojure code</title>
		<link>http://techbehindtech.com/2010/07/24/different-tools-to-help-you-test-your-clojure-code/</link>
		<comments>http://techbehindtech.com/2010/07/24/different-tools-to-help-you-test-your-clojure-code/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 00:51:08 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=83</guid>
		<description><![CDATA[Problem : We need to parse a xml string and be able to query using xpath style tag list. Ex : I need a function that can do this, returns &#8220;Siva&#8221; Solution : To parse and query xml we need to do these following three things in clojure. 1) Convert xml string (file) to Struct [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=83&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Problem :</strong></p>
<p>We need to parse a xml string and be able to query using xpath style tag list.</p>
<p>Ex :<br />
<pre class="brush: plain;">
&lt;friends&gt;
  &lt;person&gt;
   &lt;name&gt;Siva&lt;/name&gt;
  &lt;/person&gt;
&lt;/friends&gt;
</pre></p>
<p>I need a function that can do this,</p>
<p><pre class="brush: plain;">
(get-value xml :person :name)
</pre> returns &#8220;Siva&#8221;</p>
<p><strong>Solution :</strong></p>
<p>To parse and query xml we need to do these following three things in clojure.</p>
<p><strong><em>1) Convert xml string (file) to Struct Map</em></strong></p>
<p>Clojure core comes with a build in xml library (clojure.xml <a href="http://richhickey.github.com/clojure/clojure.xml-api.html">http://richhickey.github.com/clojure/clojure.xml-api.html</a>) that has a parse function which takes in InputStream and returns a struct map that represents xml.</p>
<p><pre class="brush: plain;">
(defn get-struct-map [xml]
  (let [stream (ByteArrayInputStream. (.getBytes (.trim xml)))]
    (xml/parse stream)))
</pre></p>
<p><pre class="brush: plain;">
user&gt; (get-struct-map xml)
{:tag :friends, :attrs nil, :content [{:tag :person, :attrs nil, :content [{:tag :name, :attrs nil, :content [&quot;Siva&quot;]}]}]}
</pre></p>
<p>This struct map is cumbersome to query.</p>
<p><strong><em>2) Convert Struct Map to Zipper Data Structure</em></strong></p>
<p>&#8220;A zipper is a technique of representing an aggregate data structure so that it is convenient for writing programs that traverse the structure arbitrarily and update its contents, especially in purely functional programming languages.&#8221; <a href="http://en.wikipedia.org/wiki/Zipper_%28data_structure%29">http://en.wikipedia.org/wiki/Zipper_%28data_structure%29</a></p>
<p>To make it easy for us to traverse we will change struct map to zipper data structure. Clojure comes with zip library ( it is short form for zipper ) <a href="http://richhickey.github.com/clojure/clojure.zip-api.html">http://richhickey.github.com/clojure/clojure.zip-api.html</a></p>
<p>We will this zip library to convert xml struct map to zipper data structure.</p>
<p><pre class="brush: plain;">
user&gt; (clojure.zip/xml-zip xml-struct)
[{:tag :friends, :attrs nil, :content [{:tag :person, :attrs nil, :content [{:tag :name, :attrs nil, :content [&quot;Siva&quot;]}]}]} nil]
</pre></p>
<p><em><strong>3) Use Zip-filter library and query zipper data structure.</strong></em></p>
<p>Now that we have our xml in zipper data structure we could use zip-filter library that is present in clojure.contrib. <a href="http://richhickey.github.com/clojure-contrib/zip-filter-api.html">http://richhickey.github.com/clojure-contrib/zip-filter-api.html</a></p>
<p><pre class="brush: plain;">user&gt; (clojure.contrib.zip-filter.xml/xml-&gt; zipper-struct :person :name)
(&quot;Siva&quot;)
</pre><br />
Putting this altogether</p>
<p><pre class="brush: plain;">
(ns com.sivajag.utils.xml
  (:import (java.io ByteArrayInputStream))
  (:require [clojure.xml :as xml])
  (:require [clojure.zip :as zip])
  (:require [clojure.contrib.zip-filter.xml :as zf]))

(defn get-struct-map [xml]
  (if-not (empty? xml)
    (let [stream (ByteArrayInputStream. (.getBytes (.trim xml)))]
      (xml/parse stream))))

(defn get-value [xml &amp;amp; tags]
  (apply zf/xml1-&gt; (zip/xml-zip (get-struct-map xml)) (conj (vec tags) zf/text)))

user&gt; (get-value xml :person :name)
&quot;Siva&quot;</pre></p>
<p>Happy Coding!!!</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/testing/'>testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/83/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/83/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/83/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=83&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/07/24/different-tools-to-help-you-test-your-clojure-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Clojure futures &#8211; A Walkthrough</title>
		<link>http://techbehindtech.com/2010/07/14/clojure-futures-a-walkthrough/</link>
		<comments>http://techbehindtech.com/2010/07/14/clojure-futures-a-walkthrough/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 04:22:18 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[future]]></category>
		<category><![CDATA[snippet]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=80</guid>
		<description><![CDATA[What is Future? It is a simple mechanism to execute a snippet of code on a background thread. How to use Future? We can use Future in two ways. 1) Using macro &#8220;future&#8221; 2) Using function &#8220;future-call&#8221; Under the shell both these ways are equivalent. The macro is syntax sugar and it gets converted to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=80&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4>What is Future?</h4>
<p>It is a simple mechanism to execute a snippet of code on a background thread.</p>
<h4>How to use Future?</h4>
<p>We can use Future in two ways.</p>
<p>1) Using macro &#8220;future&#8221;</p>
<p><pre class="brush: plain;">	
  (def f
	(future
 		(prn &quot;going to sleep...&quot;)
		(Thread/sleep 10000)
		(prn &quot;slept good&quot;)))
</pre></p>
<p>2) Using function &#8220;future-call&#8221;</p>
<p><pre class="brush: plain;">
(defn long-process[]
  (Thread/sleep 10000))

(future-call long-process)

</pre></p>
<p>Under the shell both these ways are equivalent. The macro is syntax sugar and it gets converted to future-call. </p>
<p>Even though &#8220;long-process&#8221; function is put to sleep for 10 secs, it will return immediately. It returns a &#8220;future&#8221; object. We can use this object to inspect whether the function has been executed in background thread.</p>
<p><pre class="brush: plain;">
(future-done? f)
(future-cancelled? f)
(future-cancel f)
</pre></p>
<h4>Limitations of Future?</h4>
<p>As you known clojure comes with a bounded thread pool and unbounded thread pool. Mostly CPU bound operations should be using bounded thread pool and IO operations should be using unbound thread pool. Clojure Future uses unbounded thread pool, so it is good for IO operations but not for CPU bound operations. So for CPU bound operations Future might not be a good choice. But there is a open source project that helps to overcome this limitations. Check out <a href="http://github.com/amitrathore/medusa">http://github.com/amitrathore/medusa</a></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/future/'>future</a>, <a href='http://techbehindtech.com/tag/snippet/'>snippet</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/80/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/80/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/80/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=80&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/07/14/clojure-futures-a-walkthrough/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>clj-web-crawler &#8211; Web Crawling tool in clojure</title>
		<link>http://techbehindtech.com/2010/07/07/clj-web-crawler-web-crawling-tool-in-clojure/</link>
		<comments>http://techbehindtech.com/2010/07/07/clj-web-crawler-web-crawling-tool-in-clojure/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 07:22:32 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[crawler]]></category>
		<category><![CDATA[libraries]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=77</guid>
		<description><![CDATA[I was looking for a simple web crawler in clojure and came across clj-web-crawler (http://github.com/heyZeus/clj-web-crawler) . It took me less than 2 minutes to get started. (thanks to Leiningen) 1) In project.clj add these two lines for :dependencies 2) Run lein deps and you ready to play with clj-web-crawler. Checkout http://github.com/heyZeus/clj-web-crawler for more information Filed [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=77&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I was looking for a simple web crawler in clojure and came across clj-web-crawler (<a href="http://github.com/heyZeus/clj-web-crawler">http://github.com/heyZeus/clj-web-crawler</a>) . It took me less than 2 minutes to get started. (thanks to Leiningen)</p>
<p>1) In project.clj add these two lines for :dependencies</p>
<p>                <pre class="brush: plain;">
                 [com.jmeeks/clj-web-crawler &quot;0.1.0-SNAPSHOT&quot;]
                 [org.clojars.kjw/commons-httpclient &quot;3.1&quot;]	</pre></p>
<p>2) Run lein deps and you ready to play with clj-web-crawler.</p>
<p>Checkout <a href="http://github.com/heyZeus/clj-web-crawler">http://github.com/heyZeus/clj-web-crawler</a> for more information</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/crawler/'>crawler</a>, <a href='http://techbehindtech.com/tag/libraries/'>libraries</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/77/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/77/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/77/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=77&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/07/07/clj-web-crawler-web-crawling-tool-in-clojure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Leiningen Tips</title>
		<link>http://techbehindtech.com/2010/06/29/leiningen-tips/</link>
		<comments>http://techbehindtech.com/2010/06/29/leiningen-tips/#comments</comments>
		<pubDate>Tue, 29 Jun 2010 20:08:49 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[build]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Leiningen]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=73</guid>
		<description><![CDATA[Tip 1 : Adding License info To add your license info, add these following lines in project.clj Tip 2: Turning off auto delete of lib folder Tip 3: Turning on reflection warning calls Tip 4: Changing JVM level options Filed under: Clojure Tagged: build, clojure, Leiningen<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=73&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Tip 1 : Adding License info</strong></p>
<p>To add your license info, add these following lines in project.clj</p>
<p><pre class="brush: plain;">
:license {:name &quot;Eclipse Public License - v 1.0&quot;
          :url &quot;http://www.eclipse.org/legal/epl-v10.html&quot;
          :distribution :repo
          :comments &quot;same as Clojure&quot;}
</pre></p>
<p><strong>Tip 2: Turning off auto delete of lib folder</strong></p>
<p><pre class="brush: plain;">:disable-implicit-clean true</pre></p>
<p><strong>Tip 3: Turning on reflection warning calls</strong></p>
<p><pre class="brush: plain;">:warn-on-reflection true</pre></p>
<p><strong>Tip 4: Changing JVM level options</strong></p>
<p><pre class="brush: plain;">:jvm-opts &quot;-Xmx1g&quot;</pre></p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/build/'>build</a>, <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/leiningen/'>Leiningen</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/73/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=73&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/06/29/leiningen-tips/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
		<item>
		<title>Parsing XML in Clojure</title>
		<link>http://techbehindtech.com/2010/06/25/parsing-xml-in-clojure/</link>
		<comments>http://techbehindtech.com/2010/06/25/parsing-xml-in-clojure/#comments</comments>
		<pubDate>Fri, 25 Jun 2010 13:57:46 +0000</pubDate>
		<dc:creator>Siva Jagadeesan</dc:creator>
				<category><![CDATA[Clojure]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">https://sivajag.wordpress.com/?p=68</guid>
		<description><![CDATA[Problem : We need to parse a xml string and be able to query using xpath style tag list. Ex : I need a function that can do this, returns &#8220;Siva&#8221; Solution : To parse and query xml we need to do these following three things in clojure. 1) Convert xml string (file) to Struct [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=68&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Problem :</strong></p>
<p>We need to parse a xml string and be able to query using xpath style tag list.</p>
<p>Ex :</p>
<p><pre class="brush: xml;">
&lt;friends&gt;
  &lt;person&gt;
   &lt;name&gt;Siva&lt;/name&gt;
  &lt;/person&gt;
&lt;/friends&gt;
</pre></p>
<p>I need a function that can do this,</p>
<p><pre class="brush: plain;">
(get-value xml :person :name)
</pre></p>
<p>returns &#8220;Siva&#8221;</p>
<p><strong>Solution :</strong></p>
<p>To parse and query xml we need to do these following three things in clojure.</p>
<p><strong><em>1) Convert xml string (file) to Struct Map</em></strong></p>
<p>Clojure core comes with a build in xml library (clojure.xml <a href="http://clojure.github.com/clojure/clojure.xml-api.html">http://clojure.github.com/clojure/clojure.xml-api.html</a>) that has a parse function which takes in InputStream and returns a struct map that represents xml.</p>
<p><pre class="brush: plain;">
(defn get-struct-map [xml]
  (let [stream (ByteArrayInputStream. (.getBytes (.trim xml)))]
    (xml/parse stream)))
</pre></p>
<p><pre class="brush: plain;">
user&gt; (get-struct-map xml)
{:tag :friends, :attrs nil, :content [{:tag :person, :attrs nil, :content [{:tag :name, :attrs nil, :content [&quot;Siva&quot;]}]}]}
</pre></p>
<p>This struct map is cumbersome to query.</p>
<p><strong><em>2) Convert Struct Map to Zipper Data Structure</em></strong></p>
<p>&#8220;A zipper is a technique of representing an aggregate data structure so that it is convenient for writing programs that traverse the structure arbitrarily and update its contents, especially in purely functional programming languages.&#8221; <a href="http://en.wikipedia.org/wiki/Zipper_%28data_structure%29">http://en.wikipedia.org/wiki/Zipper_%28data_structure%29</a></p>
<p>To make it easy for us to traverse we will change struct map to zipper data structure. Clojure comes with zip library ( it is short form for zipper ) <a href="http://clojure.github.com/clojure/clojure.zip-api.html">http://clojure.github.com/clojure/clojure.zip-api.html</a></p>
<p>We will this zip library to convert xml struct map to zipper data structure.</p>
<p><pre class="brush: plain;">
user&gt; (clojure.zip/xml-zip xml-struct)
[{:tag :friends, :attrs nil, :content [{:tag :person, :attrs nil, :content [{:tag :name, :attrs nil, :content [&quot;Siva&quot;]}]}]} nil]
</pre></p>
<p><em><strong>3) Use Zip-filter library and query zipper data structure.</strong></em></p>
<p>Now that we have our xml in zipper data structure we could use zip-filter library that is present in clojure.contrib. <a href="http://clojure.github.com/clojure-contrib/zip-filter-api.html">http://clojure.github.com/clojure-contrib/zip-filter-api.html</a></p>
<p><pre class="brush: plain;">user&gt; (clojure.contrib.zip-filter.xml/xml-&gt; zipper-struct :person :name)
(&quot;Siva&quot;)
</pre></p>
<p>Putting this altogether</p>
<p><pre class="brush: plain;">
(ns com.sivajag.utils.xml
  (:import (java.io ByteArrayInputStream))
  (:require [clojure.xml :as xml])
  (:require [clojure.zip :as zip])
  (:require [clojure.contrib.zip-filter.xml :as zf]))

(defn get-struct-map [xml]
  (if-not (empty? xml)
    (let [stream (ByteArrayInputStream. (.getBytes (.trim xml)))]
      (xml/parse stream))))

(defn get-value [xml &amp; tags]
  (apply zf/xml1-&gt; (zip/xml-zip (get-struct-map xml)) (conj (vec tags) zf/text)))

user&gt; (get-value xml :person :name)
&quot;Siva&quot;</pre></p>
<p>Happy Coding!!!</p>
<br />Filed under: <a href='http://techbehindtech.com/category/clojure/'>Clojure</a> Tagged: <a href='http://techbehindtech.com/tag/clojure-2/'>clojure</a>, <a href='http://techbehindtech.com/tag/code/'>code</a>, <a href='http://techbehindtech.com/tag/snippet/'>snippet</a>, <a href='http://techbehindtech.com/tag/xml/'>xml</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sivajag.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sivajag.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sivajag.wordpress.com/68/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=techbehindtech.com&amp;blog=11954221&amp;post=68&amp;subd=sivajag&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://techbehindtech.com/2010/06/25/parsing-xml-in-clojure/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/830d93e32e7b0d8cf936355136fd0b43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">sivajag</media:title>
		</media:content>
	</item>
	</channel>
</rss>
