<?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>Prog-a-Month &#187; prog</title>
	<atom:link href="http://www.progamonth.com/?feed=rss2&#038;cat=7" rel="self" type="application/rss+xml" />
	<link>http://www.progamonth.com</link>
	<description>The journeys of a programmer</description>
	<lastBuildDate>Sat, 22 May 2010 23:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>m.stefankendall.com &#8211; My iPhone web apps</title>
		<link>http://www.progamonth.com/?p=324</link>
		<comments>http://www.progamonth.com/?p=324#comments</comments>
		<pubDate>Sat, 22 May 2010 23:01:05 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[jqtouch]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=324</guid>
		<description><![CDATA[Recently, I&#8217;ve become very interested in iPhone web app development and Grails, so I decided to merge the two into a little project. Using Grails, jQTouch, and jQuery, I built an application to search a variety of torrent portals and aggregate the results. I could describe the application, but why not just head over to [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I&#8217;ve become very interested in iPhone web app development and Grails, so I decided to merge the two into a little project. Using <a href="http://www.grails.org/">Grails</a>, <a href="http://jqtouch.com/">jQTouch</a>, and <a href="http://jquery.com">jQuery</a>, I built an application to search a variety of torrent portals and aggregate the results. I could describe the application, but why not just head over to <span style = "font-size:2em"><a href="http://m.stefankendall.com">m.stefankendall.com</a></span> and check it out?</p>
<p>If you don&#8217;t have an iPhone or Android-like device, here are some screenshots to show you what the interface looks like on a mobile device:</p>
<p><img src="blogfiles/images/iphonewebapps/iPhoneTorrentSearch1.jpg" alt="iPhone Web App Screenshot 1" /> <img src="blogfiles/images/iphonewebapps/iPhoneTorrentSearch2.jpg" alt="iPhone Web App Screenshot 2" /> <img src="blogfiles/images/iphonewebapps/iPhoneTorrentSearch3.jpg" alt="iPhone Web App Screenshot 3" /></p>
<p>Working with this project, I discovered a few interesting bits of information.</p>
<style type = "text/css">
.snippet{
color: #444444;
padding: 0 1em 0 1em;
font-family: monospace;
font-size: 1.2em;
}
.dlFindings dt{
font-size: 1.5em;
}
</style>
<ol>
<li>
<dl class = "dlFindings">
<dt>jQTouch is incomplete</dt>
<dd>I had to work through the source code of the CSS files and <a href="http://jqtouch.com/preview/demos/main/#home">demo page</a> to make any headway into this library. There is very little documentation, and some of the pre-built &#8220;apple&#8221; styles don&#8217;t look truly native. This is sad, but it does do some things pretty well. For instance, if you bind <span class = "snippet">$.tap</span> event to a jQuery object, and the target browser doesn&#8217;t support the <span class = "snippet">$.tap</span> javascript event, the event is bound to <span class = "snippet">$.click</span> instead. This is great for testing. I also found that while Safari for Windows is a close approximation for the iPhone browser, it&#8217;s not the same.</p>
<p>For instance, if your page has any HTML errors, such as improperly closed <span class = "snippet">&lt;input /&gt;</span> tag, Safari for Windows won&#8217;t complain. Safari for the iPhone, however, will break all to hell and respond haphazardly to javascript events. To prevent this from happening to you, I <strong>highly recommend</strong> enabling Safari developer mode. See the screenshots below.</p>
<p><img src="blogfiles/images/iphonewebapps/iPhoneTorrentSearch4.jpg" alt="How to enable Safari Developer mode" /> <img src="blogfiles/images/iphonewebapps/iPhoneTorrentSearch5.jpg" alt="How to enable Safari Developer mode" />
</dd>
</dl>
</li>
<li>
<dl class = "dlFindings">
<dt>Groovy has built-in JSON conversion support</dt>
<dd>At first, I thought I was going to need to use something like <a href="http://code.google.com/p/google-gson/">GSON</a> to automatically convert my objects into JSON, but Groovy can do this with built-in libraries. Check this out:</p>
<pre name = "code" class = "groovy">
		def namedResults = [:]

		results.each { ProviderService key, value ->
			namedResults[key.getName()] = value
		}

		render namedResults as JSON
</pre>
<p>This produces
<pre class = "javascript" name = "code">{"Demonoid":["Result1", "Result2",...],...}</pre>
<p> which is trivially parseable via the javascript JSON parser at <a href="www.json.org">JSON.org</a>.
</dd>
</dl>
</li>
<li>
<dl class = "dlFindings">
<dt>GPath is a decent substitute for XPath</dt>
<dd>I&#8217;m generally a big fan of XPath, but GPath ain&#8217;t so bad. Specifically, trying to find all the deepest nodes which match a certain criterion is pretty easy.</p>
<pre name = "code" class = "groovy">
		def slurper = new XmlSlurper()
		slurper.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)

		def doc = slurper.parseText(xml)

		//Find anchor tags for torrent links
		def allAnchorTags = doc.depthFirst().findAll { GPathResult node ->
			node["@class"] == "detLink"
		}
</pre>
<p>By combining <span class = "snippet">depthFirst()</span> and <span class = "snippet">findAll {&#8230;}</span>, one can filter all nodes in an XML document succinctly and with ease. The equivalent XPath <span class = "snippet">//a[@class='detLink']</span> would require some extra lifting to parse the results so neatly.
</dd>
</dl>
</li>
<li>
<dl class = "dlFindings">
<dt>Auto-wiring is magical</dt>
<dd>In the course of building the TorrentSearch application, I used nothing but auto-wiring to configure my services and controllers. This probably doesn&#8217;t scale all that well, but it worked well enough for my purposes. I tend to use the path of least resistance until it no longer works, and auto-injection via field name is definitely the path of least resistance. Code snippet:</p>
<pre name="code" class="java">
class TorrentSearchController
{
	def torrentProviderService
           ...
}
</pre>
<p>Simply by defining the service, it gets auto-injected with a singleton instance of the class named <span class="snippet">TorrentProviderService.</span>
</dd>
</dl>
</li>
</ol>
<h2>Conclusion</h2>
<p>Grails is a really neat way to develop applications, and it makes putting together simple web services incredibly easy. In the future, I&#8217;ll see how well this scales in the future, but for now it seems like <strong>the</strong> way to build super quick web applications on the JVM. jQTouch, on the other hand, is rough around the edges, although the potential of native web applications for mobile devices is promising. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=324</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Easy HTML web scraping with Groovy and Java. (w/XOM)</title>
		<link>http://www.progamonth.com/?p=312</link>
		<comments>http://www.progamonth.com/?p=312#comments</comments>
		<pubDate>Wed, 05 May 2010 04:28:19 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[code-snippet]]></category>
		<category><![CDATA[prog]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[xom]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=312</guid>
		<description><![CDATA[Ever need to parse some HTML is Java or Groovy? No matter what the source, you&#8217;re almost always guaranteed to get bad, unformed garbage as a response when scraping. Rather than ditch XML readers and bust out regex, you can transform this data into good xhtml with tools like TagSoup. The following class is a [...]]]></description>
			<content:encoded><![CDATA[<p>Ever need to parse some HTML is Java or Groovy? No matter what the source, you&#8217;re almost always guaranteed to get bad, unformed garbage as a response when scraping. Rather than ditch XML readers and bust out regex, you can transform this data into good xhtml with tools like <a href="http://home.ccil.org/~cowan/tagsoup/">TagSoup</a>.</p>
<p>The following class is a utility class meant to abstract away the nonsense of cleaning HTML. I&#8217;ve found that HTML data can come from a number of different sources (even files), so being able to clean strings containing html is immensely useful. </p>
<p><strong>HtmlParsingUtils.cleanHtml(String html)</strong> cleans the HTML passed as an argument and returns parse-able XHTML. It does not validate entities to avoid the 503 <a href="w3.org">w3.org</a> return errors if you attempt to hit the w3 servers too frequently when validating XML entities &#8211; which is exactly what happens when using TagSoup when doing massive scraping.</p>
<p><a href="www.xom.nu">XOM</a> is my XML handling library of choice, although the code can be adapted if requirements dictate no-XOM.</p>
<p><em>Example usage:</em></p>
<pre name="code" class="java">
String htmlData = obtainHtmlFromElsewhere();
String xml = HtmlParsingUtils.cleanHtml( htmlData );

Builder builder = HtmlParsingUtils.createNonValidatingXmlBuilder();
Document doc = builder.build(xml,HtmlParsingUtils.xhtmlBaseUri);
//Query: Find all anchor tags
Nodes nodes = doc.query("//html:a",HtmlParsingUtils.htmlCtx);
</pre>
<p>Presented below is the Groovy adaptation of <em>HtmlParsingUtils</em>. The Java version is identical, except the dummy entity resolver is built as private class declaration inline, rather than a closure.</p>
<pre name="code" class="java">
import nu.xom.Builder
import nu.xom.XPathContext
import org.jdom.input.SAXBuilder
import org.xml.sax.EntityResolver
import org.xml.sax.InputSource
import org.xml.sax.XMLReader
import org.xml.sax.helpers.XMLReaderFactory

/**
 * Utility class for handling html
 */
class HtmlParsingUtils
{
	public static final EntityResolver dummyEntityResolver = { String publicId, String systemId ->
		return new InputSource(new StringReader(""))
	} as EntityResolver;

	public static final xhtmlBaseUri = "http://www.w3.org/1999/xhtml"

	//Required for querying
	public static final XPathContext htmlCtx = new XPathContext("html", xhtmlBaseUri)

	/**
	 * @param str possibly non-well-formed html
	 * @return xhtml representation of the argument data
	 */
	public static String cleanHtml(String str)
	{
		SAXBuilder builder = new org.jdom.input.SAXBuilder("org.ccil.cowan.tagsoup.Parser"); // build
		builder.setEntityResolver(dummyEntityResolver);
		Reader input = new StringReader(str);
		org.jdom.Document doc = builder.build(input);
		String cleanXmlDoc = new org.jdom.output.XMLOutputter().outputString(doc);

		return cleanXmlDoc;
	}

   /**
	 * @return XOM Builder that does not validate or resolve entities.
	 */
	public static Builder createNonValidatingXmlBuilder()
	{
		XMLReader reader = XMLReaderFactory.createXMLReader();
		reader.setEntityResolver(dummyEntityResolver);
		Builder builder = new Builder(reader);

		return builder;
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=312</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails: Absolutely pure productivity.</title>
		<link>http://www.progamonth.com/?p=285</link>
		<comments>http://www.progamonth.com/?p=285#comments</comments>
		<pubDate>Fri, 30 Apr 2010 18:38:48 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[netbeans]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=285</guid>
		<description><![CDATA[Your IDE can do more. Recently, I decided I had a need to build a quick web service to back an AJAX application for iPhone that I&#8217;m developing. jQTouch is making the front-end work pretty simple, but I just wanted a super fast way to get a web service up and running that would be [...]]]></description>
			<content:encoded><![CDATA[<h1>Your IDE can do more.</h1>
<p>Recently, I decided I had a need to build a quick web service to back an AJAX application for iPhone that I&#8217;m developing. <a href="http://www.jqtouch.com">jQTouch</a> is making the front-end work pretty simple, but I just wanted a super fast way to get a web service up and running that would be maintainable and easy to scale. I considered <a href="http://www.springsource.com/products/enterprise">Spring</a> with Tomcat/Hibernate, but I didn&#8217;t want to spend a week configuring XML. I&#8217;ve attempted to Ruby/Rails in the past, but I always missed being off the JVM. Then, I came upon <a href="http://www.grails.org/">Grails</a>. It&#8217;s fast, it&#8217;s easy, and it&#8217;s Java (&#8230;ish), so in that sense there&#8217;s little to no learning curve aside from that of the Grails framework itself.</p>
<p>To begin my quest to utilize Grails, I attempted to setup Eclipse with the grails plugin. After a pound of headache, I just gave up. Then, I came upon <a href="http://www.grails.org/NetBeans+Integration">Netbeans grails integration</a>.</p>
<p><strong>Check this out.</strong></p>
<style type = "text/css">
.grailssetup li {
margin-bottom: 35px;
}
</style>
<ol class = "grailssetup">
<li>Create a project.<br />
<img src="images/grailspost/step1.png" alt="Step 1" /></li>
<li>Let grails do its magic.
<p><img src="images/grailspost/step2.png" alt="Step 2" /></li>
<li>Click the magic <strong><span style="color: #339966;">run arrow.</span></strong><br />
<img src="images/grailspost/step3.png" alt="Step 3" /></li>
<li>Watch Grails start automagically under Jetty.<br />
<img src="images/grailspost/step4.png" alt="Step 4" /></li>
<li>Create a Domain class.<br />
<img src="images/grailspost/step5.png" alt="Step 5" /></li>
<p><img src="images/grailspost/step6.png" alt="Step 6" />
</ol>
<p>Now, any changes you make in the IDE to the controllers, services, or domain classes gets picked up immediately by the running webserver. In one click, you can deploy your entire application. After that one click, everything just works. This is how all IDEs should handle server deployment. Aside from this ridiculously easy setup, grails gives you dependency management off the bat with <a href="http://ant.apache.org/ivy/">Ivy</a>, which can be configured to use the maven2 repositories.</p>
<p><strong>Check it out.</strong></p>
<p><img src="images/grailspost/dependencies.png" alt="Dependency management" /></p>
<p><strong>FURTHERMORE</strong>, grails deploys WARs for your application, so there&#8217;s no trickery to get your web application running. Develop under grails, then drop your WAR in your application container and be done with it.</p>
<p><strong>Use Grails. It&#8217;s awesome.</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=285</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OAuth is a joke.</title>
		<link>http://www.progamonth.com/?p=250</link>
		<comments>http://www.progamonth.com/?p=250#comments</comments>
		<pubDate>Sat, 13 Mar 2010 05:29:18 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[oauth]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=250</guid>
		<description><![CDATA[From oauth.net, OAuth is An open protocol to allow secure API authorization in a simple and standard method from desktop and web applications. Unfortunately, as it turns out, OAuth is neither simple nor standard in practice. In case you don&#8217;t care to read the tutorials, OAuth works something like this: You request a consumer key [...]]]></description>
			<content:encoded><![CDATA[<p>From <a href="http://oauth.net/">oauth.net</a>, OAuth is </p>
<blockquote><p>An <strong>open protocol</strong> to allow secure API authorization in a <strong>simple</strong> and <strong>standard</strong> method from desktop and web applications.</p></blockquote>
<p>Unfortunately, as it turns out, OAuth is neither simple nor standard in practice. In case you don&#8217;t care to read the tutorials, OAuth works something like this:</p>
<ol>
<li>You request a consumer key and consumer secret from a &#8220;service provider&#8221; (such as Twitter).</li>
<li>You use this consumer key and secret to request a &#8220;request key&#8221; (insecure).</li>
<li>You use the request key to generate a URL that the user can go to to authenticate.</li>
<li>You either do, or don&#8217;t, pass a callback URL to the above request to receive the response token.</li>
<li>Your callback URL gets hit, which contains the token needed to request an &#8220;access token&#8221; and &#8220;access token secret&#8221;, which may or may not expire or become invalid at any time.</li>
</ol>
<p>These steps, however, are not so clear cut when you actually start using service providers which offer OAuth authentication.</p>
<p> Let&#8217;s look at the behavior of some big-name web services which have adopted OAuth.</p>
<p><img src="http://twitter.com/images/logo.png" alt="Twitter logo" /></p>
<p>Twitter, I think, has taken a progressive approach to OAuth authentication. If you don&#8217;t pass a callback URL, you get a pretty screen prompting the user to deliver a PIN code to the application from which you&#8217;ve come.</p>
<p><img src="blogfiles/images/twitter_oauth.png" alt="Twitter pretty pin entry" /></p>
<p>This looks great, right? Well, if you try the same stuff on <a href="http://www.tripit.com">TripIt</a>, you just get the return data.<br />
<img src = "http://www.tripit.com/images/header/logo.png" alt = "TripIt logot" /></p>
<p><strong>Response:</strong></p>
<blockquote><p>oauth_token=935394b819ab32c9558e7063dbb3bcda9c274a00</p></blockquote>
<p>TripIt presents no user display, so you&#8217;re stuck if you didn&#8217;t want to a provide a callback URL. Once you understand that Twitter just does things differently, you begin to assume that using a callback URL would work swimmingly. Well, if you wanted Twitter support, you just lost it. Look at Twitter&#8217;s response to a request with a callback URL specified:</p>
<p><strong>Response URL:</strong></p>
<p>http://stefankendall.com:8080/test.jsp?oauth_token=0yLxRrUoxHJxA0tF8hJSxP2EHfFaYyw1a3nW4Dqg&#038;oauth_verifier=Alzk3ehPRq6bbjvISlgXqn9Jk7yZJlmst0jtXpg</p>
<p>That&#8217;s right. TWO values, whereas TripIt just provided one. You&#8217;ll notice that oauth_token is now the token you requested with, and oauth_verifier is the real data you need. This is a direct contradiction in the naming and response schemes of TripIt and Twitter. Oy vey.</p>
<p>I would go on about Netflix, but that&#8217;s a jump down the rabbit hole I&#8217;m not willing to take right now.</p>
<p>OAuth is a joke, and as it stands, it&#8217;s neither simple nor a standard. Good grief.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=250</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby and named regex matched groups.</title>
		<link>http://www.progamonth.com/?p=222</link>
		<comments>http://www.progamonth.com/?p=222#comments</comments>
		<pubDate>Wed, 17 Feb 2010 16:35:59 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=222</guid>
		<description><![CDATA[Back from China, I&#8217;ve resume my normal programming schedule. I&#8217;m working through Pragmatic Bookshelf&#8217;s Programming Ruby, and there&#8217;s a lot more to ruby than I initially gave credit. For example, consider the following: str = 'an' * 3000 + 'garbage' + 'an'*3000 r = /(?&#60;pattern&#62;.*) #The first part (?:.*?) #Garbage \k&#60;pattern&#62;/x #The first part, repeated. [...]]]></description>
			<content:encoded><![CDATA[<p>Back from China, I&#8217;ve resume my normal programming schedule. I&#8217;m working through <a href="http://www.pragprog.com/titles/ruby/programming-ruby">Pragmatic Bookshelf&#8217;s Programming Ruby</a>, and there&#8217;s a lot more to ruby than I initially gave credit. For example, consider the following:</p>
<pre name = "code" class = "ruby">
str = 'an' * 3000 + 'garbage' + 'an'*3000
r = /(?&lt;pattern&gt;.*) #The first part
    (?:.*?) #Garbage
    \k&lt;pattern&gt;/x #The first part, repeated.
str =~ r
puts $1.length
</pre>
<p>First, we create a repeated string, followed by some garbage data, followed by that string again. A pattern is built to find the largest prefix which is also a suffix, given a break in data. Ruby lets us name the regex</p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=222</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XSLT: How you should be transforming XML into HTML.</title>
		<link>http://www.progamonth.com/?p=180</link>
		<comments>http://www.progamonth.com/?p=180#comments</comments>
		<pubDate>Tue, 05 Jan 2010 20:50:43 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xslt]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=180</guid>
		<description><![CDATA[XSLT is a method of transforming XML with a set of rules, functions, and selectors. Transformations can be complex or simple, but the benefit of using XSLT is immediately obvious after first use. Consider the following: &#60;posts&#62; &#60;post&#62; &#60;title&#62;XSLT!&#60;/title&#62; &#60;description&#62;A short post about XSLT&#60;/description&#62; &#60;content date = &#34;01/03/2009&#34;&#62; Lorum ipsum &#60;/content&#62; &#60;/post&#62; &#60;posts&#62; The naive [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.w3schools.com/xsl/">XSLT</a> is a method of transforming XML with a set of rules, functions, and selectors. Transformations can be complex or simple, but the benefit of using XSLT is immediately obvious after first use.</p>
<p>Consider the following:</p>
<pre name = "code" class = "xml">
&lt;posts&gt;
   &lt;post&gt;
      &lt;title&gt;XSLT!&lt;/title&gt;
      &lt;description&gt;A short post about XSLT&lt;/description&gt;
      &lt;content date = &quot;01/03/2009&quot;&gt;
      Lorum ipsum
      &lt;/content&gt;
   &lt;/post&gt;
&lt;posts&gt;</pre>
<p>The naive approach of displaying this to the user is to manually parse the data with an XML parser of some kind. I&#8217;ve done this in previous projects; it works, but it&#8217;s generally stuck in code, which means that changes to the output format require recompilation or some other elaborate build and deployment. This is inherently wrong given the process that&#8217;s taking place. A transformation of XML can and should be independent from the XML itself.</p>
<p>Here&#8217;s some pseudocode for the rendering of an XML document into HTML:</p>
<pre name = "code" class = "python">
html = '&lt;html&gt;&lt;body&gt;'
for node in document.find( 'post' )
    title = node.find( 'title' ).text
    descriptionNode = node.find( 'description' )
    postDate = descriptionNode.attribute( 'date' )
    descriptionText = descriptionNode.text

    html += '&lt;div&gt;'
    html += '&lt;h1&gt;' + title + '&lt;/h1&gt;'
    html += '&lt;p&gt;' + descriptionText + '&lt;/p&gt;'
    html += '&lt;p&gt;&lt;em&gt;' + postData + '&lt;/em&gt;&lt;/p&gt;'
    html += '&lt;/div&gt;'

html += '&lt;/body&gt;&lt;/html&gt;'
render(html)
</pre>
<p>While this is straightforward enough in the trivial example, it falls apart when parsing large, complex documents. Consider now the XSLT equivalent:</p>
<pre name = "code" class = "xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;xsl:stylesheet xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot; version=&quot;2.0&quot;&gt;
    &lt;xsl:template match=&quot;/&quot;&gt;
        &lt;html&gt;
            &lt;body&gt;
                &lt;xsl:apply-templates /&gt;
            &lt;/body&gt;
        &lt;/html&gt;
    &lt;/xsl:template&gt;
    &lt;xsl:template match = &quot;post&quot;&gt;
        &lt;div&gt;
            &lt;xsl:apply-templates /&gt;
        &lt;/div&gt;
    &lt;/xsl:template&gt;
    &lt;xsl:template match = &quot;title|description&quot;&gt;
        &lt;p&gt;&lt;xsl:apply-templates /&gt;&lt;/p&gt;
    &lt;/xsl:template&gt;
    &lt;xsl:template match = &quot;content&quot;&gt;
        &lt;p&gt;&lt;xsl:apply-templates /&gt;&lt;/p&gt;
        &lt;p&gt;&lt;em&gt;&lt;xsl:value-of select=&quot;@date&quot; /&gt;&lt;/em&gt;&lt;/p&gt;
    &lt;/xsl:template&gt;
&lt;/xsl:stylesheet&gt;
</pre>
<p>Although the trivial example is longer in terms of characters, there are numerous benefits to this approach.</p>
<ol>
<li>The transformation is externalized. If you decide that all post divs now need a &#8220;post&#8221; class, you don&#8217;t need to recompile, and you know exactly where to make the change.</li>
<li>Presumably, your XSLT editor can validate XML, or at least tell you when you&#8217;re missing a closing angle bracket or two. Most IDEs will not see unclosed angle brackets within strings as a problem, so in you get a proper environment in which to craft your output HTML. Sure, you could use an XML library that hides this implementation from you, but you still run the risk of missing an element or forgetting to append nodes to one another. This wastes time. With a XSLT document, you can very clearly easily about your output <strong>before testing</strong>. This emphasizes another issue.</li>
<li>Good XSLT editors will let you quickly and easily run XSLT against XML. Using <a href="http://www.oxygenxml.com/">oXygen</a>, I was able to develop the above document in under a minute. Actually testing manually-manipulated XML, on the other hand, takes much more time.</li>
</ol>
<p>All of this said, there are still reasons to avoid XSLT in certain situations. All browsers do not support XSLT, and there are few XSLT 2.0 processors at the moment. Ergo, you must perform your transformations on the server, rather than on the client, but you should probably be doing that anyway. Furthermore, maintenance programmers will need to know XSLT to debug and extend your application, so if you&#8217;re worried about limited knowledge handling your software, it may be best to simply avoid XSLT altogether.</p>
<p>I&#8217;ve quickly found that XSLT is often the right tool for the job, however, so it would be a sin to not learn enough of the technology to recognize when its applicable and when it isn&#8217;t. Don&#8217;t craft your HTML by hand, but only use XSLT when it&#8217;s appropriate.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=180</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring 2.5 with SpringMVC</title>
		<link>http://www.progamonth.com/?p=125</link>
		<comments>http://www.progamonth.com/?p=125#comments</comments>
		<pubDate>Thu, 19 Nov 2009 02:23:22 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[spring junit tomcat xom]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=125</guid>
		<description><![CDATA[This month, I decided to go more in-depth with Spring and SpringMVC and model the web services for a CMS/Shopping Cart system. With Spring, Tomcat, XOM, and JUnit, I was able to speedily throw together a modular, DI-driven web service that implemented a simple web service interface without needing to worry about database details or [...]]]></description>
			<content:encoded><![CDATA[<p>This month, I decided to go more in-depth with <a href="http://www.springsource.org/">Spring</a> and <a href="http://static.springsource.org/spring/docs/2.5.x/reference/mvc.html">SpringMVC</a> and model the web services for a CMS/Shopping Cart system. With Spring, Tomcat, <a href="http://www.xom.nu/">XOM</a>, and JUnit, I was able to speedily throw together a modular, DI-driven web service that implemented a simple web service interface without needing to worry about database details or request mapping.</p>
<p>Specifically, Spring&#8217;s MultiActionController and XOM&#8217;s XML building utilities let me write the minimal AccountController given below.</p>
<pre name = "code" class = "java">
public class AccountController extends MultiActionController
{
private AccountManagementService accountManagementService;

public ModelAndView login( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.login( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public ModelAndView register( HttpServletRequest request, HttpServletResponse response ) throws IOException
{
   String username = StringEscapeUtils.escapeHtml( request.getParameter( "username" ) );
   String password = StringEscapeUtils.escapeHtml( request.getParameter( "password" ) );
   Document xmlDoc = accountManagementService.register( username, password );

   response.getWriter().println( xmlDoc.toXML() );

   return null;
}

public void setAccountManagementService( AccountManagementService accountManagementService )
{
   this.accountManagementService = accountManagementService;
}
}
</pre>
<p>The URL mapping for service requests was also dead-simple:</p>
<pre name = "code" class = "xml">
&lt;bean id=&quot;urlMappingDeployment&quot; class=&quot;org.springframework.web.servlet.handler.SimpleUrlHandlerMapping&quot;&gt;
      &lt;property name=&quot;mappings&quot;&gt;
         &lt;props&gt;
             &lt;prop key=&quot;/login.do&quot;&gt;accountController&lt;/prop&gt;
             &lt;prop key=&quot;/register.do&quot;&gt;accountController&lt;/prop&gt;
             &lt;prop key=&quot;/getInventory.do&quot;&gt;inventoryController&lt;/prop&gt;
             &lt;prop key=&quot;/updateInventory.do&quot;&gt;inventoryController&lt;/prop&gt;
          &lt;/props&gt;
      &lt;/property&gt;
   &lt;/bean&gt;
</pre>
<p>By utilizing Spring, I saved reams of code, although using a more expressive language like Groovy with Grails may have been quicker and more expressive. At any rate, I&#8217;m off to go learn about XSLT. Cheers. <img src='http://www.progamonth.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=125</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Scala &#8211; fun, powerful JVM fun</title>
		<link>http://www.progamonth.com/?p=108</link>
		<comments>http://www.progamonth.com/?p=108#comments</comments>
		<pubDate>Mon, 12 Oct 2009 13:19:22 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=108</guid>
		<description><![CDATA[If you&#8217;re like me, you heard about this language on the Java Posse Pod-cast (link), and you&#8217;re just now trying to figure out what all the hubbub is about. Well, Scala is functional, declaration, strongly typed (although it doesn&#8217;t feel like it), and most importantly, a JVM language. it compiles to Java classes, and with [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re like me, you heard about this language on the Java Posse Pod-cast (link), and you&#8217;re just now trying to figure out what all the hubbub is about. Well, Scala is functional, declaration, strongly typed (although it doesn&#8217;t feel like it), and most importantly, a JVM language. it compiles to Java classes, and with the inclusion of a single library, you can work Scala quite easily into your web application, either by design or postfixed.</p>
<p>Aside from ease of integration, Scala also offers many functional concepts: first-class functions, curried functions, partially applied functions, and in simple cases, tail recursion! Object-Oriented purists can continue to work as they would in Java, but those of us willing to dabble in the dark-arts can do things like this:</p>
<pre name = "code" class = "scala">
class MyApplication extends Application {
   println( "Hello, World!" )
}
</pre>
<p>See what&#8217;s happening? The closure between the braces is passed as a constructor argument to MyApplication, which then executes the function. It&#8217;s not that much of a convenience, but for small applications, <code>public static void main( String[] args )</code> is just annoying. </p>
<h3>Tomcat</h3>
<p>Remember how I said Scala could run under Tomcat as easily as Java? Well, I setup a servlet on my server to proxy file downloads. Try this:</p>
<p><a href="http://stefankendall.com:8080/download?url=http://stefankendall.com/files/test.txt">http://stefankendall.com:8080/download?url=http://stefankendall.com/files/test.txt</a></p>
<p>It&#8217;s not much to see, but the code is pretty simple!</p>
<pre name = "code" class = "scala">
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}
import javax.servlet.ServletOutputStream
import java.net.URL
import java.io.{BufferedInputStream, PrintStream, StringWriter, PrintWriter }

class ProxyDownloadServlet extends HttpServlet
{
	override def doGet( request: HttpServletRequest,	response: HttpServletResponse )
	{
		//get the file url to download from the GET request parameter
		val fileUrl = request.getParameter( &quot;url&quot; );

		//if no url was provided, write that to the user
		if( fileUrl == null )
		{
			response.getWriter().println( &quot;&lt;html&gt;&lt;body&gt;&lt;p&gt;No download url!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;&quot; )
			return
		}

		try
		{
			//download the file
			val inputStream = new BufferedInputStream( new URL( fileUrl ).openStream() )

			//set the content type of the response so the
			//user will be prompted to download
			response.addHeader( &quot;Content-Type&quot;,&quot;application/octet-stream&quot;);

			//get the output stream
			val outputStream = response.getOutputStream();

                                  //data buffer
			var buffer = new Array[byte](4 * 1024)

			var bytesRead = inputStream.read( buffer )
			while( bytesRead != -1 )
			{
				outputStream.write( buffer, 0, bytesRead )
				bytesRead = inputStream.read( buffer )
			}
		}
		catch
		{
			case e =&gt; {
				println( &quot;Attempted to download:&quot; )
				println( fileUrl )
				e.printStackTrace()
				response.setContentType(&quot;text/html&quot;)
				outputStream.println( &quot;&lt;html&gt;&lt;body&gt;&lt;p&gt;Bad file url!&lt;/p&gt;&quot; )
				outputStream.println( &quot;&lt;p&gt;File: &quot; )
				outputStream.println( fileUrl );
				outputStream.println( &quot;&lt;/p&gt;&quot; )
				outputStream.println( &quot;&lt;/body&gt;&lt;/html&gt;&quot; )
			}
		}
		finally
		{
			inputStream.close()
			outputStream.close()
		}
	}
}
</pre>
<p>I had some trouble getting things like String concatenation working under Tomcat (Yeah, I know.), and the tools for Scala are rather weak right now (at least the eclipse plugin), but it&#8217;s definitely not Java! There&#8217;s probably a more Scala way to do this, but that just illustrates the point: you can use as much, or little, Java-isms as you see fit. Remember that this compiles to .class files, so it can mingle with other Java servlets as easily as other Java could.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=108</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[[Objective-C prog] with: iPhone and: iTunes release]</title>
		<link>http://www.progamonth.com/?p=93</link>
		<comments>http://www.progamonth.com/?p=93#comments</comments>
		<pubDate>Wed, 16 Sep 2009 19:26:08 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=93</guid>
		<description><![CDATA[Doesn&#8217;t that subject line look crazy? Well, in Objective-C, methods, properties, and members are accessed with maniacal brackets. This is fine, aside from the fact that you need to know how deep you&#8217;re going to chain a method call BEFORE you actually do it, as otherwise you have to go back and add the correct [...]]]></description>
			<content:encoded><![CDATA[<p>Doesn&#8217;t that subject line look <em>crazy</em>? Well, in Objective-C, methods, properties, and members are accessed with maniacal brackets. This is fine, aside from the fact that you need to know how deep you&#8217;re going to chain a method call BEFORE you actually do it, as otherwise you have to go back and add the correct number of left brackets. Objective-C 2.0, as supported on the iPhone, supports dot notation, but when in Rome, I hear you use crazy bracket syntax. So, then, how does this all play out? Well, iPhone development can really be sectioned off into its constituting parts: <em><strong>Objective-C programming</strong></em>, <em><strong>Interface Builder</strong></em>, and <em><strong>release to the app store on iTunes</strong></em>.</p>
<h2>Objective-C</h2>
<p>Objective-C 2.0 has properties, strong typing, and memory management. Objective-C for the iPhone only has the first two. For this reason, we&#8217;re forced to deal with memory management or deal with the terrible results. In making a simple business calculator, I was able to leak 6 UI elements each time the program was run and take my 3GS iPhone down to a few MB of remaining ram in only 7 or so test runs. The solution, of course, was simply releasing the UI objects when the application was closing, but this is a significant annoyance when trying rapidly design software.</p>
<p>True properties, of course, with synthesized property methods, save a decent amount of time and just look nicer than having your IDE generate getters and setters.</p>
<p>Consider the following:</p>
<pre>
//Tester.h
@interface Tester
{
   MyClass * myClass;
}
@property MyClass * myClass;
@end

//Tester.m
@implementation Tester
@synthesize myClass;
@end
</pre>
<p>Now, [testObj myClass] calls the implicitly created getter of Tester, and [testObj setMyClass: myClass] calls the implicitly generated setter. Isn&#8217;t that cool?</p>
<h2>iPhone Development</h2>
<p>Aside from the Objective-C nonsense, the iPhone SDKs and Interface Builder make life pretty easy for app development. Interface Builder provides a full visual interface for designing iPhone applications, and XCode even provides an iPhone emulator with which to test applications. Sure, the emulator won&#8217;t tell you if you have a memory leak, or anything of that nature, but there are other tools to monitor such.<br />
<code>/* TODO: add screenshots */</code></p>
<h2>iTunes and iTunes Connect</h2>
<p>The release process to iTunes, while relatively painless, requires a wealth of information and takes about two weeks to process (at least it did for <b>FoodWatcher</b>, my &#8220;Hello World&#8221; iTunes application to measure weightwatchers points).</p>
<p>The following is required to submit an application to the app store:</p>
<ul>
<li>application name</li>
<li>application version</li>
<li>512&#215;512 image to represent the application. This is used if the application gets &#8220;featured.&#8221;</li>
<li>57&#215;57 iPhone icon for the application. You can either add your own gloss or let the iPhone render it for you.</li>
<li>At least 1 screenshot of the application in progress</li>
<li>A support website for the application</li>
<li>A support email for the application</li>
<li>A list of user names/passwords if your application requires it</li>
</ul>
<p>and for non-free applications, you need to provide full tax/bank information. The process is a bit of a hassle, but the requirements make sense given the context of iTunes and the App Store.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=93</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery: Plugins.</title>
		<link>http://www.progamonth.com/?p=56</link>
		<comments>http://www.progamonth.com/?p=56#comments</comments>
		<pubDate>Wed, 19 Aug 2009 01:39:22 +0000</pubDate>
		<dc:creator>Stefan Kendall</dc:creator>
				<category><![CDATA[prog]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.progamonth.com/?p=56</guid>
		<description><![CDATA[Lorum Ipsum and such jQuery has plugins. Lots of them, in fact. The jQuery plugin page lists hundreds of additions to the base jquery package. These plugins make web development even easier and more glamorous than jQuery alone, doing splendid things like Show dialogs. Now isn&#8217;t that cool? jQuery plugins let external authors write neat [...]]]></description>
			<content:encoded><![CDATA[<div id="dialog" title="Dialog Title" style="display:none">Lorum Ipsum and such</div>
<h2>jQuery has plugins.</h2>
<p>Lots of them, in fact. The <a href="http://plugins.jquery.com/">jQuery plugin page</a> lists hundreds of additions to the base jquery package. These plugins make web development even easier and more glamorous than jQuery alone, doing splendid things like <a id = "dialogLink" href = "#">Show dialogs</a>.</p>
<p>Now isn&#8217;t that cool? jQuery plugins let external authors write neat libraries to extend the language, much as firefox extensions improve the core of firefox. As jQuery has become the javascript go-to tool of choice, jQuery plugins have become the library tools of choice for productive, external-library-oriented developers, such as you and me. So fly, ye&#8217; programmer, and explore the world of jQuery plugins.</p>
<link rel = "stylesheet" type = "text/css" href = "files/jquery-ui/css/smoothness/jquery-ui-1.7.2.custom.css" />
<script type = "text/javascript" src="files/jquery-ui/js/jquery-ui-1.7.2.custom.min.js" ></script><br />
<script type = "text/javascript">
$(document).ready(function(){
$('#dialogLink').click(function(){
$("#dialog").dialog();
});
});
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.progamonth.com/?feed=rss2&amp;p=56</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
