<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc=" http://purl.org/dc/elements/1.1/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>briancarper.net (λ) (Tag: Compojure)</title><link>http://briancarper.net/tag/94/compojure</link><description>Some guy's blog about programming and Linux and cows.</description><item><title>New blog engine up and running</title><link>http://briancarper.net/blog/542/new-blog-engine-up-and-running</link><guid>http://briancarper.net/blog/542/new-blog-engine-up-and-running</guid><pubDate>Wed, 23 Jun 2010 15:48:24 -0700</pubDate><description>&lt;p&gt;Well, my new blog is up and running.  Sorry for the temporary lack of cows in my layout.  I'm dogfood-testing the blog engine in a fairly vanilla state until I work out some of the bugs.  This layout is based upon &lt;a href=&quot;http://shaheeilyas.com/archives/barecity/&quot;&gt;barecity&lt;/a&gt;, a minimalist Wordpress theme that I adapted easily enough to my blog.&lt;/p&gt;

&lt;p&gt;As a bonus, I applied a dirty hack to my RSS feed that I think should help avoid screwing up people's RSS readers with duplicate entries.&lt;/p&gt;

&lt;p&gt;I'll write again soon with some info about the blog engine and some things I learned writing it.&lt;/p&gt;

&lt;p&gt;(As mentioned previously, &lt;a href=&quot;http://github.com/briancarper/cow-blog/tree/0.2.0&quot;&gt;here's the code&lt;/a&gt;.)&lt;/p&gt;</description></item><item><title>Breaking links is easy to do</title><link>http://briancarper.net/blog/breaking-links-is-easy-to-do</link><guid>http://briancarper.net/blog/breaking-links-is-easy-to-do</guid><pubDate>Tue, 22 Jun 2010 23:23:27 -0700</pubDate><description>&lt;p&gt;I apologize in advance to everyone who subscribes to my blog's RSS feed, but this week your RSS reader is probably going to suddenly find 25 &quot;new&quot; posts from me.&lt;/p&gt;

&lt;p&gt;My blog currently uses &lt;code&gt;/blog/title&lt;/code&gt; as the URL scheme, with similar URLs for categories and tags etc.  Soon, I'm probably going to change it to &lt;code&gt;/blog/123/title&lt;/code&gt;, as part of the impending release of version 0.2 of my blog engine.  (The code-in-progress is in a &lt;a href=&quot;http://github.com/briancarper/cow-blog/tree/0.2.0&quot;&gt;branch on github&lt;/a&gt;, for the daring and foolish among you.)&lt;/p&gt;

&lt;p&gt;This way, I can change the title of a post without breaking everything.  I have heretofore lacked this ability.  It's easy to code, you just tell Compojure to ignore everything after the number in a route.  Something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defroutes foo
  (GET [&quot;/blog/:id:etc&quot; :id #&quot;\d+&quot; :etc #&quot;(/[^/]*)?&quot;] [id]
    (pages/post-page id)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It's only a few lines of code to change, but the ramifications are widespread.  It'll instantly break every link to my blog, for example.  At least it's pretty easy to set up a bunch of redirects in Compojure to avoid that.  I think this'll work:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(require (blog [db :as db]
               [link :as link])
         (oyako [core :as oyako])
         (ring.util [response :as response]))

(defn redirect-post [name]
  (when-let [post (oyako/fetch-one db/posts :url name)]
    (response/redirect (link/url post))))

(defroutes redirect-routes
  (GET [&quot;/blog/:name&quot; :name #&quot;[^/]+$&quot;] [name]
    (redirect-post name)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(&lt;a href=&quot;http://github.com/briancarper/oyako&quot;&gt;Oyako&lt;/a&gt; here is the experimental ORM-like library I'm using to interface with PostgreSQL nowadays, having ditched Tokyo Cabinet.)&lt;/p&gt;

&lt;p&gt;Changing my URL scheme is also going to mess up RSS though, because I (foolishly) used post URLs as the GUIDs in my RSS feed up to this point.  This problem I don't know how to avoid.  I might reduce the number of posts included in my feed temporarily, to limit the damage.&lt;/p&gt;</description></item><item><title>Deploying Clojure websites</title><link>http://briancarper.net/blog/deploying-clojure-websites</link><guid>http://briancarper.net/blog/deploying-clojure-websites</guid><pubDate>Mon, 04 Jan 2010 20:42:17 -0800</pubDate><description>&lt;p&gt;On my server I'm running one Java process, which handles four of my websites on four different domains.  These are all running on Clojure + Compojure.  Some people asked for details of how to do this, so here's a rough outline.  For the sake of brevity I'm only going to talk about two domains here, though it scales up to however many you want pretty easily.&lt;/p&gt;

&lt;p&gt;This is surely not the only way to do this, and probably not the best way, but it's what I've arrived at after a year of goofing off.&lt;/p&gt;

&lt;p&gt;Summary: Emacs + SLIME + Clojure running in GNU Screen; all requests are handled by Apache and &lt;code&gt;mod_proxy&lt;/code&gt; sends them to the appropriate Jetty instance / servlet.&lt;/p&gt;

&lt;!--more Lots of fun details follow --&gt;

&lt;h1&gt;Directory structure&lt;/h1&gt;

&lt;p&gt;First you have to decide on a directory structure.  There's a sort of Clojure convention to have a &lt;code&gt;src&lt;/code&gt; and &lt;code&gt;deps&lt;/code&gt; directory, though Clojure is so young that this convention may or may not stick.  Behold my ASCII line-art directory tree:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;~/public_html/base/
|
|----src/
|    |
|    |----common/
|    |
|    |----net/
|         |
|         |----briancarper/
|         |    |
|         |    |----&amp;lt;lots of .clj files&amp;gt;
|         |
|         |----ffclassic/
|              |
|              |----&amp;lt;lots of .clj files&amp;gt;
|
|----deps/
|    |
|    |----&amp;lt;lots of .jar files&amp;gt;
|
|----briancarper.net/
|    |
|    |----public/
|    |
|    |----db/
|    |
|    |----apache/
|
|----ffclassic.net/
|    |
|    |----public/
|    |
|    |----apache/
|
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;src&lt;/code&gt; holds the Clojure source code for all of my sites.  Java (therefore Clojure) forces your directory structure to match your namespaces, and traditionally people use domain names in reverse order for both.  Whether you like or dislike this convention, you must admit that if you're writing code that's actually going to be used to host websites on domains, the convention probably makes sense.  There are some utility libraries I wrote that I like to share between sites, so I put those in some &lt;code&gt;common&lt;/code&gt; namespace in their own directory.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;deps&lt;/code&gt; holds a bunch of &lt;code&gt;.jar&lt;/code&gt; files.  This includes &lt;code&gt;clojure.jar&lt;/code&gt;, &lt;code&gt;clojure-contrib.jar&lt;/code&gt;, &lt;code&gt;compojure.jar&lt;/code&gt;, &lt;code&gt;swank-clojure.jar&lt;/code&gt; (for SLIME), and all the Java libraries I use, like Jetty, a bunch of Apache Commons libraries, Tokyo Cabinet, Rhino and so on.  This means that all of my sites are sharing libraries, and therefore must be running the same version of Clojure and all other libraries.  So when I upgrade a library that one site is using, I must upgrade all the other sites.  This is sometimes a hassle, but it forces me not to be lazy.&lt;/p&gt;

&lt;p&gt;Then I have one more directory for each of my domains, for static files and such.  These directories have different subdirectories depending on how I'm running them.  For the sites that use Tokyo Cabinet, I have a &lt;code&gt;db&lt;/code&gt; directory to hold the database files.  On some sites I want to run a PHP or CGI script, so I have a directory for Apache to use.  All of them have a &lt;code&gt;public&lt;/code&gt; folder, from which Clojure serves images, JS and CSS files etc.&lt;/p&gt;

&lt;p&gt;Phil Hagelberg's recent &lt;a href=&quot;http://github.com/technomancy/leiningen&quot;&gt;Leiningen project&lt;/a&gt; can possibly help with some of this.  I don't use Lein but I may switch someday.&lt;/p&gt;

&lt;h1&gt;Emacs + SLIME + CLASSPATH setup&lt;/h1&gt;

&lt;p&gt;Building or installing Clojure and Emacs and SLIME and friends is beyond the scope of this blog post.  &lt;a href=&quot;http://github.com/technomancy/swank-clojure&quot;&gt;swank-clojure&lt;/a&gt; has come a long way in being auto-installable via ELPA nowadays, if you like.&lt;/p&gt;

&lt;p&gt;The most important thing is to set up &lt;code&gt;CLASSPATH&lt;/code&gt; correctly.  &lt;code&gt;src&lt;/code&gt; should be on the &lt;code&gt;CLASSPATH&lt;/code&gt;, as well as every &lt;code&gt;.jar&lt;/code&gt; file in &lt;code&gt;deps&lt;/code&gt;.  My &lt;code&gt;.emacs&lt;/code&gt; contains this, among other things:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(setq swank-clojure-classpath (list &quot;.&quot; &quot;./src&quot; &quot;./deps/*&quot;))
(setq swank-clojure-library-paths (list &quot;/usr/local/lib&quot;))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Java will take a glob and expand it to include every jar file in a directory, thankfully.  But this seems to happen right when you start Java, so to add a new &lt;code&gt;.jar&lt;/code&gt; to your &lt;code&gt;CLASSPATH&lt;/code&gt; you generally need to restart the JVM.  This is annoying, but oh well.&lt;/p&gt;

&lt;p&gt;If you AOT-compile your Clojure code you might also have a &lt;code&gt;classes&lt;/code&gt; folder on your classpath, but I don't bother.  You could also compile your whole site into its own &lt;code&gt;.jar&lt;/code&gt; file and use that.  I don't do this because I want to be able to edit my Clojure source files on the server if I need to. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;swank-clojure-library-paths&lt;/code&gt; is necessary for me because Tokyo Cabinet uses some C libraries.  You might not need it.&lt;/p&gt;

&lt;p&gt;Then when I start Emacs, I &lt;code&gt;M-x cd&lt;/code&gt; to the base folder and start SLIME there.  It'll find Clojure in &lt;code&gt;deps&lt;/code&gt; and give me a REPL.  If you can get this working, you're well on your way.&lt;/p&gt;

&lt;h1&gt;Clojure code&lt;/h1&gt;

&lt;p&gt;I have a file &lt;code&gt;server.clj&lt;/code&gt; for each domain, which are in charge of setting up and starting / stopping the servlets.  So in &lt;code&gt;src/net/briancarper/server.clj&lt;/code&gt; I have something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(ns net.briancarper.server
  (:use (compojure.http request servlet session routes)
        (compojure.server jetty)
        (compojure control)
        (net.briancarper ...)))  ;; lots of files containing the guts of the site

(defroutes some-routes ...)
(defroutes other-routes ...)

(defroutes all-routes
  some-routes
  other-routes)

(defserver blog-server
  {:port 8080 :host &quot;localhost&quot;}
  &quot;/*&quot; (servlet all-routes))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;src/net/ffclassic/server.clj&lt;/code&gt; is similar, except with different routes (obviously) and a different port for the servlet.  Note that we bind to &lt;code&gt;localhost&lt;/code&gt; here, so that people can't connect directly to port 8080 and bypass Apache.&lt;/p&gt;

&lt;p&gt;One of the routes should be set up to point to the proper &lt;code&gt;public&lt;/code&gt; folder.  Generally some catch-all route near the end of your list of routes, like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(GET &quot;/*&quot; (static-file (params :*)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;where this &lt;code&gt;static-file&lt;/code&gt; knows to serve files from &lt;code&gt;briancarper.net/public&lt;/code&gt;, and the other &lt;code&gt;server.clj&lt;/code&gt; for the other domains point to different directories.&lt;/p&gt;

&lt;p&gt;Compojure has the &lt;code&gt;compojure.http.helpers/serve-file&lt;/code&gt; function you can use to serve static files too.  I use my own function for various reasons.  Note that Compojure generally doesn't set any HTTP headers on your responses.  You should probably set some kind of cache control headers unless you want your users to re-download all of your image files and stylesheets every time they hit a new page.  You might also have to fiddle with &lt;code&gt;Content-Type&lt;/code&gt; sometimes, though Compojure is usually pretty good about guessing them.&lt;/p&gt;

&lt;p&gt;Note that Compojure's hands-off approach has its upsides too.  For example, I have a bunch of CSS files for my blog.  In Clojure, I read and concatenate all of those CSS files into one blob of text and have Clojure serve that as &lt;a href=&quot;http://briancarper.net/combined.css&quot;&gt;http://briancarper.net/combined.css&lt;/a&gt;.  &lt;code&gt;combined.css&lt;/code&gt; doesn't actually exist.  I do the same for JS.  This speeds up user requests quite a bit, without having to merge all the files on the filesystem.  I could further compactify them if I cared.&lt;/p&gt;

&lt;p&gt;If your Clojure app is handling arbitrary request URIs, you should be careful you aren't serving up &lt;code&gt;../../../../etc/passwd&lt;/code&gt; or something.  Pretty sure Apache protects you against this by default, but Compojure uses &lt;code&gt;compojure.http.helpers/safe-path?&lt;/code&gt; to test for it too if you use the built-in &lt;code&gt;serve-file&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Finally, for convenience, in the base directory I have a file called &lt;code&gt;server.clj&lt;/code&gt; which contains this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(ns server
  (:require [net.briancarper server]
            [net.ffclassic server]))

(defn go []
  (.start net.briancarper.server/blog-server)
  (.start net.ffclassic.server/ffclassic-server))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, to start everything, from a REPL:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user&amp;gt; (require 'server)
2010-01-04 18:10:50.046::INFO:  Logging to STDERR via org.mortbay.log.StdErrLog
net.briancarper.server.proxy$javax.servlet.http.HttpServlet$0
net.ffclassic.server.proxy$javax.servlet.http.HttpServlet$0
nil
user&amp;gt; (server/go)
2010-01-04 18:11:02.260::INFO:  jetty-6.1.15
2010-01-04 18:11:02.358::INFO:  Started SocketConnector@localhost:8080
2010-01-04 18:11:02.707::INFO:  jetty-6.1.15
2010-01-04 18:11:02.789::INFO:  Started SocketConnector@localhost:8087
nil
user&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;On the server (Apache)&lt;/h1&gt;

&lt;p&gt;To deploy this to my server I just &lt;code&gt;rsync&lt;/code&gt; it all over SSH.  On the server, I have Emacs and Java installed, as well as Apache and GNU Screen.&lt;/p&gt;

&lt;p&gt;Why Apache?  In case I want to run something that isn't Clojure, like webmail or some CGI script.  Plus it's easy to run Clojure as a non-priviledged user on a non-priviledged port, and have Apache forward requests to the proper servlet based on the domain in the request.  Apache is also nice for doing HTTPS.&lt;/p&gt;

&lt;p&gt;My Apache setup is a pretty standard Debian-ish setup.  You need &lt;code&gt;mod_proxy&lt;/code&gt; installed.  My Apache config for one domain looks a bit like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;VirtualHost *:80&amp;gt;
        ServerName ffclassic.net
        ServerAlias www.ffclassic.net

        &amp;lt;Directory /home/user/clj/ffclassic.net/apache/&amp;gt;
           AllowOverride All
           Order Allow,Deny
           Allow from all
        &amp;lt;/Directory&amp;gt;

        DocumentRoot /home/user/clj/ffclassic.net/apache/

        ProxyPass /foo !
        ProxyPass / http://localhost:8087/
        ProxyPassReverse / http://localhost:8087/
&amp;lt;/VirtualHost&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Yeah, that's about it.  By default, every request will be passed to Clojure.  The ports specified here should obviously match the ports you specify in your Clojure code for your servlets.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;ProxyPass /foo !&lt;/code&gt; tells Apache to handle requests to &lt;code&gt;http://ffclassic.net/foo&lt;/code&gt; itself rather than pass them to Clojure.  I override URIs on a case-by-case basis like this, to tell Apache to run whatever CGI or PHP scripts I need.&lt;/p&gt;

&lt;p&gt;One oddity of running a setup like this is that thanks to &lt;code&gt;mod_proxy&lt;/code&gt;, the &quot;remote address&quot; for every request is always going to be &lt;code&gt;127.0.0.1&lt;/code&gt; by the time they get to Clojure.  So if you want to see the IP address of your users, you have to do something like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn- ip [request]
  (or ((:headers request) &quot;x-forwarded-for&quot;)
      (:remote-addr request)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another oddity is that sometimes if Apache is running, and then I start Clojure, I have to restart Apache before it &quot;finds&quot; Clojure and starts forwarding traffic.  No big deal though.&lt;/p&gt;

&lt;p&gt;This is otherwise transparent from the Clojure end.&lt;/p&gt;

&lt;h1&gt;Starting it up&lt;/h1&gt;

&lt;p&gt;You probably want to SSH to your server, start a REPL, start your code running, and then log off the server.  There are various ways you can run keep Emacs running in the background.  You could run Emacs in server mode and attach to it with emacsclient.  I use GNU Screen because it's easy and I have other things running in Screen instances that I like to switch between.  So I start Screen, start Emacs, start SLIME, and start my site from there.  Then detach from Screen when I'm done.  It's easier than it sounds.&lt;/p&gt;

&lt;p&gt;Why SLIME and not a normal commandline REPL?  Because in Emacs I can patch the code easily on a function-by-function basis, among other things.  You can do this from a commandline REPL but not nearly as easily.  Emacs is a much nicer place to type than any command line.  When I need to make an update to the site or fix a bug, my workflow is typically:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Fix it locally on my test machine, make sure it works&lt;/li&gt;
&lt;li&gt;rsync the changed files to the server&lt;/li&gt;
&lt;li&gt;SSH to the server&lt;/li&gt;
&lt;li&gt;&lt;code&gt;screen -r&lt;/code&gt; to bring up Emacs&lt;/li&gt;
&lt;li&gt;Open the &lt;code&gt;.clj&lt;/code&gt; file(s) I changed&lt;/li&gt;
&lt;li&gt;&lt;code&gt;C-c C-c&lt;/code&gt; to recompile and reload the individual function(s) I changed, or &lt;code&gt;C-c C-k&lt;/code&gt; to recompile and load a whole &lt;code&gt;.clj&lt;/code&gt; file, or whatever.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;C-a d&lt;/code&gt; to detach from Screen&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I can do any database inspecting or fiddling I need to do from the REPL.  I can also do some live testing of the site or whatever else I want.  It's good for debugging.&lt;/p&gt;

&lt;p&gt;I've had Emacs running for months this way without having to restart it, it seems to work OK.&lt;/p&gt;

&lt;h1&gt;That's it&lt;/h1&gt;

&lt;p&gt;It's not that hard.  It's clearly more steps than dumping some PHP files into a directory and having them work.  But with Clojure, you get the benefit of a persistently running environment with a nice REPL interface, all in a nice fast multi-threaded JVM.  Plus you get to write all your code in Clojure instead of PHP.  In terms of fun and long-term maintenance costs, Clojure comes out way ahead in the end, for me anyways.&lt;/p&gt;</description></item><item><title>Clojure and Compojure to the rescue, again</title><link>http://briancarper.net/blog/clojure-and-compojure-to-the-rescue-again</link><guid>http://briancarper.net/blog/clojure-and-compojure-to-the-rescue-again</guid><pubDate>Sun, 03 Jan 2010 15:57:52 -0800</pubDate><description>&lt;p&gt;I haven't posted here much recently because I've been hacking on another recently-sort-of-completed website.  One of my favorite hobbies is old 8-bit video games.  The first thing I ever programmed was a &lt;a href=&quot;http://ffclassic.net&quot;&gt;website about Final Fantasy for the old NES&lt;/a&gt;, and I've fiddled with it for the past 10 years or so.&lt;/p&gt;

&lt;p&gt;A while back I decided to rewrite the whole thing using Clojure + Compojure with data in mysql.  This went really well.  I know lines of code isn't that great a metric, but it can give a rough estimate: this whole website is done in 3,400 lines of Clojure, which includes all of the HTML &quot;templates&quot; and the DB layer I had to write.  And it's &lt;del&gt;turtles&lt;/del&gt; Clojure all the way down.  The only thing not written in Clojure are a couple bits of Javascript here and there and the stylesheet.&lt;/p&gt;

&lt;p&gt;I suspect the target audience of this blog and the target audience of that website don't overlap that much, but I figured someone might be interested in some of the detail of how it's implemented.  A few things I learned...&lt;/p&gt;

&lt;!--more Read on --&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;I didn't write a single line of HTML by hand.  I can't overemphasize how wonderful this is.  Compojure's HTML library lets you write HTML as Clojure data structures, with vectors being tags, keywords being tag names, hash-maps being attribute-value pairs etc.&lt;/p&gt;

&lt;p&gt;Not only is this easier to write, it's easy to generate and manipulate.  I have a ton of functions where given a list of hash-maps of data, it spits out a nicely formatted chart of that data.  Here's an example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(chart &quot;Armor&quot; (armor game)
       [&quot;&quot; #(name-with-image %)
        &quot;Locations&quot; (comp ulist location-links :locations)
        &quot;Buy&quot; (comp g :buy)
        &quot;Sell&quot; (comp g :sell)
        &quot;Absorb&quot; :abs
        &quot;Evade%&quot; (comp percent :ev)
        &quot;Element&quot; (comp ulist #(map :name %) :elements)
        &quot;Casts&quot; #(-&amp;gt; % :magic :name)
        &quot;Usable by&quot; (comp (partial equipable-by game ps) :pcs)])
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;chart&lt;/code&gt; is a function taking a chart title, some data, and then a vector of column-header names and functions for the data in each column.  Anonymous functions are a great way to format each column differently depending on the kind of data it contains.  &lt;code&gt;chart&lt;/code&gt; also does some other stuff like standardizing the text of the chart title, alternating the background color of rows of data, re-inserting the header every so often, and formatting the first column specially (expecting it to be a title) and so on.&lt;/p&gt;

&lt;p&gt;Sample output of this function is &lt;a href=&quot;http://ffclassic.net/nes/armor&quot;&gt;here&lt;/a&gt;.  A screenshot for the lazy (click for bigger version):&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;/random/ffclassic-armor.png&quot;&gt;&lt;img src=&quot;/random/thumbs/ffclassic-armor.png&quot; alt=&quot;Armor Page&quot; title=&quot;&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Who needs an ORM?  &lt;a href=&quot;http://briancarper.net/blog/clojure-orm-ish-stuff&quot;&gt;I wrote about this previously&lt;/a&gt;, but for my needs, an ORM is overkill.  The vast majority of my interaction with a DB is reading data.  All you need for that is an easy way to write SQL queries and get the results into a hash-map.  I wrote a bunch of macros for this, and there's &lt;a href=&quot;http://gitorious.org/clojureql&quot;&gt;ClojureQL&lt;/a&gt; and &lt;code&gt;clojure.contrib.sql&lt;/code&gt; and friends to help.  For example I run some polls that users can vote on, and here's the entirety of the code that fetches it out of the DB.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn polls []
  (with-tables [polls poll_options poll_votes]
    (map (fn [p] (assoc p
                   :total (count (:votes p))))
         (-&amp;gt; polls
             (one-to-many :options poll_options (key= :id :poll_id))
             (one-to-many :votes poll_votes (key= :id :poll_id))))))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;with-tables&lt;/code&gt; is a simple macro I wrote that fetches data from the DB for some table (possibly putting a &lt;code&gt;WHERE&lt;/code&gt; clause on the query if specified, unspecified here).  It takes care to run the minimal number of queries necessary, generally one query per table of data.  Then I use other functions like &lt;code&gt;one-to-many&lt;/code&gt; to join the data together.  The result is a list of hash-maps, with the value of some keys (here &lt;code&gt;:options&lt;/code&gt;, &lt;code&gt;:votes&lt;/code&gt;) being sub-lists of hash-maps, for data that &quot;belongs&quot; to the toplevel hash-map.&lt;/p&gt;

&lt;p&gt;Doing it this way helps me avoid the infamous &quot;N+1 queries&quot; which plagues naive use of Rails (where each of N objects would query the DB again to get its sub-lists of objects).  I think Rails uses an &lt;code&gt;:include&lt;/code&gt; option in its &lt;code&gt;find&lt;/code&gt; functions to do that same kind of thing.&lt;/p&gt;

&lt;p&gt;This is dirt-simple, but it gives me a lot of control.  I can easily &lt;code&gt;map&lt;/code&gt; or &lt;code&gt;filter&lt;/code&gt; over any of these intermediary table lists before or after putting the results together.  I can add keys with values that are calculated from other values, so it looks like the records have fields that don't really exist in the DB.  I can do a &lt;code&gt;sort-by&lt;/code&gt; on some key.  I can take a &lt;code&gt;user&lt;/code&gt; parameter and return different results based on whether that user is an admin or not.  I can put metadata on the hash-maps, e.g. to indicate which table the data was fetched from.  And so on.  &lt;/p&gt;

&lt;p&gt;Thanks to &lt;code&gt;memoize&lt;/code&gt; (see below) this is really fast too.  The most complicated query I have is for my walkthrough.  After priming the cache:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;net.ffclassic.db.charts&amp;gt; (time (dorun (walkthrough-chapters :nes)))
&quot;Elapsed time: 0.074587 msecs&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Speaking of metadata: I like metadata.&lt;/p&gt;

&lt;p&gt;For example I have a multimethod called &lt;code&gt;link&lt;/code&gt;, which dispatches on the &lt;code&gt;:table&lt;/code&gt; metadata key set from my SQL macros above, and outputs an appropriate link for something based on what it is.  So &lt;code&gt;(link some-user)&lt;/code&gt; links to a user's profile on the site, using the user's username as the anchor text, and styles it differently if it's an admin user or normal user.  &lt;code&gt;(link some-forum-post)&lt;/code&gt; links to the forum thread which contains the post.  &lt;code&gt;(link some-poll)&lt;/code&gt; links to a poll using the poll's title as the anchor.&lt;/p&gt;

&lt;p&gt;Each of these spits out a vector that looks like &lt;code&gt;[:a {:href &quot;/user/view-profile/1&quot;} &quot;Brian&quot;]&lt;/code&gt;.  And that's changed into HTML eventually via Compojure's delicious HTML library.&lt;/p&gt;

&lt;p&gt;This makes it really easy to link to things in a standard way with standard-looking anchor text.  It also makes it easy to standardize on a URL scheme.  If I want to change the URLs used to access my polls, I only need to change it in one place.&lt;/p&gt;

&lt;p&gt;This is kind of like OOP, but not really, since I can have different metadata tags and use different ones depending on what I'm doing.  And I can completely ignore the metadata whenever I don't need to use it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Speaking of multimethods: multimethods are handy.&lt;/p&gt;

&lt;p&gt;I have five &quot;categories&quot; of pages of data on my site, with pages in each category that are usually identical across categories.  But sometimes a page in one category should look slightly different from the same page in other categories.  Sometimes a page only belongs in one category and should 404 for the other categories.  What I needed was some way to say &quot;Display this page identically for each category by default, but page Y on category X is an exception&quot;.  &lt;/p&gt;

&lt;p&gt;Multimethods are great for this.  Compojure's &quot;routes&quot; take a request URI and dispatch based on a regex pattern matched against it.  I dispatch most requests to a series of multimethods.  Given a request URI, I split the URI into category + everything else.  Then, I first try a multimethod for category-specific pages, dispatching on a vector of &lt;code&gt;[category rest-of-uri]&lt;/code&gt;.  If there is no method for this, it falls through (returning &lt;code&gt;:next&lt;/code&gt;) and Compojure tries the next route.  The next route tries a multimethod for pages that look the same category-wide, dispatching only on &lt;code&gt;rest-of-uri&lt;/code&gt; this time.  If there's no method for that, it falls through again with &lt;code&gt;:next&lt;/code&gt; and a list of &quot;static&quot; routes are tried (oddball pages that don't belong to any category).  If those all fail, you get a 404.&lt;/p&gt;

&lt;p&gt;This is an easy way to split your site into namespaces based on the uri.  You can also add new pages without editing your Compojure routes.  Just add a new method to the multimethod.&lt;/p&gt;

&lt;p&gt;The code looks something like this:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;*code edited 2010-01-04 to fix a crapload of typos, thanks Shawn&lt;/em&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defmulti category-specific-page (fn [cat page] [(keyword cat) (keyword page)]))
(defmethod category-specific-page :default [&amp;amp; _] :next)
(defmethod category-specific-page [:cat1 :some-page] [cat page]
  (...))


(defmulti cross-category-page (fn [cat page] (keyword page)))
(defmethod cross-category-page :default [&amp;amp; _] :next)
(defmethod cross-category-page :some-page [cat page]
  (...))


(defroutes some-routes
  (GET #&quot;/(cat1|cat2|cat3)/([^/+])/*$&quot; (apply category-specific-page (:route-params request)))
  (GET #&quot;/(cat1|cat2|cat3)/([^/+])/*$&quot; (apply cross-category-page (:route-params request)))
  (GET &quot;/&quot; (default-index-page))
  (ANY &quot;/*&quot; (error-404))) 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This was a nightmare to do properly in Rails.  Rails wants to dispatch to controllers, which are classes. To make this work in Rails I had to mangle this concept to fit into the idea of a hierarchy of classes and subclasses.  There might have been an elegant way to do it, but I couldn't think of one.  I suspect someone will leave me a &lt;del&gt;flame&lt;/del&gt; comment telling me how to do it.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;memoize&lt;/code&gt; is great as a poor-man's web cache.  I have a bunch of pages of data that never change.  So the first request fetches it from the DB, and subsequent requests are cached in RAM and are therefore nearly instantaneous.  The data is cached in the form of huge lists of hash-maps (many of which have sublists of more hash-maps, sometimes many levels deep).  I was concerned at first that this might take a lot of RAM, but I went with it, and it turned out not to.    &lt;code&gt;top&lt;/code&gt; tells me:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
17   0  257m 127m  12m S    0 23.6  48:18.91 java 
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I'm actually running four websites in the same instance of the JVM there, so it's not that much RAM usage at all.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;memoize&lt;/code&gt; doesn't work for everything, obviously.  There's no easy way to invalidate or refresh the cache with the built-in &lt;code&gt;memoize&lt;/code&gt;, so it's not good for data that is updated frequently.  If you do need to invalidate some data, you have to re-compile the function.  But it works well for static data.  The great thing is that it's very fine-grained.  Change a single &lt;code&gt;defn&lt;/code&gt; to &lt;code&gt;defn-memo&lt;/code&gt; (in &lt;code&gt;clojure.contrib.def&lt;/code&gt;) and you're done.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Compojure's &quot;decorators&quot; are really quite nice.  For example I use them to implement a kind of templating / layout system.  I have a &lt;code&gt;with-layout&lt;/code&gt; function which, given a response, wraps the HTML for that response in a standard layout (header, sidebar, footer).  I group a bunch of routes together and decorate all of those routes with &lt;code&gt;with-layout&lt;/code&gt;, and then it's done.  This &quot;layout&quot; code is completely separate from the code the generates the HTML for the pages, and lets me change it easily (add a new layout for some specific pages, or whatever).  A bunch of other routes, like those that handle POST requests and such, don't get a layout; I just group those routes separately and don't decorate them.&lt;/p&gt;

&lt;p&gt;All of this is done with plain old Clojure functions.  There's no separate &quot;template library&quot;.  There's no ERB or Smarty to wrestle with, though you could use something like &lt;a href=&quot;http://www.stringtemplate.org/&quot;&gt;StringTemplate&lt;/a&gt; if you wanted to.&lt;/p&gt;

&lt;p&gt;Another example: certain pages are admin-only.  So I group all of those pages together into one group of routes, and do the admin check first-thing, immediately failing if someone isn't logged in or if the current user isn't an admin.  This thankfully lets me not have to worry about doing permissions checks all over the place.  The code looks like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn admin-only [handler]
  (fn [request]
    (when (:admin (:session request))
      (handler request))))


(defroutes admin-routes
  (GET &quot;/some-admin-only-page&quot; (admin-page))
  (GET &quot;/another-admin-only-page&quot; (other-admin-page)))


(defroutes admin-form-routes
  (POST &quot;/some-admin-only-page&quot; (mangle-database)))


(decorate admin-routes with-layout admin-only with-session)
(decorate admin-form-routes admin-only with-session)


(defroutes all-routes
  admin-routes
  admin-form-routes
  other-routes
  etc.)
&lt;/code&gt;&lt;/pre&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I'm overall pretty pleased with the site.  There are still some rough edges and much more work to be done, but it's a joy to code compared to the Rails version.&lt;/p&gt;</description></item><item><title>Blog and CRUD</title><link>http://briancarper.net/blog/blog-and-crud</link><guid>http://briancarper.net/blog/blog-and-crud</guid><pubDate>Sun, 12 Apr 2009 20:01:35 -0700</pubDate><description>&lt;p&gt;I updated my &lt;a href=&quot;http://github.com/briancarper/cow-blog/tree/master&quot;&gt;blog source code on github&lt;/a&gt;.  I also split my CRUD library out into its own &lt;a href=&quot;http://github.com/briancarper/clj-crud/tree/master&quot;&gt;clj-crud&lt;/a&gt; repo.  It is cruddy, so the name is apt.&lt;/p&gt;

&lt;p&gt;This code still isn't polished enough for someone to drop it on a server and fire it up, but maybe it'll give someone some ideas.  I think the new code is cleaner and it'll be easier for me to add features now.&lt;/p&gt;

&lt;p&gt;Beware bugs, I'm positive I introduced some.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;EDIT&lt;/strong&gt;: A word about the CRUD library... persisting data to disk is hard when the data may be mutated by many threads at once and the destination for your data is an SQL database that may or may not even be running.  I have more respect for people who've written libraries that actually do this kind of thing and work right.  Granted I only spent 3 days on mine but still, it's tricky.&lt;/p&gt;

&lt;p&gt;I gave up for a while and tried &lt;a href=&quot;http://github.com/duelinmarkers/clj-record/tree/master&quot;&gt;clj-record&lt;/a&gt;, but it was prohibitively slow.  It has the old N+1 queries problem when trying to select an object which has N sub-objects.  In real life you'd write SQL joins to avoid such things.  Ruby on Rails on the other hand gets around this via some nasty &lt;code&gt;find&lt;/code&gt; syntax.  &lt;/p&gt;

&lt;p&gt;I get around it by having all my data in a Clojure ref in RAM already so it doesn't matter.  And by using hooks so each object keeps a list of its sub-objects and the list is always up-to-date (updates of sub-objects propagate to their parents).  But the crap I have to do to get this to just barely work is pretty painful.&lt;/p&gt;</description></item><item><title>Blog source code released</title><link>http://briancarper.net/blog/blog-source-code-released</link><guid>http://briancarper.net/blog/blog-source-code-released</guid><pubDate>Fri, 27 Mar 2009 02:14:53 -0700</pubDate><description>&lt;p&gt;By popular demand, I've released the source code for my blog.  Hope someone finds it useful.&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://github.com/briancarper/cow-blog/tree/master&quot;&gt;http://github.com/briancarper/cow-blog/tree/master&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feedback and bug reports welcome, email me or post them somewhere on my blog and I'll find them.&lt;/p&gt;</description></item><item><title>Anti-spam field still holding</title><link>http://briancarper.net/blog/anti-spam-field-still-holding</link><guid>http://briancarper.net/blog/anti-spam-field-still-holding</guid><pubDate>Mon, 23 Mar 2009 19:38:27 -0700</pubDate><description>&lt;p&gt;So far my silly anti-spam measures are working.  Since last week I've had 1861 spam comment attempts, of which 0 were successful.  1857 of them didn't even alter the text my the captcha text field at all.  Four of them inexplicably HTML-escaped the &lt;code&gt;&amp;lt;&lt;/code&gt; into a &lt;code&gt;&amp;amp;lt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;One feature I didn't implement from Wordpress is subscribing to comments via email.  Sending an email from Java is possible but a little bit painful to implement.  The Javamail API is a monster.&lt;/p&gt;

&lt;p&gt;I do think it's useful to be able to know when someone responds to comment you left, but is spamming your inbox really the best way?  I have to think there's a better way.&lt;/p&gt;

&lt;p&gt;I did implement an RSS feed for each individual post's comments.  And separate RSS feeds for all the tags on my blog, and all the categories.  When RSS feeds are generated dynamically, why not?  This is all of the code for the tag feeds:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(defn tag-rss [tagname]
  (if-let [tag (get-tag tagname)]
    (rss
        (str &quot;briancarper.net Tag: &quot; (:name tag))
        (str &quot;http://briancarper.net/&quot; (:url tag))
        &quot;briancarper.net&quot;
        (map rss-item (take 25 (all-posts-with-tag tag))))
    (error-404 )))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Plus the routing code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(GET &quot;/feed/tag/:name&quot; (tag-rss (route :name)))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But I haven't uploaded the comment-feed feature because I don't know if it's overkill.  Personally I am liberal with my RSS feeds, I just pop them into my Akregator and off I go.  But I don't know if other people take their feeds more seriously, or what.  RSS feeds can be a bit heavyweight.  Maybe I should make a feed for all of my comments across all posts.&lt;/p&gt;</description></item><item><title>Blog is still going strong</title><link>http://briancarper.net/blog/blog-is-still-going-strong</link><guid>http://briancarper.net/blog/blog-is-still-going-strong</guid><pubDate>Wed, 18 Mar 2009 22:01:11 -0700</pubDate><description>&lt;p&gt;After I implemented that silly CAPTCHA yesterday, the spam was stopped.  There's also a honeypot form field (it's hidden via CSS so humans don't know it's there, and if any bot POSTs text for that field, the data is rejected automatically).  It's silly and easily defeated, yet it stopped all 262 spam attempts since yesterday.  It looks like all the spam is for one site, but it's coming from a huge range of IPs.  So it's probably a botnet.  Thanks, MS Windows!&lt;/p&gt;

&lt;p&gt;I rewrote my whole CRUD layer so that I could use it for more than one database at once, and then rewrote my gallery code to take advantage, and now two hours later I have my &lt;a href=&quot;http://origamigallery.net&quot;&gt;origami gallery&lt;/a&gt; back up and running.  Both sites are running from the same JVM.  I wonder how many sites I can have going at once before the server melts into a puddle of Java-inflicted goo.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  PID PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
11338 16   0  512m 128m  12m S    0  0.3   0:28.33 java
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Good thing I have plenty of RAM on the server.  From looking at before and after shots of the memory usage, 66 MB is the JVM itself, and 40MB more is Jetty and Compojure and my code and all the dependencies.  Then the last ~20 MB or so is my database slurped into RAM.  So I can probably fit another few tens of thousands of posts and comments in here before I have to worry much.  The real test will be letting this thing run for a couple weeks and see how hard it leaks.&lt;/p&gt;</description></item><item><title>Fun with HTTP headers</title><link>http://briancarper.net/blog/fun-with-http-headers</link><guid>http://briancarper.net/blog/fun-with-http-headers</guid><pubDate>Tue, 17 Mar 2009 22:14:10 -0700</pubDate><description>&lt;p&gt;One fun thing about playing with Compojure is that it doesn't do much with HTTP headers for you, which is a good learning opportunity.  &lt;a href=&quot;http://tools.ietf.org/html/rfc2616&quot;&gt;RFC 2616&lt;/a&gt; is rather helpful here.&lt;/p&gt;

&lt;p&gt;For example I learned that if you don't set a &lt;code&gt;Cache-Control&lt;/code&gt; or &lt;code&gt;Expires&lt;/code&gt; header, your browser will happily re-fetch files over and over, which is a bit of performance hit.  Static files that don't change often like images etc. can be set with a higher &lt;code&gt;Expires&lt;/code&gt; value so they're cached.&lt;/p&gt;

&lt;p&gt;Another thing to keep in mind (note to self) is that using &lt;a href=&quot;http://httpd.apache.org/docs/2.0/mod/mod_proxy.html&quot;&gt;mod_proxy&lt;/a&gt; to forward traffic to a local Jetty server means that the &quot;remote IP&quot; you get from &lt;code&gt;(.getRemoteAddr request)&lt;/code&gt; will always be &lt;code&gt;127.0.0.1&lt;/code&gt;.  If you want the user's real remote IP, you have to look in the &lt;code&gt;X-Forwarded-For&lt;/code&gt; header (easily accessed as &lt;code&gt;(:x-forwarded-for headers)&lt;/code&gt; in Compojure.  Given that &lt;a href=&quot;http://en.wikipedia.org/wiki/Identicon&quot;&gt;Identicons&lt;/a&gt; are generated from a hash of an IP address, this has resulted in some screwed up (wrongly identical) avatars for a bunch of people in posts for the past couple days.  Oops.  Not much I can do to fix that now.&lt;/p&gt;

&lt;p&gt;In other non-news, I just the spam logging for the blog so I can see the kinds of things bots are doing to get around my feeble anti-spam measures.  Sadly the spam seems to have stopped entirely, right after I set this up.  How annoying.&lt;/p&gt;</description></item></channel></rss>

