<?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/"
	>

<channel>
	<title>Paul Legato &#187; Java</title>
	<atom:link href="http://www.paullegato.com/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.paullegato.com</link>
	<description></description>
	<lastBuildDate>Tue, 06 Dec 2011 00:52:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Android or iPhone Development?</title>
		<link>http://www.paullegato.com/blog/android-iphone-development/</link>
		<comments>http://www.paullegato.com/blog/android-iphone-development/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 20:28:40 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=381</guid>
		<description><![CDATA[Which platform should I target first? iPhone, for now, though it's close. Android cannot (yet) provide the same level of developer tools or paying user base, the Android emulator can't handle graphics, and I already own an iPhone. I do expect that Android's competitive position will improve significantly over the next few years, but it's not there yet.]]></description>
			<content:encoded><![CDATA[<p>Android or iPhone? Which platform should I target first? iPhone, for now, though it&#8217;s close. Android cannot (yet) provide the same level of developer tools or paying user base, the Android emulator can&#8217;t handle graphics, and I already own an iPhone. I do expect that Android&#8217;s competitive position will improve significantly over the next few years, but it&#8217;s not there yet.<span id="more-381"></span></p>
<h2>iPhone Pros</h2>
<ul>
<li><strong>iPhones are all (almost) exactly the same.</strong> 4th generation iPhones do support an optional higher screen resolution than previous models, but they&#8217;re 100% binary backwards compatible. This is a trivial difference when put up against the <a href= "https://secure.wikimedia.org/wikipedia/en/wiki/Comparison_of_Android_devices"> dozens of different Android devices</a> available with radically different hardware, and the <a href= "http://developer.android.com/guide/practices/screens_support.html"> hoops that you as a developer have to jump through</a> to make sure your app runs correctly on all of them.</li>
<li><strong>Large, high-end user base that demonstrably spends money on apps.</strong> iPhone users have already shown their willingness to buy large numbers of apps; Android users, not so much. This seems to be slowly changing over time as the Android app store matures, but for now, iPhone is still the cash cow.  </li>
<li><strong>Beautiful and well-designed UI and system architecture.</strong> iPhones have been designed as an integrated and coherent experience. Apple&#8217;s renowned mastery of intuitive human-computer interaction is evident at every step while using the device. There is an overall (and well documented) unifying strategic vision of how different subsystems should fit together seamlessly and present a unified interface to the user. Their development libraries have been designed to support this theme at every level. Android, by contrast, reads much more like KDE or Gnome; it was bolted together out of disparate pieces written by different groups working in isolation with minimal coordination. Perceived technical coolness from the perspective of a software engineer who is already intimately familiar with the system&#8217;s internals took precedent over usability. Android&#8217;s user interface is generally much uglier and much less intuitive.</li>
<li><strong>iPhones support low latency audio.</strong> Android uses ALSA internally, which does support low-latency audio, but the low-latency API is not exposed to developers, and <a href= "https://code.google.com/p/android/issues/detail?id=3434">Google does not seem to be interested in fixing this</a>. Android latency is unacceptably high for realtime sound synthesis unless you hack it and use the ALSA API, which is officially forbidden and in any case could change significantly and without warning between Android operating system updates and between phones. iPhone, on the other hand, has an <a href= "http://developer.apple.com/library/ios/#codinghowtos/AudioAndVideo/index.html#PLAYBACK-MINIMIZE_PLAYBACK_LATENCY"> officially supported low latency audio API</a>, and there are many successful realtime sound synthesizer apps in the app store.</li>
<li><strong>XCode.</strong> XCode is a really well done IDE. I normally don&#8217;t like IDEs. I normally use Emacs for everything. But, in all fairness, I decided to give XCode and Eclipse with the Android plugins a shot. Eclipse is nice, but a little rough around the edges. I ran into a few bizarre IDE error messages while developing my Android test projects that required extensive Googling and hours of experimentation to unravel. XCode, as one would expect from a flagship Apple product, is immaculately polished and completely integrated from top to bottom.</li>
</ul>
<h2>iPhone cons</h2>
<ul>
<li> <strong>Objective C.</strong> While Objective C was really cool and innovative in 1988, today it seems archaic. Nobody uses it except Apple. It&#8217;s laden with tons of cruft. It still feels like it&#8217;s a bolt-on afterthought preprocessor for a C compiler. For example:</p>
<ul>
<li><a href= "http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Articles/ocSelectors.html"><strong>Selectors</strong></a>: you can&#8217;t refer to method names directly; you have to use the special <code>@selector()</code> compiler directive to look up their index number. This probably made great sense when CPUs were very slow and doing a lookup in an ASCII table was a significant performance hit over doing an integer offset jump, but on modern computers, this is just annoying. CPU time is cheaper than engineer time.</li>
<li>
<p><strong>Manual reference-counted memory management is an obsolete and extremely fragile pain in the ass.</strong> Lisp had GC ~40 years ago. The vast set of problems introduced by manual memory management, such as buffer overflows and memory leaks, is just not worth the small gain in efficiency that you get from not periodically running a garbage collector. Again, CPU time is cheaper than engineer time. Android does GC on a phone just fine, so I don&#8217;t buy the argument that a phone can&#8217;t support that kind of overhead. Garbage collection was recently introduced for the Mac OS X desktop system, but is as of yet not available on the iPhone.</p>
<p>(I&#8217;m aware that C and C++ are widely used and both still make you do manual memory management, too. Far from regarding this as a vehicle for a macho display of programming prowess, I find manual memory management to be more of an annoyance, something that the computer should be handling for me automatically, much like how figuring out the exact memory address of a function was automated long ago and is no longer something we as application-level programmers ever need to worry about much.)</p>
</li>
<li><a href= "http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html#//apple_ref/doc/uid/TP30001163-CH12-DontLinkElementID_66"><strong>The use of <code>+</code> and <code>-</code> to mark methods as class or instance methods.</strong></a> Principle of least surprise; why not just use, say, the English word <code>class</code> or <code>static</code> or something to that effect to designate class methods, and leave instance methods unmarked? Perhaps using 1 character symbols rather than entire English words as the token improved compile times on large, complex projects in the &#8217;80s, but the time savings is infinitesimal on a modern computer, so I&#8217;ll vote for obviousness and clarity rather than crypticity.</a></li>
<li><strong>The use of [] (square brackets) for message passing, and the requirement for named (but non-reorderable) arguments.</strong>
<p>Perhaps this was done out of a well-intentioned effort to make the programmer notice that these are messages and not function calls or C++ methods, and to make the code self-documenting. I find the introduction of new syntax rather unwarranted and distracting. I&#8217;d much prefer the familiar <code>object.message(argument1, argument2)</code> over the verbose and unwieldly <code>[object message:argument1 parameterName:argument2]</code>. You can&#8217;t even re-order the named arguments, so including the argument name is just noise in the code. I guess I&#8217;ve been spoiled by Clojure and Lisp, where there&#8217;s almost no syntax.</p>
<p>If they really felt strongly about the need to pedantically differentiate messages from function calls or methods at the syntax level, they should at least have retained the general function/method syntactic template and chosen a different separator character, so as to enable programmers to re-use most of their neural syntax parsing circuitry rather than force us to introduce an entirely new syntactic template that performs only 1 task. For example, a more intuitive syntax that still emphasizes the fact that this is not a function or method call could be something like <code>object#message(argument1, argument2)</code> or <code>object<-message(argument1, argument2)</code>.
 </ul>
</li>
<li><strong>Closed platform.</strong> The source code to the vast Cocoa library is proprietary. You can develop with things Apple tells you you may develop with, and nothing else. They only recently <a target="_blank" href="http://www.macrumors.com/2010/09/09/apple-opens-app-store-to-third-party-development-tools-publishes-review-guidelines/" >relaxed the restriction on using any third party tools</a> at all. <a target="_blank" href="https://encrypted.google.com/search?q=iphone+cpu+java" >The iPhone's CPU is widely reported to have built-in hardware level Java bytecode support</a>, but that's off-limits. </li>
<li><strong>Vendor lock-in.</strong> This is a huge and obvious minus for the iPhone. Your ability to generate revenue is 100% dependent upon Apple's whims, upon remaining in Apple's good graces. Uncountable horror stories circulate online about developers who invested months and many thousands of dollars into a project only to have it rejected by Apple, often after a considerable delay and with little or no explanation.</li>
</ul>
<h2>Android pros</h2>
<ul>
<li><strong>Java (almost).</strong> Android apps are written in Java. (Well, technically not in Java due to licensing issues, but in a language that is 99.9% the same as Java.) If you already know Java, as I do, this is a big plus. You can easily re-use your code elsewhere, on any platform, with minor or no modifications. Objective C code is rather limited in what you can do with it: you can re-use it in your Apple desktop apps. (Yes, there is a free GNU Objective C compiler, but almost all real-world Objective C code is locked into Apple's proprietary Cocoa runtime system.)</li>
<li><strong>A JVM, almost.</strong> Android doesn't run a true JVM, unfortunately, as part of a licensing dispute between Google and Sun, but it's close. Android's <a target="_blank" href="http://en.wikipedia.org/wiki/Dalvik_(software)" >Dalvik</a> is a cleanroom reimplementation of part of Java, designed to avoid triggering what Google regards as onerous licensing fees for the use of a true JVM on a mobile handset. In any case, it's close enough that the door is open to potentially running Clojure and other JVM languages on it someday.</li>
<li><strong>No upfront developer fees. Develop for free.</strong> You can download the SDK and go nuts, upload your code to a real handset to test, send your apps to the app store for sale, whatever. There is no $99 developer tax.  </li>
<li><strong>Larger ultimate user base.</strong> Android phones are now outselling iPhones, and this trend looks set to continue. The price you pay is coding for 200 slightly different handsets.</li>
<li><strong>Open source platform.</strong> Most of the Android system is freely available, precluding vendor lock-in, at least in theory.</li>
</ul>
<h2>Android cons</h2>
<ul>
<li><strong>Android emulator lacks hardware accelerated graphics.</strong> This is a big minus. I made a very simple bouncing-ball demo with <a target="_blank" href="http://www.rokonandroid.com/" >Rokon</a> that got about 6 or 7 fps in the emulator. Full games often take multiple seconds per frame, completely unusable. If you want to write games (or anything else where graphical performance is key), you absolutely need to have a hardware handset from the start. If you don't already own an Android phone anyway, this means you have to invest hundreds of dollars upfront, just to see if the platform is for you.</li>
<li><strong>Lack of interest from Google.</strong> Google has many, many pots cooking at once. While they do devote significant resources to Android's maintenance and expansion, it's nowhere near as important a product for them as the iPhone is for Apple, and you can tell. The iPhone is a core strategic product for Apple, whereas Android is a relatively minor satellite project for Google. Correspondingly, Apple's general support of the iPhone and its developers seems far better.  </li>
<li><strong>Relatively few libraries.</strong> For the moment, there seem to be more third party libraries available for the iPhone, and they seem to be more mature and robust than what's out there for Android. This will change in time, as more and more app developers begin to use Android. </li>
</ul>
<p>It was a close call. I did some exploratory coding on both platforms &mdash; there's no substitute for direct experience. Though I much prefer Java over Objective C as a language, the universe of extant Android libraries is much smaller and less mature. I may have been able to live with that in order to be able to code in Java and avoid Apple's vendor lock-in. In the end, the tipping point was practical: the Android emulator's lack of hardware accelerated graphics left me with an unusable framerate, so I'd have to spend hundreds of dollars on a handset to do even trivial demo development, whereas I already own an iPhone.</p>
<p>I'll be checking back in on Android periodically, as I expect its long-term position will improve substantially in time, but for now, I'm going with the iPhone.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=381&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/android-iphone-development/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Swing-Clojure GUI for the Black-Scholes Option Modeler</title>
		<link>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/</link>
		<comments>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 07:55:56 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[finance]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=352</guid>
		<description><![CDATA[Now that we have implemented Black-Scholes in Clojure, let&#8217;s make a Swing GUI for it. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we have implemented <a href="http://www.paullegato.com/blog/black-scholes-clojure/" >Black-Scholes in Clojure</a>, let&#8217;s make <a target="_blank" href="http://github.com/pjlegato/clojure_options" >a Swing GUI for it</a>. The Swing GUI will have text boxes for all the necessary inputs, and calculate prices and Greeks when the button is pressed. It&#8217;s a simple and straightforward way to get started in Swing GUI programming in Clojure. Here&#8217;s what it looks like. <a href="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" ><img src="http://www.paullegato.com/wp-content/uploads/2010/07/Swing-GUI-Clojure-Black-Scholes.png" alt="Screenshot of the Swing GUI for the Black-Scholes option modeler, implemented in Clojure" title="Swing-GUI-Clojure-Black-Scholes" width="569" height="355" class="alignright size-full wp-image-354" /></a></p>
<p>The GUI is written entirely in Clojure with the Swing toolkit. Calculation state is stored in a series of atoms. Watches are used to update the output table automatically when an atom changes, <a target="_blank" href="http://kotka.de/blog/2010/05/Decoupling_Logic_and_GUI.html" >an idea from Kotka</a>. I used the excellent <a target="_blank" href="http://www.miglayout.com/" >MiG Layout</a> for general layout functionality, and generic Swing widgets (JTextFields and a JTable) for the input and output.<br />
<span id="more-352"></span></p>
<h2>Clojure code</h2>
<p>The Black-Scholes GUI is launched with the<code>main</code> function. The Swing GUI is actually created in the <code>initialize-gui</code> function, but since <a target="_blank" href="http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html" >Swing widgets are not threadsafe</a>, we must use the <code>do-swing*</code> helper function from Clojure Contrib to spin off the real GUI creation code into the Swing event thread.</p>
<pre class="brush: clojure; title: ; notranslate">
(defn initialize-gui
  []
  (let [frame (JFrame. &quot;Black-Scholes Option Modeler&quot;)]

    (doto frame
      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (-&gt; .getContentPane
          (.add (miglayout (JPanel.)

                           (input-panel
                            (fn [_]
                              (do-swing
                               (doto frame
                                 (.setVisible false)
                                 (.dispose)))))

                           (result-table)

                           )))

      (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE)
      (.pack)
      (.setVisible true))
     ))

(defn main
  []
  (do-swing* :now initialize-gui))
</pre>
<p>This is pretty straightforward. We make a (locally scoped) JFrame to be the main container at line 3. Within the context of the <code>let</code>, we add a JPane using MiG Layout to its content area (starting at line 8). The JPanel itself contains two subwidgets, which are those returned from the <code>input-panel</code> and <code>result-table</code> functions.</p>
<p>Note that we are passing an anonymous function to <code>input-panel</code> at line 11. The input panel contains the &#8220;Quit&#8221; button, and that button needs to know what to do when it&#8217;s pressed. We want it to close the GUI; that is, it should destroy the outer JFrame. To do that, it needs a reference to it. However, as a local variable in <code>initialize-gui</code>, the JFrame is not in scope elsewhere; we have to pass it in. The given function closes over the JFrame reference (line 13) and transports it to <code>input-panel</code>, where that function will be called as an event listener when the &#8220;Quit&#8221; button is pressed.</p>
<p>We could also have simply passed the bare JFrame rather than a function, and moved the frame-closing code into <code>input-panel</code>, but that would imply that the input panel must always be in a JFrame, which will not necessarily the case. Passing in an external anonymous function to be activated by the &#8220;Quit&#8221; button allows the input panel to be used generically in any sort of container, with the container deciding what to do when &#8220;Quit&#8221; is pressed.</p>
<h3>The Input Panel</h3>
<pre class="brush: clojure; title: ; notranslate">

(defn- input-panel [quit-action]
    (let [
          ;; Fields
          spot (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                 (.setColumns 6)
                 (.setValue @*spot*))

          strike (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                   (.setColumns 6)
                   (.setValue @*strike*))

          days-till-expiry (doto (JFormattedTextField. (NumberFormat/getIntegerInstance))
                             (.setColumns 6)
                             (.setValue @*days-till-expiry*))

          riskfree (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                     (.setColumns 6)
                     (.setValue @*riskfree*))

          volatility (doto (JFormattedTextField. (NumberFormat/getNumberInstance))
                       (.setColumns 6)
                       (.setValue @*volatility*))

          ;; Buttons
          calculate (JButton. &quot;Calculate&quot;)
          quit (JButton. &quot;Quit&quot;)
          ]

      (add-action-listener
       calculate
       (fn [_]
         (update-all-calculations
          (Double/parseDouble (.getText spot))
          (/ (Integer/parseInt (.getText days-till-expiry)) *trading-days-per-year*)
          (Double/parseDouble (.getText strike))
          (Double/parseDouble (.getText riskfree))
          (Double/parseDouble (.getText volatility)))))

      (add-action-listener
       quit
       quit-action)

      (miglayout (JPanel.)
                 :layout  [:wrap 2 ]

                 (JLabel. &quot;Spot&quot;) [:align &quot;right&quot;]
                 spot

                 (JLabel. &quot;Strike&quot;) [:align &quot;right&quot;]
                 strike

                 (JLabel. &quot;Risk-free rate&quot;) [:align &quot;right&quot;]
                 riskfree

                 (JLabel. &quot;Volatility&quot;) [:align &quot;right&quot;]
                 volatility

                 (JLabel. &quot;Days till expiry&quot;) [:align &quot;right&quot;]
                 days-till-expiry

                 calculate
                 quit)))
</pre>
<p>The input widgets are local variables in the input panel function, along with the two buttons. The widgets are initialized from the state atoms (which are then unused again; see discussion below.) The &#8220;Quit&#8221; button is given the event callback passed in as an argument (so it can manipulate the enclosing JFrame as per above.) The &#8220;Calculate&#8221; button is given an event callback that calls the <code>update-all-calculations</code> function with the values in the input widgets.</p>
<p>The lot are then stuffed into a JPanel with a MiG Layout and returned.</p>
<h3>The Output Table</h3>
<pre class="brush: clojure; title: ; notranslate">
(defn- update-cell
  &quot;Updates the given AbstractTableModel cell and fires a change event for that cell.&quot;
  [model data row col]
  (.setValueAt model data row col)
  (.fireTableCellUpdated model row col))

(defn- result-table []
  (let [
        column-names [&quot;&quot; &quot;Call&quot; &quot;Put&quot;]
        row-names [&quot;Price&quot; &quot;Delta&quot; &quot;Theta&quot; &quot;Rho&quot; &quot;Gamma&quot; &quot;Vega&quot;]
        table-model (proxy [AbstractTableModel] []
                      (getColumnCount [] (count column-names))
                      (getRowCount [] (count row-names))
                      (isCellEditable [] false)
                      (getColumnName [col] (nth column-names col))
                      (getValueAt [row col]
                                  (condp = col
                                      0 (nth row-names row) ;; Return the row name for column zero
                                      (condp = [row col]
                                          [0 1] @*call-price*
                                          [0 2] @*put-price*

                                          [1 1] @*call-delta*
                                          [1 2] @*put-delta*

                                          [2 1] @*call-theta*
                                          [2 2] @*put-theta*

                                          [3 1] @*call-rho*
                                          [3 2] @*put-rho*

                                          [4 1] @*gamma*
                                          [4 2] &quot;==&quot;

                                          [5 1] @*vega*
                                          [5 2] &quot;==&quot;

                                          nil))))

        table (doto (JTable. table-model)
                (.setGridColor java.awt.Color/DARK_GRAY))
        ]

    (add-watch *call-price* ::update-call-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 1)))
    (add-watch *put-price* ::update-put-price (fn [_ _ _ newprice] (update-cell table-model newprice 0 2)))

    (add-watch *call-delta* ::update-call-delta (fn [_ _ _ newval] (update-cell table-model newval 1 1)))
    (add-watch *put-delta* ::update-put-delta (fn [_ _ _ newval] (update-cell table-model newval 1 2)))

    (add-watch *call-theta* ::update-call-theta (fn [_ _ _ newval] (update-cell table-model newval 2 1)))
    (add-watch *put-theta* ::update-put-theta (fn [_ _ _ newval] (update-cell table-model newval 2 2)))

    (add-watch *call-rho* ::update-call-rho (fn [_ _ _ newval] (update-cell table-model newval 3 1)))
    (add-watch *put-rho* ::update-put-rho (fn [_ _ _ newval] (update-cell table-model newval 3 2)))

    (add-watch *gamma* ::update-gamma (fn [_ _ _ newval] (update-cell table-model newval 4 1)))
    (add-watch *vega* ::update-vega (fn [_ _ _ newval] (update-cell table-model newval 5 1)))

    ;; This shrinks the table's preferred viewport down to its actual size.
    ;; (The default is to make a huge viewport, even though the table is small.)
    (.setPreferredScrollableViewportSize table (.getPreferredSize table))

    (JScrollPane. table)
    ))
</pre>
<p>The output table itself is a standard JTable. Its model is initialized from the output state atoms. The watches at lines 44-57 are the most interesting part; they allow arbitrary code to be called when the output state atoms change. This allows the Black-Scholes calculation to happen independently of the output widget. When one of those atoms is changed, it self-updates automatically via the watches.</p>
<p>The helper function at lines 1-5 updates the appropriate model cell and fires an event to tell the JTable to repaint it.</p>
<p>The scrollable viewport business at line 61 is to work around a questionable Java design decision where a JTable, by default, tells its container to make its viewport enormous, even though it have very little data. (That&#8217;s not an error, that&#8217;s subjunctive.)</p>
<h2>Design considerations</h2>
<h3>GUI and business logic decoupling</h3>
<p>Above all, the GUI has to be decoupled from the model itself. Internal changes to one should never affect the other, and the two should be independently testable. In such a simple application, this was easy enough. A more complex app that requires several information round trips would be trickier. We now have a good foundation for such an app. No business calculations are performed in the GUI code namespace. The sole point of connection is in the update-all-calculations function:</p>
<pre class="brush: clojure; title: ; notranslate">

(defn- update-all-calculations [spot timeleft strike riskfree sigma]
  (swap! *call-price* (fn [_] (bs/call spot timeleft strike riskfree sigma)))
  (swap! *put-price* (fn [_] (bs/put spot timeleft strike riskfree sigma)))

  (swap! *call-delta* (fn [_] (bs/call-delta spot timeleft strike riskfree sigma)))
  (swap! *put-delta* (fn [_] (bs/put-delta spot timeleft strike riskfree sigma)))

  (swap! *call-theta* (fn [_] (bs/call-theta spot timeleft strike riskfree sigma)))
  (swap! *put-theta* (fn [_] (bs/put-theta spot timeleft strike riskfree sigma)))

  (swap! *call-rho* (fn [_] (bs/call-rho spot timeleft strike riskfree sigma)))
  (swap! *put-rho* (fn [_] (bs/put-rho spot timeleft strike riskfree sigma)))

  (swap! *vega* (fn [_] (bs/vega spot timeleft strike riskfree sigma)))
  (swap! *gamma* (fn [_] (bs/gamma spot timeleft strike riskfree sigma))))
</pre>
<h3>Atoms to hold state</h3>
<p>As we can see above, set of atoms holds state for the GUI, in keeping with the general Clojure principle of isolating state into transactional memory. (Actually, I cheated a bit. Our full state consists of the input values and the results of our Black-Scholes calculations. Although I created atoms for the input state values as well, I calculate the results directly from the widgets. It is a trivial exercise to alter the &#8220;Calculate&#8221; button callback to use the atoms. This would be more useful in the case where changes to a widget fire an event that triggers recalculation, which is not done in this demo as per below. I would use the atoms in a real application.)</p>
<p>I/O is inherently stateful, as are GUIs. There was therefore the temptation to use the Swing widget objects themselves as state-holders, and in fact it requires extra code to shuttle data back and forth between the widgets and the atoms. In such a simple app as this, using the GUI widgets as state-holders does not make much practical difference, but in a more complex app, a well designed set of state atoms and watches can automate much of the tedious GUI logic.</p>
<p>Using the widgets directly as state holders implies a tight coupling between the input widgets, the business logic, and the output widgets. Changing any one of them would invariably have required changes to the linking logic.</p>
<p>For example, suppose we were using widgets-as-state, and we changed the &#8220;days left till expiry&#8221; input to a slider rather than a text box, or suppose we wanted to read it from a file or from an API. We would have to update the code that reads it, calculates the model, and puts the results into the output table. Touching that code implies a non-zero likelihood of breaking it. Why even introduce the potential for breaking something that is unrelated to the task at hand, in this case the business logic and output code?</p>
<p>Again, this seems trivial with such a very small application that is only a few lines long, but the design principle is what&#8217;s important. Imagine applying it to a much larger application with hundreds of inputs spread across 4 windows, 3 databases, and 6 web feeds to see why this is a good idea.</p>
<h3>Auto-updating results when input changes</h3>
<p>I wanted the results to auto-update anytime an input is changed, without resorting to a &#8220;Calculate&#8221; button. Having the button trigger the calculation and output update allows the state of the input and the output to become decoupled, which can be confusing for the user. Worse, it could be unnoticed by a user who is doing other things at the same time.</p>
<p>Due to typical Java overengineering, there is no straightforward way to simply <code>(add-action-listener)</code> on the JTextField and get notifications when it changes. Instead, <a target="_blank" href="http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/generaltext.html#document" >each Swing widget implements full-blown model-view separation</a>, and so you have to get the document underlying the JTextField. Yes, the view components of your MVC application themselves contain both models and views. Each and every field contains an entire implementation of the document object and associated cruft, all for itself. If you want to monitor changes in the widget, you need to build out a <code>DocumentListener</code> to watch for such events.</p>
<p>In a real application, I&#8217;d bite the bullet and implement it, but it&#8217;s not worth the extra time for the purposes of this demo, so we are left with a &#8220;Calculate&#8221; button and manual updating.</p>
<h2>Clojure-Options on Github</h2>
<p>The entire package so far is now <a target="_blank" href="http://github.com/pjlegato/clojure_options" >available on my GitHub page</a>. Patches are welcome. Atomizing the input widgets and adding the appropriate event callbacks and watches to eliminate the &#8220;Calculate&#8221; button is particularly welcome. <img src='http://www.paullegato.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=352&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/swing-clojure-gui-black-scholes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Log4J and Clojure Configuration</title>
		<link>http://www.paullegato.com/blog/log4j-clojure/</link>
		<comments>http://www.paullegato.com/blog/log4j-clojure/#comments</comments>
		<pubDate>Sun, 16 May 2010 22:12:48 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=292</guid>
		<description><![CDATA[Clojure, Log4J, and clojure.contrib.logging can play nicely together. Here's a reasonable default configuration.]]></description>
			<content:encoded><![CDATA[<p>Clojure, Log4J, and <code>clojure.contrib.logging</code> can play nicely together. Here&#8217;s a reasonable default configuration.</p>
<ol>
<li>
<p>If using <a target="_blank" href="http://github.com/technomancy/leiningen" >Leiningen</a>, add</p>
<pre class="brush: clojure; title: ; notranslate">
:dependencies [
                 [log4j &quot;1.2.15&quot; :exclusions [javax.mail/mail
                                              javax.jms/jms
                                              com.sun.jdmk/jmxtools
                                              com.sun.jmx/jmxri]]
]
</pre>
<p>to your <code>project.clj</code> file and rerun <code>lein deps</code> to auto-install the Log4J JAR.
</p>
<p>If not using Leiningen, <a target="_blank" href="http://logging.apache.org/log4j/1.2/download.html" >acquire a Log4J JAR</a> and put it on your classpath.</p>
</li>
<li>Create a file called <code>log4j.properties</code> on your classpath and put the following into it:
<pre class="brush: plain; title: ; notranslate">
# Based on the example properties given at http://logging.apache.org/log4j/1.2/manual.html
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern= %-5p %c - %m%n
</pre>
</li>
</ol>
<p>That&#8217;s the short version. Read on for the gory details.<span id="more-292"></span></p>
<h2>Logging philosophy</h2>
<p>My logging requirements are simple at the moment. I want to write messages to the console, each tagged with a log level (&#8220;INFO&#8221;, &#8220;WARN&#8221;, &#8220;ERROR&#8221;, etc.) I want to be able to set a log level, and only see log messages of that severity or higher. That&#8217;s it. I take this to be the canonical base case of logging that covers 80% of needs. All other logging features (e.g. logging to a file, differentiating by class or namespace) are nice, but much less common, and ought to be handled via configurable deviations from this default case.</p>
<p><code>clojure.contrib.logging</code> does not presently make it easy to do any of this common base case out of the box. The Lispy façade quickly falls apart; you&#8217;re <a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >dumped into the deep end of the Java overengineering mire</a> without a life vest when you simply want to change the log level temporarily. </p>
<h3>What&#8217;s wrong with clojure.contrib.logging&#8217;s defaults?</h3>
<p><code>clojure.contrib.logging</code> with no special configuration done prefaces each and every logged line on my system with:</p>
<pre class="brush: plain; title: ; notranslate">
[null] May 16, 2010 1:08:48 PM clojure.contrib.logging$eval__2077$impl_write_BANG___2088 invoke
</pre>
<p>I have no idea why. This makes it very hard to read the log when logging any nontrivial amount of information.</p>
<p><a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >clojure.contrib.logging&#8217;s documentation</a> contains a rather cryptic offhanded remark, with no further explanation: <em>Note: your log configuration should display the name that was passed to the logging implementation, and not perform stack-inspection, otherwise you&#8217;ll see something like &#8220;fn__72$impl_write_BANG__39__auto____81&#8243; in your logs.</em></p>
<p>My log configuration? Stack inspection? Why do I need to have a log configuration to just dump strings to the console? Why is the default case to print a verbose and useless header for each line? Isn&#8217;t this Javaesque mess &mdash; <a target="_blank" href="http://wiki.apache.org/logging-log4j/Log4jXmlFormat" >obscure 50 line XML configuration files just to get basic logging functionality working</a> &mdash; exactly what we&#8217;re trying to avoid?</p>
<h2>Log4J with <code>clojure.contrib.logging</code> configuration</h2>
<p>Ah, well, there&#8217;s nothing for it, I suppose.  Better just get a serious logging library and figure out how to configure it. The docs say that <code>clojure.contrib.logging</code> delegates to the first supported logging implementation that it finds. I am apparently using <a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >the builtin JDK logger</a> by default, and Apache Commons&#8217; logger is just another wrapper, so I added Log4J to Leiningen&#8217;s project.clj and it installed the jar for me.</p>
<p>Now, I get:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] log4j:WARN No appenders could be found for logger (my-project-name).
     [null] log4j:WARN Please initialize the log4j system properly.
</pre>
<p>Followed by dead silence.</p>
<p>Hm.</p>
<p>I can only imagine that Log4j was never intended to be used without a custom configuration. Odd. Why people design software that comes without reasonable defaults pre-set to cover the common base case is beyond me. I fully understand that strange setups will require customized configuration, but &#8220;dumping strings to the console&#8221; does not seem like a bizarre edge case for a logging package. A default case of &#8220;send all log messages to the black hole unless configured to do otherwise&#8221; makes little sense.</p>
<p>So, how hard can it be to configure Log4J for this base case functionality? The &#8220;<a target="_blank" href="http://logging.apache.org/log4j/1.2/manual.html" >short introduction to log4j</a>&#8221;  is 19 pages long. Sigh. (<a target="_blank" href="http://www.qos.ch/shop/products/log4jManual" >The complete manual</a> is proudly described as &#8220;over 200 pages.&#8221; I sometimes wonder if they overengineer Java libraries on purpose just to drive book sales.) </p>
<p>I do not want to know what a Nested Diagnostic Context is, or the precise semantic distinction between &#8220;Loggers,&#8221; &#8220;Appenders,&#8221; and &#8220;Layouts.&#8221; I don&#8217;t care about &#8220;Appender Additivity&#8221; and &#8220;Named Hierarchies,&#8221; and I certainly don&#8217;t want to write an XML configuration file. I Just want to log tagged strings to the console, and have them print without a bizarre autogenerated header line. That&#8217;s it. I fully appreciate that those things will be useful for some people &mdash; maybe even for me, when my project grows to become more complex. I have nothing against their existence; but for the base case, one should not need to know of it.</p>
<p>On page 9 of the &#8220;short&#8221; manual, after a boatload of irrelevant information, we have an answer: there is a class called <code>BasicConfigurator</code> with a static method that does reasonable initialization for logging to the console. We can just do <code>(org.apache.log4j.BasicConfigurator/configure)</code> and get that.</p>
<p>However, we are still getting log messages like:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] 3702 [8633270@qtp-3149669-2] INFO my.namespace - log message
</pre>
<p>We have to learn something about <a target="_blank" href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/EnhancedPatternLayout.html" >Layouts</a> now. The thread names generated by Clojure are apparently not very useful, so we&#8217;re going to turn them off. And while interesting when profiling, the number of milliseconds since program start is just going to be visual clutter 98% of the time, so I&#8217;m going to turn that off, too, until I actually need it.</p>
<p>The result is the <code>log4j.properties</code> file listed above. Just copy and paste it into your classpath. If you want more or different information in your logs, take a look at the <a target="_blank" href="http://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/PatternLayout.html" >PatternLayout API documentation</a> and alter the <code>ConversionPattern</code> line according to your preferences.</p>
<p>The result:</p>
<pre class="brush: plain; title: ; notranslate">
     [null] INFO  my.namespace - log message
</pre>
<p>I&#8217;m still not sure where the <code>[null]</code> comes from, but overall, it&#8217;s very readable.</p>
<h2>Clojure posts you might also like:</h2>
<ul>
<li><a href="http://www.paullegato.com/blog/lazy-spy-clojure-logging-lazy-sequences/" >Lazy-spy: Clojure logging/spy for lazy sequences</a></li>
<li><a href="http://www.paullegato.com/blog/setting-clojure-log-level/" >Setting Clojure’s Log Level</a></li>
<li><a href="http://www.paullegato.com/blog/sql-where-clojure-s-expressions/" >SQL WHERE clauses in Clojure from S-Expressions</a>
<li><a href="http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/" >XML DTD Validation in Clojure: Turning It Off, Parsing Malformed XML</a></li>
</ul>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=292&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/log4j-clojure/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>XML DTD Validation in Clojure: Turning It Off, Parsing Malformed XML</title>
		<link>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/</link>
		<comments>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 00:29:31 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[sax]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=262</guid>
		<description><![CDATA[I wanted to parse some externally-generated and malformed HTML, so naturally I went to the short and sweet clojure.xml/parse function. I got a nasty error: error: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd It seems that the W3C blocked access to the DTDs two years ago, but Java still tries to load [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to parse some externally-generated and malformed HTML, so naturally I went to the short and sweet <a target="_blank" href="http://richhickey.github.com/clojure/clojure.xml-api.html" ><code>clojure.xml/parse</code> function</a>. I got a nasty error:</p>
<blockquote><p>
<code>error: java.io.IOException: Server returned HTTP response code: 503 for URL: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</code>
</p></blockquote>
<p>It seems that <a target="_blank" href="http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic" >the W3C blocked access to the DTDs</a> two years ago, but Java still tries to load them by default anyway. The following allows <code>clojure.xml</code> to run without checking external DTDs:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn startparse-sax-non-validating [s ch]
  (.. (doto (. javax.xml.parsers.SAXParserFactory (newInstance))
       (.setValidating false)
       (.setFeature &quot;http://apache.org/xml/features/nonvalidating/load-dtd-grammar&quot; false)
       (.setFeature &quot;http://apache.org/xml/features/nonvalidating/load-external-dtd&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/validation&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/external-general-entities&quot; false)
       (.setFeature &quot;http://xml.org/sax/features/external-parameter-entities&quot; false))

       (newSAXParser) (parse s ch))))
</pre>
<p>Then you can simply <code>(xml/parse "sourcefile.xml" startparse-sax-non-validating)</code>. This is not the ideal solution &mdash; ideally, we want to use a locally cached DTD &mdash; but it works well enough for one-off code. Read on for further information.<span id="more-262"></span></p>
<h2>W3C&#8217;s malformed specification</h2>
<p>The W3C webserver was being DDoSed by the massive number of XML parsers trying to download the DTDs constantly, so they just blocked everyone. This is a direct result of the poorly considered technical specification for DTD identification and <a target="_blank" href="http://en.wikipedia.org/wiki/URI#Relationship_to_URL_and_URN" >URIs themselves</a>, then exacerbated by the W3C&#8217;s institutional culture and philosophy.</p>
<h3>Technical commentary</h3>
<p>The root of the problem is, as they put it, that &#8220;these [DTD URIs] are <em>not hyperlinks</em>; these URIs are used for identification&#8221; (emphasis in original.) This is an abuse of the URL format. If it&#8217;s &#8220;for identification,&#8221; then it doesn&#8217;t need to specify a transport protocol! They are relying upon their particular interpretation of the old <a target="_blank" href="http://tools.ietf.org/html/rfc3305" >URI/URL debate</a>, reducing the transport protocol element to a namespace identifier instead, and then assuming everyone will defer to their judgement and wisdom on the matter.</p>
<p>The W3C (and others who share their URL/URI interpretation) decided to conflate the semantic functions of <em>locating and transporting</em> a resource with the very distinct function of <em>identifying</em> a resource. &#8220;My name&#8221; is not the same thing as an instruction to &#8220;get in your car, drive to my street address, pick up someone with my name here, and then drive me back to your house,&#8221; even though there is indeed only one person with my name at this address. If you want to identify me, you would not give someone the latter instruction. Most likely, they didn&#8217;t think about this at all and just did it. Now everyone suffers for this poor design decision. They are being DDoSed and paying massive amounts of money to keep the servers going, and everyone&#8217;s XML parsers are broken because they&#8217;re now returing 503s for all the DTD URIs.</p>
<p>The W3C&#8217;s proposed solution is that everyone else should a) defer to their views on the URL/URI matter, and 2) rewrite their XML parsers to be massively more complex and build local caching DTD catalogs for every single one-off parse. In practice, most people will just turn DTD validation off, potentially breaking a lot of other things.</p>
<h3>Institutional commentary on the W3C itself</h3>
<p>The tone of naive incredulity in the W3C&#8217;s plea is most amazing of all. They seem genuinely baffled as to why anyone would ever choose to ignore their wisdom on the URL/URI matter, and even more confused as to how anyone could ignore any detail of a baroque and poorly communicated specification like those for XML and DTD cataloging. &#8220;We spent a long time writing that, and we have [the self-appointed] institutional authority to write specifications and make determinations like what a URI should be, so surely people would never just ignore us!&#8221;</p>
<p>For them, the only conceivable explanation for every detail of the specification not being implemented is sheer ignorance. They even gently chide the readers about their failure to use URIs properly and to build DTD caches into everything, much as a kindergarten teacher would a well-meaning but rather dumb child who continually ignores instructions about how to use his crayons. They think that they only have to patiently remind people enough times that there is indeed a right way to do it, that which is sanctioned by the appropriate institutional authorities (them, of course) &mdash; and finally everything will be fine once people get that message.</p>
<p>This is the sort of ingenuous attitude that can only develop in a pure research institute and among people who mostly have very high <a target="_blank" href="http://psychology.wikia.com/wiki/Power_distance" >power distance index scores</a>. The high PDI explains their naive arrogation of global authority and utterly genuine assumption that everyone ought to just do as they say, simply because they&#8217;re the (self-)designated authority. The research institute setting means that they&#8217;re shut off from the economic real world. Since money is never a big issue, the worship of artificially created fancy titles and institutional authority can become rampant, and it&#8217;s perfectly fine to spend <a target="_blank" href="http://stackoverflow.com/questions/243728/how-to-disable-dtd-at-runtime-in-javas-xpath" >extended amounts of time</a> parsing a 2 page XML document &#8220;the right way&#8221; rather than 15 minutes hacking it and moving on to more pressing problems so your company doesn&#8217;t go bankrupt in the interim.</p>
<p>Moreover, <em>they are still intransigently defending the original poor design choice</em> to use URIs with embedded transport protocols as unique identifiers, because they (as an institution) cannot admit the possibility that this was a poor choice. That would create a great deal of <a target="_blank" href="http://en.wikipedia.org/wiki/Cognitive_dissonance" >cognitive dissonance</a> vis-à-vis their conception of the nature of an institution and its role in dictating what is correct and what is not in the world; their view that institutional authority must be right, because, well, otherwise it wouldn&#8217;t be an institution. After all, <a target="_blank" href="http://en.wikipedia.org/wiki/Argument_from_authority" >everyone there does have more fancy titles</a> than most people who are not there.</p>
<p>These attitudes are pervasive throughout most W3C work, and are the main reason that real-world implementations ignore much of their work.</p>
<h2>Parsing malformed HTML</h2>
<p>So, in any case, I have another problem besides Java trying to load the unavailable DTD. The input HTML is malformed. Not just a little; it&#8217;s utterly broken. It&#8217;s both externally-generated and unreplaceable, so fixing it at the source is not an option. I&#8217;m stuck with it; it&#8217;s the only way to get the data I need. (That&#8217;s real-world programming as opposed to academia right there.)</p>
<h3>Disabling XML validation</h3>
<p>Disabling all XML validation is the obvious solution to both problems, but there is no readily apparent way to do that <code>clojure.xml</code>. Calling <code><a target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html#setValidating%28boolean%29" >setValidating(false)</a></code> on the factory is insufficient. Thanks to <a target="_blank" href="http://stackoverflow.com/questions/243728/how-to-disable-dtd-at-runtime-in-javas-xpath" >Stack Overflow</a>, I found that you must also use<br />
<code><a target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html#setFeature%28java.lang.String,%20boolean%29" >setFeature()</a></code> with several obscure &#8220;<a target="_blank" href="http://www.saxproject.org/apidoc/org/xml/sax/package-summary.html#package_description" >SAX2 Standard Feature Flags</a>&#8220;, as above.</p>
<h3>HTML Tidy to the rescue</h3>
<p>This still leaves the problem of the malformed HTML. There does not seem to be any easy way to make Sax ignore errors. (<code>(.setFeature "http://apache.org/xml/features/continue-after-fatal-error" true)</code> has no apparent effect; it still doesn&#8217;t continue after a fatal parse error.)</p>
<p>In the end, I just ran the malformed input HTML through <a target="_blank" href="http://tidy.sourceforge.net/" >HTML Tidy</a> before attempting to parse it. HTML Tidy coerces the malformed input into valid XML, and Sax is finally happy.</p>
<p>(I now get &#8220;<code>Exception in thread "Swank REPL Thread" java.lang.RuntimeException: java.lang.IllegalMonitorStateException</code>&#8221; from SLIME when I try to actually <em>display</em> the parsed XML in Emacs, but that&#8217;s another matter&#8230;)</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=262&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/dtd-validation-malformed-xml-clojure/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Clojure SQL Dates and Times with Joda</title>
		<link>http://www.paullegato.com/blog/clojure-joda-sql-date-time/</link>
		<comments>http://www.paullegato.com/blog/clojure-joda-sql-date-time/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 04:52:56 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=196</guid>
		<description><![CDATA[The date and time classes built into Java are a horrible mess. What are Clojure programmers to do? Use Joda Time instead. Joda Time is coherently designed and easy to use.
]]></description>
			<content:encoded><![CDATA[<p>The date and time classes built into Java are a horrible mess. What are Clojure programmers to do? Use <a target="_blank" href="http://joda-time.sourceforge.net/" >Joda Time</a> instead. Joda Time is coherently designed and easy to use.</p>
<p>JDBC (at least, the PostgreSQL driver) can&#8217;t use Joda Time directly (without explicit type mapping). One way to convert a Joda LocalDate into something JDBC can use:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn to-sql-date [date]
  &quot;Convert any Joda-readable date object (including a string) to a java.sql.Date&quot;
  (java.sql.Date. (.. (LocalDate. date) toDateMidnight toInstant getMillis)))
</pre>
<p>It&#8217;s not pretty, but it works. You can follow a similar procedure for any of the Joda classes.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=196&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/clojure-joda-sql-date-time/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Setting Clojure&#8217;s Log Level</title>
		<link>http://www.paullegato.com/blog/setting-clojure-log-level/</link>
		<comments>http://www.paullegato.com/blog/setting-clojure-log-level/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 03:35:34 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=177</guid>
		<description><![CDATA[Clojure.contrib.logging doesn't have any way to set the log level. This is obviously a problem if you want to make use of various log levels (debug, warn, etc.) to separate different logging depths. Here's a function to set the logging level.]]></description>
			<content:encoded><![CDATA[<p>Clojure.contrib.logging doesn&#8217;t have any way to set the log level. This is obviously a problem if you want to make use of various log levels (debug, warn, etc.) to separate different logging depths. Here&#8217;s a function to set the logging level on my default clojure.contrib.logging setup:</p>
<pre class="brush: clojure; title: ; notranslate">
;;; This version works when (impl-get-log &quot;&quot;) returns an org.apache.commons.logging.impl.Jdk14Logger
(use 'clojure.contrib.logging)
(defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.
   Level should be one of the constants defined in java.util.logging.Level.&quot;
  (let [logger (.getLogger (impl-get-log &quot;&quot;))]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
</pre>
<pre class="brush: clojure; title: ; notranslate">
;;; This version works when (impl-get-log &quot;&quot;) returns a java.util.logging.LogManager$RootLogger
(use 'clojure.contrib.logging)
(defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.
   Level should be one of the constants defined in java.util.logging.Level.&quot;
  (let [logger (impl-get-log &quot;&quot;)]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
</pre>
<p>This log level setting function works with a standard out-of-the-box clojure.contrib.logger on my system &mdash;  depending on what logging libraries it finds on your classpath, <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >as per the docs</a>, it may not work for you. In particular, you need to be using clojure.contrib.logger to wrap an Apache Commons Logging instance, which in turn wraps a java.util.logging instance. This is the way my system works without any configuration; YMMV. Hopefully, something like this will be assimilated into a universal wrapper in the next clojure.contrib.logging.</p>
<p>For the gory details of how this was constructed&#8230; <span id="more-177"></span></p>
<h2>Changing log levels</h2>
<p>I needed to log some data in my Clojure app. I looked through clojure-contrib and found <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html" >clojure.contrib.logging</a>. It provides a unified logging wrapper for Apache commons-logging, log4j, and java.util.logging.</p>
<p>The <a target="_blank" href="http://richhickey.github.com/clojure-contrib/logging-api.html#clojure.contrib.logging/spy" ><code>spy</code> macro</a> looks particularly useful for debugging intermediate functions without complicating their code with a bunch of logging cruft: just wrap them in a single tiny <code>spy</code> call, and you&#8217;re set.</p>
<p>Unfortunately, <a target="_blank" href="http://github.com/richhickey/clojure-contrib/blob/655060b3f265026ef3b45b44f5ab22d8897b3034/src/main/clojure/clojure/contrib/logging.clj#L236" ><code>spy</code> logs at the :debug level</a>, and my logger by default seems to be set to <code>:info</code> level. No problem, I thought, I&#8217;ll just increase the log level to <code>:debug</code>&#8230; Hm&#8230; Turns out that there&#8217;s no simple way to do that.</p>
<p><code>clojure.contrib.logging</code> presently includes nothing at all for setting the debug level, in fact, a curious omission of obvious and very basic functionality. So we dig.</p>
<p>Setting the log level must be done in the underlying logging library, since there&#8217;s no clojure.commons.logging wrapper. Looking at <code>*impl-name*</code>, it seems that I&#8217;m using <code>org.apache.commons.logging</code>.</p>
<h3>Apache Commons Logging</h3>
<p>OK, great. Let&#8217;s take a look at the Commons Logging docs. The Commons Logging <a target="_blank" href="http://commons.apache.org/logging/guide.html" >User Guide</a> sounds like a good place to start. Surely changing the log level is a very common task that will be prominently addressed there&#8230; Perhaps even in the <a target="_blank" href="http://commons.apache.org/logging/guide.html#Quick%20Start" >Quick Start guide</a>.</p>
<p>Hmm, nope, nothing about changing the log level, but there <em>is</em> a somewhat disturbing reference to &#8220;a simple <code>commons-logging.properties</code> file&#8221;, conjuring up long-ago memories of Java overengineering and bloat &mdash; an entire configuration file, just to temporarily change the log level?? Surely not&#8230; Also mildly disturbingly, there are references to &#8220;the underlying logging system&#8221;. Commons Logging seems to be, itself, just an abstraction around some other logging system. So I&#8217;m using <em>two</em> layers of logging wrappers now.</p>
<p>Well, let&#8217;s see what Clojure thinks we&#8217;re using:</p>
<pre class="brush: clojure; title: ; notranslate">
&gt; (log/impl-get-log &quot;user&quot;)
#&lt;Jdk14Logger org.apache.commons.logging.impl.Jdk14Logger@13e168&gt;
</pre>
<p>Now we&#8217;re getting somewhere. Let&#8217;s look at <a target="_blank" href="http://commons.apache.org/logging/apidocs/org/apache/commons/logging/impl/Jdk14Logger.html" >Jdk14Logger&#8217;s JavaDocs</a>: the <code>getLogger()</code> &#8211; &#8220;Return the native Logger instance we are using&#8221; method looks promising.</p>
<h3>java.util.logging.Logger</h3>
<pre class="brush: clojure; title: ; notranslate">
&gt; (.. (log/impl-get-log &quot;user&quot;) getLogger)
#&lt;Logger java.util.logging.Logger@1a32f73&gt;
</pre>
<p><code>java.util.logging.Logger</code>! Aha! Let&#8217;s see <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html"  class="broken_link">what we can do with that</a>&#8230; &#8220;The log level &#8230; may also be dynamically changed by calls on the Logger.setLevel method.&#8221; Finally!</p>
<p>This being Java, <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Logger.html#setLevel(java.util.logging.Level)" >setLevel() naturally requires an entire object</a> to wrap the integer specifying the log level, with the integer in turn standing in for what we would call a symbol in Lisp (and being referenced symbolically through constants in the Level class.) Ugh. And confusingly, the <a target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/logging/Level.html#field_summary" >log level constants in that class</a> are named <code>FINE</code>, <code>FINER</code>, <code>FINEST</code>, <code>INFO</code>, <code>OFF</code>, <code>SEVERE</code>, and <code>WARNING</code>, which do not correspond to the :debug, :info, :warn, :error levels used by Clojure and Apache Commons Logging.</p>
<p>Let&#8217;s see what we&#8217;re at now:</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (use 'clojure.contrib.logging)
nil
user&gt; (warn &quot;foo&quot;) ; -&gt; WARNING: foo
nil
user&gt; (info &quot;foo&quot;) ; -&gt; INFO: foo
nil
user&gt; (debug &quot;foo&quot;) ; nothing printed
nil
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getLevel)
nil
;;
;; Nil? WTF?
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger )
#&lt;Logger java.util.logging.Logger@197952&gt;
;;
;; Yep, we're using the right object...
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getName)
&quot;user&quot;
;;
;; and we have the logger for the correct namespace...
;; it has a getParent() method - maybe it inherits?
;;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getParent)
#&lt;RootLogger java.util.logging.LogManager$RootLogger@1c2df08&gt;
user&gt; (.. (impl-get-log &quot;user&quot;) getLogger getParent getLevel)
#&lt;Level INFO&gt;
;;
;; AHA. it does.
;;
</pre>
<p>So we&#8217;ve finally tracked down where the log level is set. According to the Javadocs, a logger with a null log level will inherit its parent&#8217;s log level, and changing the parent with <code>setLevel()</code> will also affect any children that are inheriting. The docs tell us that we can get the root logger by asking for the &#8220;&#8221; (empty string) name, so we can simply modify that:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn set-log-level! [level]
&quot;Sets the root logger level.&quot;
  (.setLevel (.getLogger (log/impl-get-log &quot;&quot;)) level))
</pre>
<p>But all is not well:</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (.. (impl-get-log &quot;&quot;) getLogger getLevel)
#&lt;Level FINE&gt;
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/FINER)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/FINEST)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
user&gt; (set-log-level! java.util.logging.Level/ALL)
nil
user&gt; (debug &quot;foobar&quot;) ;; prints nothing
nil
</pre>
<p>Err&#8230; ok. Maybe that&#8217;s the wrong method? Maybe it&#8217;s not actually setting it?</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (.. (impl-get-log &quot;user&quot;) isDebugEnabled)
true
user&gt; (.. (impl-get-log &quot;&quot;) isDebugEnabled)
true
user&gt; (log :debug &quot;asdf&quot;) ;; prints nothing
nil
user&gt; (debug &quot;asdf&quot;) ;; prints nothing
nil
;;
;; Maybe printing directly to the Java object rather than going through contrib.logger will help?
;;
user&gt; (. (impl-get-log &quot;user&quot;) debug  &quot;foo bar&quot;) ;; prints nothing
nil
user&gt; (. (impl-get-log &quot;&quot;) debug  &quot;foo bar&quot;) ;; prints nothing
nil
user&gt; (. (impl-get-log &quot;user&quot;) warn  &quot;foo bar&quot;) ;; prints &quot;WARNING: foo bar&quot;
nil
</pre>
<p>WTF.</p>
<p>Digging even further into the docs, we find:</p>
<blockquote><p>
 On each logging call the Logger initially performs a cheap check of the request level (e.g. SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately.</p>
<p>After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent&#8217;s Handlers, recursively up the tree.
</p></blockquote>
<p>Great, more Filters of some kind (beyond the log level check filter), a LogRecord object to wrap a string, and an inherited tree of Handlers. All to write a simple level-bound log message to STDERR. (And this is the <em>simple</em> logging library. I shudder to think of log4j&#8217;s internals.)</p>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (..  (impl-get-log &quot;&quot;) getLogger getFilter)
nil
user&gt; (..  (impl-get-log &quot;user&quot;) getLogger getFilter)
nil
user&gt; (..  (impl-get-log &quot;&quot;) getLogger getHandlers)
#&lt;Handler[] [Ljava.util.logging.Handler;@23f019&gt;
user&gt; (first (..  (impl-get-log &quot;&quot;) getLogger getHandlers))
#&lt;ConsoleHandler java.util.logging.ConsoleHandler@829d91&gt;
user&gt; (.. (first (..  (impl-get-log &quot;&quot;) getLogger getHandlers)) getLevel)
#&lt;Level INFO&gt;
user&gt;
</pre>
<p>So... in the "simple" logger package, we have <strong>two. seperate. levels.</strong> of filtering on the log level, which are entirely uncoordinated. And no mention in the documentation of what exactly these "Filters" and "Handlers" do, or that they can also discard log messages. Certainly no mention at the logger's <code>setLevel()</code> method docs that your setting might be overruled by a "Handler" in some other part of the object tree. (Now, why did I ever stop coding in Java, again...?)</p>
<h3>The working function to set the log level</h3>
<pre class="brush: clojure; title: ; notranslate">
user&gt; (defn set-log-level! [level]
  &quot;Sets the root logger's level, and the level of all of its Handlers, to level.&quot;
  (let [logger (.getLogger (impl-get-log &quot;&quot;))]
    (.setLevel logger level)
    (doseq [handler (.getHandlers logger)]
      (. handler setLevel level))))
#'user/set-log-level!
user&gt; (set-log-level! java.util.logging.Level/ALL)
nil
user&gt; (debug &quot;foo bar&quot;) ;; FINALLY prints &quot;FINE: foo bar&quot;. Not quite what I wanted (&quot;FINE&quot;?), but close enough.
nil
user&gt; (spy (str &quot;abc&quot; &quot;def&quot;)) ;; -&gt; &quot; FINE: (str &quot;abc&quot; &quot;def&quot;) =&gt; abcdef&quot;. cool.
&quot;abcdef&quot;
</pre>
<p>So there you have it. You can now adjust your clojure.contrib.logger log level at runtime &mdash; at least for clojure.contrib.logger wrapping Apache Commons Logging wrapping a java.util.logging logger. No doubt log4j requires its own unique set of black magic. I hope a future version of clojure.contrib.logger will include a universal loglevel-setting function &mdash; I&#8217;ll gladly donate this code to it.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=177&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/setting-clojure-log-level/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Libcurl bindings for Java on Macintosh</title>
		<link>http://www.paullegato.com/blog/libcurl-java-macintosh/</link>
		<comments>http://www.paullegato.com/blog/libcurl-java-macintosh/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 03:35:14 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[unix]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=173</guid>
		<description><![CDATA[Libcurl's Java bindings now compile on Macintosh, with a few minor modifications to the Makefile. Get the code from my Github account.]]></description>
			<content:encoded><![CDATA[<p>Libcurl&#8217;s Java bindings now compile on Macintosh, with a few minor modifications to the Makefile. <a target="_blank" href="http://github.com/pjlegato/curl-java" >Get the code</a> from my Github account.</p>
<p><em>Update</em>: More recent Java bindings, which do not seem to be linked anywhere on the libcurl site, are available at <a target="_blank" href="http://www.gknw.net/viewvc/trunk/?root=curl-java"  class="broken_link">http://www.gknw.net/viewvc/trunk/?root=curl-java</a>. Still no multi support, though.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=173&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/libcurl-java-macintosh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Yahoo Finance in Clojure</title>
		<link>http://www.paullegato.com/blog/yahoo-finance-clojure/</link>
		<comments>http://www.paullegato.com/blog/yahoo-finance-clojure/#comments</comments>
		<pubDate>Sun, 14 Mar 2010 02:54:05 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[automated trading]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=146</guid>
		<description><![CDATA[A Clojure version of my Yahoo Finance Ruby gem seemed like an interesting challenge and a good way to learn Clojure better. This version uses Apache HttpClient, which is significantly slower than libcurl. A libcurl version is on the way.]]></description>
			<content:encoded><![CDATA[<p>A Clojure version of my <a href="http://www.paullegato.com/blog/yahoo-finance-ruby-typhoeus/" >Yahoo Finance Ruby gem</a> seemed like an interesting challenge and a good way to learn Clojure better. <a target="_blank" href="http://github.com/pjlegato/Clojure-yahoo-finance" >This version</a> uses Apache HttpClient, which is significantly slower than libcurl. A libcurl version is on the way.<span id="more-146"></span></p>
<h2>Project requirements and background</h2>
<p>We want a fast and efficient way to download thousands of symbols&#8217; worth of historic stock data from Yahoo Finance. Parallel HTTP queries and persistent connections are, therefore, required.</p>
<p><a target="_blank" href="http://github.com/technomancy/clojure-http-client" >Technomancy&#8217;s clojure-http-client</a> is beautifully written idiomatic Clojure, but unfortunately it does not yet support connection pooling. Needless to say, the built-in Java standard library HTTP client don&#8217;t seem to have it, either. I thought of <a target="_blank" href="http://curl.haxx.se/" >libcurl</a>, of course, but <a target="_blank" href="http://curl.haxx.se/libcurl/java/" >its Java bindings</a> (and <a target="_blank" href="http://javacurl.sourceforge.net/" >older bindings</a> that the official site says to avoid) do not seem to be particularly complete or maintained. Googling turned up <a target="_blank" href="http://www.innovation.ch/java/HTTPClient/index.html" >a HTTPClient last updated in 2001</a>, <a target="_blank" href="http://oaklandsoftware.com/product_http/overview.html" >a commercial package</a>, and the free <a target="_blank" href="http://hc.apache.org/httpcomponents-client/index.html" >Apache HttpClient</a> project, which seems to be reasonably active and to do almost everything that the Oakland Software commercial package does (the comparison on their website seems to have been written in 2003, when they had several features that Apache lacked, but which have since been implemented.) Oakland Software&#8217;s client has pipelining, which none of the others do, but that alone isn&#8217;t worth the price.</p>
<p>I went with Apache HttpClient. I figured that it would be easier to use  than libcurl&#8217;s Java bindings (ha!) as it presented a higher-level user interface. (It turns out that whatever ease-of-use gain there was to be had there is more than compensated for by its confused documentation and general overengineered Java coding style.)</p>
<p>Apache HttpClient&#8217;s docs are a little out of date. I found an example of <a target="_blank" href="http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java" >multithreaded parallel HTTP requests</a> and <a target="_blank" href="http://hc.apache.org/httpcomponents-core/httpcore/apidocs/index.html" >the</a> <a target="_blank" href="http://hc.apache.org/httpcomponents-client/httpclient/apidocs/index.html" >JavaDocs</a> and went from there.</p>
<h2>Clojure code</h2>
<p>I began by translating the general outline of the Java example to Clojure, though it pained me to see such imperativeness in parentheses. I made a few updates: I changed it to use the Executor threading system rather than creating threads manually, and of course I used a Clojure function instead of a thread (since all Clojure functions implement <code>Callable</code>, which is really convenient.) I also used <a target="_blank" href="http://joda-time.sourceforge.net/" >Joda-Time</a> to replace the obscene GregorianCalendar/Date classes that come with Java.</p>
<p>The latest version of this code is <a target="_blank" href="http://github.com/pjlegato/Clojure-yahoo-finance" >available from GitHub</a>.</p>
<pre class="brush: clojure; title: ; notranslate">
;; clojure-yahoo-finance: Clojure interface to Yahoo! Finance historic stock data.
;;
;; Copyright (C) 2010 Paul Legato. All rights reserved.
;; Licensed under the BSD-new license: see the file LICENSE for details.
;;
;; This code is not endorsed by or connected with Yahoo in any way.
;;
(ns clojure-yahoo-finance.core
  (:import (org.apache.http
            HttpResponse
            HttpVersion
            client.HttpClient
            client.methods.HttpGet
            conn.scheme.PlainSocketFactory
            conn.scheme.Scheme
            conn.params.ConnManagerParams
            conn.params.ConnPerRouteBean
            conn.scheme.SchemeRegistry
            impl.client.DefaultHttpClient
            impl.conn.tsccm.ThreadSafeClientConnManager
            params.BasicHttpParams
            params.HttpConnectionParams
            params.HttpProtocolParams
            protocol.BasicHttpContext
            util.EntityUtils
            )
           (java.util.concurrent Executors)
           (org.joda.time LocalDate)
           ))

(defn- yahoo-request-thread
  &quot;Internal function used as the thread to retrieve historic data for symbol from startDate to endDate via httpClient.

   The value will be either a map with the symbol name and the raw CSV data from Yahoo, or an HTTP status code (e.g. 404 means the symbol was not found.)

   Dates can be of any class that Joda-Time understands (including a 'YYYY-MM-DD' String.)
&quot;
  [httpClient symbol startDate endDate]
   (let [
         start (LocalDate. startDate)
         end (LocalDate. endDate)

         httpGet (new HttpGet
                      (str &quot;http://itable.finance.yahoo.com&quot;
                           &quot;/table.csv?s=&quot; symbol &quot;&amp;g=d&quot; +
                           &quot;&amp;a=&quot; (- (.getMonthOfYear start) 1)
                           &quot;&amp;b=&quot; (.getDayOfMonth start)
                           &quot;&amp;c=&quot; (.getYear start)
                           &quot;&amp;d=&quot; (- (.getMonthOfYear end) 1)
                           &quot;&amp;e=&quot; (.getDayOfMonth end)
                           &quot;&amp;f=&quot; (.getYear end)))

         ]
     (try
      (let [httpResponse  (. httpClient execute httpGet (new BasicHttpContext))
            entity (. httpResponse getEntity)
            data (if (= 200 (.. httpResponse getStatusLine getStatusCode))
                   (. EntityUtils toString entity)
                   404)]
        (.consumeContent entity) ;; required to release the connection back to the pool? Docs are unclear on whether EntityUtils does this itself.
        {symbol data}
        )
      (catch Exception e
        (.abort httpGet)
        (throw e)))))

(defn blocking-query
  &quot;Returns historic data between startDate and endDate for the seq of symbols.

Options:
  :maxConnections - default 200.
  :threadPoolSize - default 300. Should be larger than maxConnections
                    for optimal efficiency. Set to 0 for an unbounded thread pool - be
                    advised that doing so may exhaust available memory if you're requesting a lot of symbols
                    relative to the amount of free memory and thread-creation overhead on your system.

The optimal values for these parameters are system-dependent.

&quot;
  [startDate endDate symbols &amp; options]
  (let [opts (when options (apply assoc {} options))

        params (new BasicHttpParams)
        schemeRegistry (new SchemeRegistry)

        results {}

        threadPoolSize (or (:threadPoolSize opts) 300)
        threadPool (if (= threadPoolSize 0)
                     (Executors/newCachedThreadPool)
                     (Executors/newFixedThreadPool threadPoolSize))
        ]

    ;; Wow, this is ugly. Now I remember why I stopped using Java.
    (. HttpProtocolParams setVersion params HttpVersion/HTTP_1_1)
    (. HttpProtocolParams setUserAgent params &quot;Clojure-Yahoo-Finance&quot;)

    (. HttpConnectionParams setTcpNoDelay params true)

    ;; If these are turned too low, then you will get timeouts when running very large queries, because
    ;; all threads are started at once and each will block until it is allocated an HTTP connection from
    ;; the pool.
    (. HttpConnectionParams setConnectionTimeout params 100000)
    (. ConnManagerParams setTimeout params 100000)

    ;; These methods are marked deprecated in 4.1-alpha1, but their replacements don't work.
    (. ConnManagerParams setMaxConnectionsPerRoute params (new ConnPerRouteBean (or (:maxConnections opts) 200)))
    (. ConnManagerParams setMaxTotalConnections params (or (:maxConnections opts) 200))

    (. schemeRegistry register (new Scheme &quot;http&quot; (. PlainSocketFactory getSocketFactory) 80))

    (let [connectionManager (new ThreadSafeClientConnManager params schemeRegistry)
          httpClient (new DefaultHttpClient connectionManager params)
          ]

      ;; Broken in 4.1-alpha1 - need to use the deprecated method above instead
      ;;
      ;;(doto connectionManager
      ;; (.setMaxTotalConnections (or (:maxConnections opts) 200)))
      ;;        (.setDefaultMaxPerRoute (or (:maxConnections opts) 200))) 

      (try
       (let [tasks (map (fn [sym]
                          (fn [] (yahoo-request-thread httpClient sym startDate endDate)))
                        symbols
                        )
             futures (map (fn [x] (.get x)) (.invokeAll threadPool tasks))]
         (reduce conj futures))

         (finally
          (.. httpClient getConnectionManager shutdown)
          (.shutdown threadPool)))
       ))))
</pre>
<h2>Notes</h2>
<ul>
<li>The optimal values for :maxConnections and :threadPoolSize depend on how much free RAM is available to the Clojure process, how much memory overhead is involved in creating a new thread (JVM/OS dependent), and the latency characteristics of the network link between the user and Yahoo. The defaults should be reasonable for most modern desktop computers and broadband network environments, but those with access to particularly fast network pipes and with lots of RAM to spare may be able to get better performance by tweaking them. Note that you have to give <code>java</code> the <code>-Xmx</code> flag at startup to actually make more free RAM available to the JVM.</li>
<li>Although using <code>ConnManagerParams</code> to set the maximum connections (lines 106-7) is marked deprecated in the JavaDocs for 4.1-alpha1, their replacements (lines 118-120) don&#8217;t actually do anything, so I had to use the deprecated methods instead. This took me a while to figure out, since of course this isn&#8217;t mentioned anywhere in the docs.</li>
<li>The docs are inconsistent and vague about how an HTTP connection gets returned to the thread pool. Compounding the problem is that many of the docs seem to have been written for version 3.x, where it was apparently required to manually release connections. One doc mentions that 4.x automatically returns connections to the pool, another says you need to call either <code>abort</code> on the connection or <code>consumeContent</code> on an <code>entity</code> (included at line 60, just to be safe.)</li>
</ul>
<h2>No refs</h2>
<p>My first version passed a ref to each thread and had it update it itself with its results That works fine, but I suspected that refs are not the most efficient way to go about this, as they incur transaction overhead in each thread. Profiling proved this theory out. Downloading one month of AAPL with the refs version above took about 0.60 seconds on average. I rewrote it to simply return the result from the thread rather than store it in a ref itself. The calling function then aggregates the results of all threads with <code>reduce</code>. This version gives us a slight performance boost, averaging around 0.45 seconds. (Subsequent additional optimizations boosted performance further, to the 0.24 seconds in the chart below.)</p>
<h2>pmap / reduce version</h2>
<p>A guy on IRC pointed me to <a target="_blank" href="http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/pmap" >pmap</a>/<a target="_blank" href="http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/reduce" >reduce</a> as a more Clojureish way of doing parallel calculation aggregation. This looks very interesting and is on the list for future projects.</p>
<h2>Profiling</h2>
<p>Tests were repeated 10 times, and the runtimes were averaged.</p>
<table border="1">
<tr>
<td><strong>Test</strong></td>
<td><strong>clojure-yahoo-finance</strong></td>
<td><strong>Ruby / yahoofinance-typhoeus</strong></td>
</tr>
<tr>
<td>AAPL Jan 2009</td>
<td>241 ms</td>
<td>146 ms</td>
</tr>
<tr>
<td>AAPL all of 2009</td>
<td>609 ms</td>
<td>267 ms</td>
</tr>
</table>
<p>Clojure-yahoo-finance is quite a bit slower than the Ruby/Typhoeus version, but not so much slower as to render it unusable for most purposes. I suspect this is mainly because Typhoeus uses <a target="_blank" href="http://curl.haxx.se/" >libcurl</a>, written in C and heavily optimized over many years for speed, for all of its HTTP processing, whereas the Clojure version is using the pure-Java <a target="_blank" href="http://hc.apache.org/" >Apache HttpClient</a>, replete with all the usual overengineered cruft one associates with Java, such as 5 million typed helper setter methods for generic &#8220;configuration options,&#8221; plus a helper class to actually set the 2 configuration options that exist, and Bean objects that do nothing but wrap an integer.</p>
<p>The next step is to figure out the Java bindings for libcurl and write a Clojure version with that. Stay tuned.</p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=146&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/yahoo-finance-clojure/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>JNI, Leiningen, and the :native-path argument</title>
		<link>http://www.paullegato.com/blog/jni-leiningen-native-path/</link>
		<comments>http://www.paullegato.com/blog/jni-leiningen-native-path/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 00:12:52 +0000</pubDate>
		<dc:creator>Paul Legato</dc:creator>
				<category><![CDATA[Tech]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[Incanter]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JNI]]></category>
		<category><![CDATA[JVM]]></category>
		<category><![CDATA[leiningen]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[r]]></category>
		<category><![CDATA[statistics]]></category>

		<guid isPermaLink="false">http://www.paullegato.com/?p=119</guid>
		<description><![CDATA[How to load JNI native libraries via Leiningen's undocumented :native-path argument, for installation of Rincanter.]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://github.com/jolby/rincanter" >Rincanter</a> allows one to access the <a target="_blank" href="http://www.r-project.org/" >R statistical programming language</a> from Clojure. Rincanter also integrates R with <a target="_blank" href="http://data-sorcery.org/" >Incanter</a> for charting and more stats. Rincanter is based on  <a target="_blank" href="http://www.rforge.net/rJava/index.html" >rJava</a>&#8216;s <a target="_blank" href="http://www.rforge.net/JRI/" >JRI R-from-Java bridge</a>. Getting this working required making a JNI library available to Clojure via an as-yet-undocumented Leiningen setting, <code>:native-path</code>.<span id="more-119"></span></p>
<h2>R-Java Bridge Motivation</h2>
<p>I have some statistical functions written in R which would be annoying to re-implement in Java or Clojure, mainly because they depend on R libraries that are already written and for which there are no readily apparent Java/Clojure equivalents (the augmented Dickey-Fuller test, if you&#8217;re interested.) So, naturally, I decided to look into embedding R into Java, somehow.</p>
<h2>Rincanter: R from Clojure</h2>
<p><a target="_blank" href="http://github.com/jolby/rincanter" >Rincanter</a> came up, and it looks perfect: not only does it embed R into the JVM (via <a target="_blank" href="http://www.rforge.net/rJava/index.html" >rJava</a>&#8216;s <a target="_blank" href="http://www.rforge.net/JRI/" >JRI</a> component), it provides a nice Clojure wrapper <em>and</em> it integrates it with <a target="_blank" href="http://data-sorcery.org/" >Incanter</a>, a Clojure-based statistics and charting package that I&#8217;ve been wanting to try.</p>
<h2>rJava and JRI: Low level bridge</h2>
<p>rJava is, incidentally, mainly intended for calling Java code from R, which is the opposite of what I want to do. It absorbed the JRI project, which allows one to call R from Java, into its source tree a while ago, but so far it appears to be a direct graft onto the source tree with little or no integration. Perfect, since I don&#8217;t need to use the Java-from-R stuff anyway. So I downloaded rJava and built only the JRI subdirectory.</p>
<p>Going by Rincanter&#8217;s installation instructions, I need two things from JRIL: a generic JAR for the system-independent Java parts and a platform-specific JNI, a Java Native Interface to the actual R implementation on the system. The build produced two important files (hidden in the <code>src/</code> subdirectory), <code>JRI.jar</code> and <code>libjri.jnilib</code>. (The name of the latter will vary depending on your build platform; it will be a <code>.so</code> file on Linux, a <code>.dll</code> file on Windows, etc.) I stuck them in my Clojure project&#8217;s <code>lib/</code> subdirectory, restarted Leiningen, and went to the REPL to see whether everything worked.</p>
<p>Glancing through the examples that came with JRI, I decided to try a &#8220;<code>(.new org.rosuda.JRI.Rengine)</code>&#8220;. This failed spectacularly, and crashed the JVM with a complaint about being unable to locate the JNI library.</p>
<h2>Loading JNI libraries with Leiningen</h2>
<p><a target="_blank" href="http://blog.pingoured.fr/index.php?post/2009/03/23/Getting-rJava/JRI-to-work%3A" >Further investigation</a> showed that just placing the JNI library on the classpath doesn&#8217;t work. JNI libraries apparently have a separate classpath-like construct stored in the JVM system property <code>java.library.path</code>. Mine was set to <code>".:/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java"</code> by default.</p>
<p>I don&#8217;t want to install the JRI library system-wide. The default inclusion of <code>"."</code> was curious, but I also don&#8217;t want to start dumping files into my project&#8217;s root directory. What I need is a way to set this system property. Of course, I could be crude and just hammer it in in one of my Clojure source files, but, as it&#8217;s analogous to setting up the classpath, it seems rather like something that Leiningen should be doing as part of its config-file based JVM startup procedure.</p>
<p>Good news: <a target="_blank" href="http://groups.google.com/group/leiningen/browse_thread/thread/3c0f3c28851dec37" >Leiningen got the ability to set java.library.path</a> last December. It&#8217;s still not documented in the README, but the code was merged into the official release. Searching through the codebase, I found that the <code>defproject</code> argument <code>:native-path</code> sets up JNI&#8217;s <code>java.library.path</code>. I made myself a <code>jni/</code> subdirectory, added <code>:native-path "jni"</code> to my <code>project.clj</code>, and it worked.</p>
<p>It did clobber the default <code>java.library.path</code> property completely, replacing it with my &#8220;jni/&#8221; argument rather than appending it. That&#8217;s OK for my case, since I&#8217;m not using any systemwide JNI libraries, but it is something to be aware of in case you are.</p>
<p><em>Update:</em> Rincanter apparently does its own management of <code>java.library.path</code> and JNI library loading. The docs ask for the .jnilib to be installed into Rincanter itself. It&#8217;s still good to know about the Leiningen way. </p>
<img src="http://www.paullegato.com/?ak_action=api_record_view&id=119&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://www.paullegato.com/blog/jni-leiningen-native-path/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

