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

<channel>
	<title>Fiascode</title>
	<atom:link href="http://www.fiascode.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.fiascode.com</link>
	<description>Coding and such...</description>
	<pubDate>Sun, 05 Oct 2008 21:32:31 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>Getting it on with Git - Part 2</title>
		<link>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2/</link>
		<comments>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 21:20:09 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[General Technology]]></category>

		<category><![CDATA[Git]]></category>

		<category><![CDATA[Project Management]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=21</guid>
		<description><![CDATA[In my previous post I introduced Git and discussed its distributed nature, speed, and powerful branching/merging capabilities.  Today I'm going to continue the discussion on Git by writing about GitHub, Git in practice, and why Git may not be for everyone.

GitHub is Sexy
GitHub is an online Git repository hosting service that is freely available [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.fiascode.com/general-technology/getting-it-on-with-git-part-1/">previous post</a> I introduced <a href="http://git.or.cz/">Git</a> and discussed its distributed nature, speed, and powerful branching/merging capabilities.  Today I'm going to continue the discussion on Git by writing about GitHub, Git in practice, and why Git may not be for everyone.</p>
<span id="more-21"></span>
<h3 id="github_sexy">GitHub is Sexy</h3>
<p><a href="http://github.com/">GitHub</a> is an online Git repository hosting service that is freely available to anyone who wishes to share their Git managed projects.  The service is very similar to <a href="http://sourceforge.net/">SourceForge</a> and <a href="http://code.google.com/hosting/">Google Code Hosting</a>, but because GitHub uses Git as its source control management system it offers a variety of advantages over other code hosting services.</p>
<p>To begin with, by using GitHub the barrier for working on and contributing to open source projects is significantly reduced.  In traditional centralized models only certain developers are given commit rights to any given project repository.  This creates a problem however for those developers who checkout the project and make changes.  Those developers have no way of keeping track of their local changes and history unless they import the project into their own centralized repository.  Doing this however means that the developer will lose the ability to easily synchronize their local project with the original project.</p>
<p>This problem goes away when using Git because all commits are local.  You can checkout a project from GitHub, makes changes as you wish, and commit them to your local repository.  This allows you to keep track of all of your changes and their history.  If you want to synchronize with the original project's repository you simply need to issue a "pull" command to get the latest updates.  As a bonus, if you come up with some feature that you think is particularly useful to the original project, you can ask the owner of that project to issue a "pull" request from your repository so your changes can be merged back into the master project.</p>
<p>Setting up your own remote Git repository is not that difficult, but GitHub adds a great web interface on top of Git that feels very much like a social networking site and serves as a platform for developers to share and contribute to each other's projects.  A lot of big name open source projects (especially in the Ruby community) are hosted on GitHub including <a href="http://www.rubyonrails.org/">Rails</a>, <a href="http://merbivore.com/">Merb</a>, and <a href="http://script.aculo.us/">Script.aculo.us</a> so developers can feel confident that the guys at GitHub have their act together.  GitHub also offers a variety of other features including private repositories (for a fee), a developer API, and integration with other services including <a href="http://www.basecamphq.com/">Basecamp</a>, <a href="http://lighthouseapp.com/">Lighthouse</a>, and <a href="http://twitter.com/">Twitter</a>.</p>
<h3 id="git_in_practice">Git in Practice</h3>
<p>It's highly unlikely that a developer will be able to get their current project team to switch version control systems overnight, but with Git you don't have to.  Git has powerful migration tools that can be used in conjunction with other version control systems, especially <a href="http://subversion.tigris.org/">Subversion</a>.  Current Subversion users can use Git to manage the source code on their local machine while still staying in sync with their team's Subversion repository using a built in Git command called "<a href="http://www.kernel.org/pub/software/scm/git/docs/git-svn.html">git-svn</a>".  The git-svn command allows developers to "push" and "pull" commits to and from a centralized Subversion repository.  This gives developers the power of local branching/merging capabilities using Git without forcing the technology on their team members.  In fact, no one even needs to know that Git is being used.</p>
<h3 id="git_not_for_everyone">Git, it's not for everyone</h3>
<p>Git is a pretty incredible tool, but it is likely not going to be championed by all developers.  To begin with, Git's learning curve can be a bit steep especially when compared with other version control tools.  Developers who desire to give Git a shot should be very comfortable working with the command line because Git's visualization support leaves something to be desired.</p>
<p>Git was created by Linux kernel developer Linus Torvalds so it may not come as a huge surprise that Git support on Windows is a bit lackluster.  I would guess that a majority of developers use Windows in some capacity so having a tool with weak Windows support is likely to hinder the adoption of that tool.  Fortunately, there is a project called <a href="http://code.google.com/p/msysgit/">MSysgit</a> which allows developers to use Git on their Windows machines.  I've personally used this tool on my Windows XP laptop and find that it works pretty well.</p>
<h3>Conclusion</h3>
<p>Minor drawbacks aside, Git is a pretty amazing tool for source control management and will be the one that I use for my future projects.  Its distributed nature, speed, and branching/merging capabilities make it a great tool for managing source code changes and revision history.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Getting it on with Git - Part 1</title>
		<link>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-1/</link>
		<comments>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-1/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 02:40:56 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[General Technology]]></category>

		<category><![CDATA[Git]]></category>

		<category><![CDATA[Project Management]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=20</guid>
		<description><![CDATA[When I first heard about Git a few months ago the first thing that popped in my mind was: "Why the hell would I ever want to learn a new version control system?"  Subversion works perfectly fine, doesn't it?  I resisted at first, but after a few weeks I came around and decided [...]]]></description>
			<content:encoded><![CDATA[<p>When I first heard about <a href="http://git.or.cz/">Git</a> a few months ago the first thing that popped in my mind was: "Why the hell would I ever want to learn a new version control system?"  Subversion works perfectly fine, doesn't it?  I resisted at first, but after a few weeks I came around and decided to take Git for a test drive.  This is what I discovered:</p>
<span id="more-20"></span>
<h3>Distributed Source Code Management</h3>
<p>Git is a <strong><em>distributed</em></strong> source code management tool which means that there is no centralized source code repository.  This is a fundamental shift in the way source control is handled by systems like <a href="http://subversion.tigris.org/">Subversion</a>, <a href="http://www.nongnu.org/cvs/">CVS</a>, and <a href="http://www.perforce.com/">Perforce</a> and is probably the most challenging concept to grasp (it certainly was for me) when first learning about Git.  Version control using a centralized model is useful for things such as sharing code among developers, providing a history of changes to the code, and backing up data in a single location.  However, since Git does not use a centralized repository, a few obvious questions are raised about the Git's workflow model.  Questions like:</p>
<p><strong><em>Where are code commits stored?</em></strong></p>
<p>All code commits are stored on each developer's local machine.  Everyone has a copy of the entire repository and all of its history.</p>
<p><strong><em>How do developers share code?</em></strong></p>
<p>Developers share code with Git by executing commands called "push" and "pull".  Issuing a push command will push changes made in your repository to another developer's repository.  Conversely, issuing a pull command will pull changes from another developer's repository into your repository.  This may seem strange at first, but it actually ends up providing developers with a lot of collaborative power.  For example, instead of checking code changes into a central repository for everyone to see, two or more developers can share code with one another directly in a controlled fashion by pushing and pulling changes to and from each of their repositories respectively.</p>
<p><strong><em>How are backups handled in Git?</em></strong></p>
<p>If all of my code commits are stored on my local machine and my hard drive fails, wouldn't I be in a lot of trouble?  Not with Git.  If you are working by yourself, regularly backing up your repository using <a href="http://samba.anu.edu.au/rsync/">rsync</a>, <a href="http://mozy.com/">Mozy</a>, <a href="http://www.apple.com/timecapsule/backup.html">Time Capsule</a> or some other backup system will allow you to completely restore all of your work.  This is because Git stores all code revisions and history within each repository.</p>
<p>If you are working with other developers you simply need to <a href="http://www.kernel.org/pub/software/scm/git/docs/git-clone.html">clone</a> their copy of the repository.  In this sense, Git is actually incredibly fault-tolerant in that it provides geographically redundant archives of a repository because each repository is essentially a mirror of the entire project.</p>
<p>Finally, you could use one of the many publicly available Git repositories including <a href="http://github.com/">GitHub</a> and <a href="http://repo.or.cz/">repo.or.cz</a>.</p>
<h3>Git is Blazing Fast</h3>
<p>Since all commits, branching, and merging operations are local, Git is fast.  Real fast.  Unless you are pushing or pulling code there is no network to worry about.  Increased speed means developers can be more productive because they don't have to spend time waiting for costly repository operations to take place across a network.</p>
<h3>Git Makes Branching and Merging Easy</h3>
<p>In a centralized version control system branching and merging can often times be a source of frustration for developers.  All branches must live in the centralized repository and are likely viewable by other developers on the team.  If enough developers decide to create branches on the centralized server the repository can quickly become bloated.</p>
<p>Git takes a different approach.  Branching and merging in Git occur locally.  This dramatically increases the speed in which branching and merging can take place.  In addition, a single developer can create and destroy as many branches as they desire without having to worry about polluting a centralized repository.  Experimental features can quickly and easily be tested by creating a branch from the current working copy's "master" branch.  If the code produced in the branch proves worthy, it can be merged back into the "master" branch.  If the code from the branch ends up being useless, the branch can simply be deleted and no one ever needs to know that it existed.</p>
<h3>Part 1 Wrap Up</h3>
<p>Sunday I'll post <a href="http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2/">Part 2</a> of my "Getting it on with Git" series where I'll discuss <a href="http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2#github_sexy">GitHub</a>, <a href="http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2#git_in_practice">Git in practice</a>, and why <a href="http://www.fiascode.com/general-technology/getting-it-on-with-git-part-2#git_not_for_everyone">Git may not be for everyone</a>.  Be sure to check back then!</p>
<h3>Useful Links</h3>
<p><a href="http://git.or.cz/">Official Git Site</a></p>
<p><a href="http://git.or.cz/gitwiki/GitCheatSheet">Git Cheat sheet</a></p>
<p><a href="http://www.youtube.com/watch?v=8dhZ9BXQgc4">Google Tech Talk on Git</a></p>
<p><a href="http://www.youtube.com/watch?v=4XpnKHJAok8">Linus Torvalds on Git</a></p>
<p><a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/book.html">GitMagic Book</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/general-technology/getting-it-on-with-git-part-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Groovy Domain Specific Language Tutorial</title>
		<link>http://www.fiascode.com/programming/groovy-domain-specific-language-tutorial/</link>
		<comments>http://www.fiascode.com/programming/groovy-domain-specific-language-tutorial/#comments</comments>
		<pubDate>Mon, 18 Aug 2008 00:42:05 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=19</guid>
		<description><![CDATA[Although it may seem like an advanced topic, writing a simple Domain Specific Language (DSL) in Groovy is actually pretty easy.  Groovy's dynamic nature and metaprogramming capabitlities give developers all the tools they need to quickly and easily write their own DSL.

Domain Specific Languages are typically small, simple languages with a highly expressive syntax [...]]]></description>
			<content:encoded><![CDATA[<p>Although it may seem like an advanced topic, writing a simple <a href="http://en.wikipedia.org/wiki/Domain-specific_programming_language">Domain Specific Language (DSL)</a> in <a href="http://groovy.codehaus.org/">Groovy</a> is actually pretty easy.  Groovy's dynamic nature and metaprogramming capabitlities give developers all the tools they need to quickly and easily write their own DSL.</p>
<span id="more-19"></span>
<p>Domain Specific Languages are typically small, simple languages with a highly expressive syntax and grammar.  In computing, DSLs are used to provide domain experts (who may or may not have prior programming experience) with programming capabilities limited to their specific area of expertise.</p>
<p>There are two types of DSLs: external and internal.  External DSLs allow you to define a new language using any grammar or syntax you wish.  External DSLs must then be parsed and executed by the programming language of your choice.  Internal DSLs also define a new language, but are limited to the constructs made available by the implementing language.  Because of their dynamic features, languages like Groovy and Ruby make writing internal DSLs relatively easy.</p>
<h3>A Stock Trading DSL</h3>
<p>A few weeks ago <a href="http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/">I wrote about trading stocks</a> using Google's Finance API.  Sticking with that theme, I thought it would be cool to write a Domain Specific Language that could also be used to mimic stock trading activities.</p>
<p>I'm guessing that most Wall Street traders don't know much about programming, but I'm sure most traders could decipher the actions that would take place after executing the following code:</p>
<div class="codeBlock">
	<pre><code>buy 500, "AAPL", 179.30
buy(250, "AAPL", 179.30) <strong>//parenthesis are optional</strong>
buy 500, "SUNW", 10.14
sell 350, "AAPL", 179.30

show_transactions "AAPL"

print_portfolio_value</code></pre>	
</div>
<p>The code above is actual Groovy code.  It tells the application to buy 750 shares of Apple stock at $179.30 in two separate transactions, buy 500 shares of Sun Microsystems stock at $10.14, and then sell 350 shares of Apple stock at $179.30.  After all the transactions take place the code shows the transaction history for the Apple trades and then prints the total value of the portfolio.</p>
<p>The Groovy code to drive the functionality behind this simple DSL looks like this:</p>
<div class="codeBlock">
	<pre><code><strong>portfolio = [:] //Holds all of the stock transactions</strong>

/**
 *A simple object to hold the data for each individual transaction
 */
class StockTransaction {
    def tickerSymbol
    def numberOfShares
    def sharePrice
    def type
    def transactionDate
}

def buy(numberOfShares, symbol, sharePrice){
    transaction('Buy', numberOfShares, symbol, sharePrice)    
}

def sell(numberOfShares, symbol, sharePrice){
    transaction('Sell', numberOfShares, symbol, sharePrice)        
}

def transaction(transactionType, numberOfShares, symbol, sharePrice){
    def transaction = new StockTransaction(tickerSymbol:symbol, 
        numberOfShares:numberOfShares, sharePrice:sharePrice, 
        type:transactionType, transactionDate:new Date())
        
    println "${transaction.type}ing ${transaction.numberOfShares} shares" +
        " of ${transaction.tickerSymbol} at ${transaction.sharePrice}"
    
    <strong>//If no transactions exist for a particular stock, check to see that the
    //transaction type is a 'Buy' and if so create a new list to hold 
    //transactions for a particular stock.</strong>
    if(portfolio[transaction.tickerSymbol] == null){
        if(transactionType == 'Buy')
            portfolio[transaction.tickerSymbol] = [transaction]
        else
            println "You can't sell a stock you don't own."
    } else{
        portfolio[transaction.tickerSymbol] &lt;&lt; transaction
    }     
}

def show_transactions(tickerSymbol){
    portfolio[tickerSymbol].each { transaction -&gt;
        println "${transaction.transactionDate}: ${transaction.type} " +
          "${transaction.numberOfShares} shares of ${tickerSymbol} at " +
          "${transaction.sharePrice}"
    }    
}

def <strong>getPrint_portfolio_value()</strong>{
    def totalValue = 0
        
    <strong>//Add all of the 'Buy' transactions and subtract all of the 'Sell' 
    //transactions from the total portfolio value.</strong>
    portfolio.each { tickerSymbol, transactionList -&gt;        
        transactionList.each { transaction -&gt;
            if(transaction.type == 'Buy')
                totalValue += 
                    (transaction.numberOfShares * transaction.sharePrice)
            else
                totalValue -= 
                    (transaction.numberOfShares * transaction.sharePrice)                            
        }
    }
    
    println "Your Total Portfolio Value is: ${totalValue}"
}</code></pre>    
</div>
<p>The only thing the code really does is define methods for the different types of stock trading activities.  I use a <code>HashMap</code> called <code><strong>portfolio</strong></code> to hold each of the individual stock transaction's attributes stored in a simple <code>StockTransaction</code> object.  Each time a buy or sell action takes place the <code>portfolio HashMap</code> is updated with the corresponding <code>StockTransaction</code> object.</p>
<p>The readability of the DSL code is greatly improved because Groovy allows for optional parenthesis on methods that take one or more parameters.  Notice that the second call to purchase Apple stock uses the parenthesis to illustrate this point.  It is important to keep things as simple as possible when creating a DSL.  Programmers should try to avoid bogging the domain expert down by forcing him or her to use unnecessary constructs of a language such as parenthesis.</p>
<p>If you look closely at the code that defines the DSL you will notice that in order to make the parenthesis optional for calls to the <code><strong>print_portfolio_value</strong></code> method I had to get a little hacky and define the method as: <code><strong>getPrint_portfolio_value()</strong></code>.  This is because Groovy thinks that <code>print_portfolio_value</code> is a call to a property.  By adding the "get" in front of the method call, we can "trick" Groovy into calling the method as desired.</p>
<p>After executing the DSL code the output is as follows:</p>
<div class="outputBlock">
<pre>Buying 500 shares of AAPL at 179.30
Buying 250 shares of AAPL at 179.30
Buying 500 shares of SUNW at 10.14
Selling 350 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Buy 500 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Buy 250 shares of AAPL at 179.30
Sun Aug 17 19:15:05 EDT 2008: Sell 350 shares of AAPL at 179.30
Your Total Portfolio Value is: 76790.00</pre>
</div>
<h3>Fluency</h3>
<p>In the context of trading stocks, the DSL we created above is pretty straightforward, but it does suffer a bit from a problem with fluency.  It might be nice if we could make the DSL a bit more readable.  For example, what if the DSL was changed to read like this:</p>
<div class="codeBlock">
	<pre><code>buy 500.shares.of("AAPL").at(179.30)
buy 250.shares.of("AAPL").at(179.30)
buy 500.shares.of("SUNW").at(10.14)
sell 350.shares.of("AAPL").at(179.30)

show_transactions "AAPL"

print_portfolio_value</code></pre>	
</div>
<p>Using <a href="http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/#categories">categories</a> it is possible to allow for a fluent DSL like the one above.  Take a look at the code behind this DSL:</p>
<div class="codeBlock">
	<pre><code>/**
 * The class used for the category
 */
class <strong>StockHelper</strong> {
    static portfolio = [:]
    
    static buy(<strong>self</strong>, stockTransaction) { 
        stockTransaction.type = 'Buy'    
        transaction(stockTransaction)
    }
    
    static sell(<strong>self</strong>, stockTransaction) { 
        stockTransaction.type = 'Sell'    
        transaction(stockTransaction)    
    }
    
    static transaction(stockTransaction){
        println "${stockTransaction.type}ing " +
        "${stockTransaction.numberOfShares}" +
        " shares of ${stockTransaction.tickerSymbol} at " +
        "${stockTransaction.sharePrice}"
        
        if(portfolio[stockTransaction.tickerSymbol] == null){
            if(stockTransaction.type == 'Buy')
                portfolio[stockTransaction.tickerSymbol] = [stockTransaction]
            else
                println "You can't sell a stock you don't own."
        } else{
            portfolio[stockTransaction.tickerSymbol] &lt;&lt; stockTransaction
        }                 
    }    
    
    static getShares(<strong>self</strong>) { 
        def startTransaction = new StockTransaction(numberOfShares:<strong>self</strong>, 
            transactionDate:new Date())
        return startTransaction
    }
    
    static of(<strong>self</strong>, tickerSymbol) { 
        <strong>self</strong>.tickerSymbol = tickerSymbol         
        return <strong>self</strong>
    }    
    static at(<strong>self</strong>, sharePrice) { 
        <strong>self</strong>.sharePrice = sharePrice 
        return <strong>self</strong>
    }    
    
    static show_transactions(<strong>self</strong>, tickerSymbol){
        portfolio[tickerSymbol].each { transaction ->
            println "${transaction.transactionDate}: ${transaction.type} " +
              "${transaction.numberOfShares} shares of ${tickerSymbol} at " +
              "${transaction.sharePrice}"
        }    
    }
    
    static getPrint_portfolio_value(<strong>self</strong>){
        def totalValue = 0
            
        portfolio.each { tickerSymbol, transactionList ->
            
            transactionList.each { transaction -&gt;
                if(transaction.type == 'Buy')
                    totalValue += 
                        (transaction.numberOfShares * transaction.sharePrice)
                else
                    totalValue -= 
                        (transaction.numberOfShares * transaction.sharePrice)                            
            }
        }
        
        println "Your Total Portfolio Value is: ${totalValue}"
    }    
}</code></pre>	
</div>
<p>By chaining methods calls together we can make our code very fluent.  We build a <code>StockTransaction</code> object by calling 3 methods: <code><strong>getShares()</strong></code>, <code><strong>of()</strong></code>, and <code><strong>at()</strong></code>.  Each of these calls is responsible for building a specific piece of the <code>StockTransaction</code> object and passing it along to the next call.  The <code><strong>self</strong></code> keyword is used to reference the target instance (i.e. the <code>StockTransaction</code> object being created).  After the <code>StockTransaction</code> is created, the <code>buy</code> or <code>sell</code> methods can be called to update the <code>portfolio HashMap</code> just as in the first example.</p>
<p>Even though parenthesis and the dot notation (for method access) must be used in order to execute this DSL code, I personally think this code is easier to read and understand as compared with the previous example.</p>
<h3>Conclusion</h3>
<p>The code in this blog entry is pretty brittle, but it illustrates how easily a DSL can be created using the Groovy programming language.  In a real life scenario programmers must be diligent about the design and usage of the DSLs they create.</p>
<p>By creating an internal DSL domain experts with some programming knowledge will also be able to exploit other constructs found in the implementing language such as loops and conditional statements.  For example, code could be written to do things such as:</p>
<div class="codeBlock">
	<pre><code>if(currentStockPriceVariable &lt; SOME_SHARE_PRICE_CONSTANT){
    buy 500.shares.of("AAPL").at(currentStockPriceVariable)
}</code></pre>
</div>
<p>or perhaps something like this:</p>
<div class="codeBlock">
	<pre><code>3.times {
    sell 500.shares.of("AAPL").at(179.30)
}</code></pre>	
</div>
<p>Over the past few years DSLs have gained popularity along with the rise of dynamic languages.  For example, <code><a href="http://gant.codehaus.org/">GANT</a></code> is a popular DSL for the Groovy programming language that can be used to script <code><a href="http://ant.apache.org/">Ant</a></code> style builds.  It will be interesting to see what other types of DSLs become available in the future.  Be sure to look out for Martin Fowler's upcoming <a href="http://martinfowler.com/dslwip/">book</a> on the subject.</p>
<h3>Code</h3>
<p><a href="http://www.fiascode.com/downloads/groovydsl.zip">Click here</a> to download the code examples from this post.</p>
<h3>Disclaimer</h3>
<p>I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/groovy-domain-specific-language-tutorial/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby Nation: Day 2 Wrap Up</title>
		<link>http://www.fiascode.com/general/ruby-nation-day-2-wrap-up/</link>
		<comments>http://www.fiascode.com/general/ruby-nation-day-2-wrap-up/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 22:49:25 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[General]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=18</guid>
		<description><![CDATA[
Opening Keynote - Rich Kilmer
Rich Kilmer's opening keynote was by far the best presentation of the day.  Rich is an incredibly experienced and skilled Ruby developer who was one of the earlier adopters of the language.  During his keynote, Rich walked through his experiences with Ruby dating all the way back to 2001. [...]]]></description>
			<content:encoded><![CDATA[<p></p>
<h3>Opening Keynote - Rich Kilmer</h3>
<p>Rich Kilmer's opening keynote was by far the best presentation of the day.  Rich is an incredibly experienced and skilled Ruby developer who was one of the earlier adopters of the language.  During his keynote, Rich walked through his experiences with Ruby dating all the way back to 2001.  He has certainly worked on some interesting projects for impressive government agencies including DARPA and the United State Air Force.  Rich also talked about projects he has created for the Ruby community including <a href="http://freeride.rubyforge.org/wiki/wiki.pl">FreeRIDE</a> - a Ruby IDE and <a href="http://rubyforge.org/">RubyForge</a> - a code repository for Ruby projects.</p>
<p>One particularly interesting thing Rich mentioned was that Ruby is becoming a mainstream language.  I personally find this both exciting and scary.  It is exciting that the community is growing at that there will likely be more opportunities to work on Ruby projects professionally, but it is a bit worrisome that the community could start to be overpopulated with run-of-the-mill developers transitioning from other dying mainstream languages.</p>
<span id="more-18"></span>
<h3>Ruby Puzzlers - Mike Furr</h3>
<p>Mike Furr, a doctoral student at <a href="http://www.umd.edu/">UMCP</a>, gave a presentation on edge case scenarios that occur in the Ruby language.  Since I'm pretty new to Ruby I struggled to follow along, but Mike did do a good job of explaining how Ruby code reacted under various situations.  Even though it can be rare to deal with edge cases in a language, it is nice to know how to avoid them or work your way out of them if they do arise.</p>
<h3>Practical JRuby - David Keener</h3>
<p>A Java(ish) presentation at a Ruby conference?  It may seem a bit strange at first, but it actually makes a lot of sense.  Java as a platform has some pretty rock solid features including performance, garbage collection, and concurrency.  A lot time and thought has also been invested into Java libraries and corporate infrastructure so in many ways it makes sense to take advantage of what is already available.  David Keener hit on all of these points in his presentation and gave an example of how to integrate <a href="http://jruby.codehaus.org/">JRuby</a> with the <a href="http://www.jfree.org/jfreechart/">JFreeChart</a> Java library.</p>
<h3>Tools for Your Ruby Toolbox - Dave Bock</h3>
<p>Dave Bock is another <a href="http://www.fgm.com">FGM</a> employee that I had the pleasure of working with a few years back.  Dave has since moved on and started his own shop called <a href="http://www.codesherpas.com/">Codesherpas</a>.  In his presentation, Dave talked about 3 lightweight tools that can be used to quickly accomplish tasks in Ruby.  Dave first talked about <a href="http://www.rubyinside.com/staticmatic-ruby-powered-static-web-site-system-603.html">StaticMatic</a>, a framework for developing simple static websites using templates, but without using all of the built in functionality of Rails.  Another web framework Dave talked about was <a href="http://sinatrarb.com/Home">Sinatra</a>.  Again, this framework allows developers to create simple web applications without the full Rails stack, but it also includes some RESTful functionality.  Finally, Dave talked about <a href="http://www.ruby-doc.org/stdlib/libdoc/gserver/rdoc/classes/GServer.html">GServer</a>, a generic server library that allows developers to easily create server applications of their own.  During his presentation Dave demoed a quick "Knock Knock" client he created using the GServer library.</p>
<h3>Lightning Talks</h3>
<p>There were five lightening talks given yesterday, but again <a href="http://smartic.us/">Bryan Liles</a> stole the show with his presentation on Project Management.  The basic takeaway: meet with your reports regularly, project confidence, and set up processes that are easy to follow.  Sounds so simple doesn't it?</p>
<h3>Closing Keynote: Bad Ruby - Stuart Halloway</h3>
<p>Stuart Holloway closed RubyNation with a talk on Bad Ruby.  Playing off of a point made earlier in Rich Kilmer's talk about Ruby becoming mainstream, Stuart noted that now was the time for Ruby developers to begin to establish best practices for the language so that common pitfalls can be avoided when mainstream developers start to migrate to Ruby.  (Assuming of course "mainstream" developers actually migrate to Ruby).</p>
<h3>Conference Wrap Up</h3>
<p>Overall the conference was pretty great.  Day two was a little less energetic than day one, but that may not be too surprising seeing as how it was on a Saturday.  I was a little disappointed that Bruce Tate wasn't able to make the conference because I was really looking forward to hearing him speak, but I was pleasantly surprised at the quality of the other speakers.  I know that a lot of people put a lot of hard work into the conference so I'd personally like to thank everyone responsible for putting on this years conference and I can't wait to attend again next year.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/general/ruby-nation-day-2-wrap-up/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby Nation: Day 1 Wrap Up</title>
		<link>http://www.fiascode.com/general/ruby-nation-day-1-wrap-up/</link>
		<comments>http://www.fiascode.com/general/ruby-nation-day-1-wrap-up/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 15:59:26 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[General]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=17</guid>
		<description><![CDATA[Ruby experts and enthusiasts from around the country met in Washington, D.C. today for the first annual RubyNation conference.  I always think it's awesome to get together with industry leaders to absorb and share new information and insights.  I've been to quite a few tech conferences in the past, but I've never been [...]]]></description>
			<content:encoded><![CDATA[<p>Ruby experts and enthusiasts from around the country met in Washington, D.C. today for the first annual <a href="http://www.rubynation.org">RubyNation</a> conference.  I always think it's awesome to get together with industry leaders to absorb and share new information and insights.  I've been to quite a few tech conferences in the past, but I've never been as engaged and attentive as I was today.  There is an energy around Ruby and Rails that I have yet to witness with other technologies.  I continue to be amazed by how passionate and open the community is as well.  I met and talked with more people today than all of the other conferences I've attended combined.</p>
<p>In case you weren't able to make it, here's a quick rundown of today's events:</p>
<span id="more-17"></span>  
<h3>Opening Keynote: Ceremony vs. Essence - Neal Ford</h3>
<p><a href="http://memeagora.blogspot.com/">Neal Ford</a> is a seasoned consultant and speaker that I've seen present on more than one occasion.  I've always enjoyed his presentations, but his talk today really hit home with me.  Neal's talk basically boiled down to the fact that we developers need to <a href="http://en.wikipedia.org/wiki/KISS_principle">Keep It Simple (KISS)</a> and avoid the "accidental complexity" that is often unnecessarily added to the problems we are trying to solve.  I've listen rhetoric like this a 1,000 times, but I've never heard it articulated so elegantly.  It was literally like he was looking inside of my head and expressing the way I (and likely a lot of developers) feel about the current state of the industry (especially if you are a Java programmer like me).</p>
<h3>DSLs and Ruby: Blurring the Lines Between Programs And Data - Russ Olsen</h3>
<p>I used to work with Russ at a <a href="http://www.fgm.com">FGM</a> so I was really looking forward to hearing him speak.  Russ has become quite a leader in the Ruby community especially after publishing his first book: <a href="http://www.amazon.com/Design-Patterns-Ruby-Russ-Olsen/dp/0321490452">Design Patterns in Ruby</a>.  Russ's talk centered around Domain Specific Languages (DSLs) and how relatively easy it is to implement one using the Ruby language.  During his presentation Russ put together a simple Internal DSL for example purposes and also discussed use cases for when it is appropriate to create a DSL to solve a problem.</p>
<h3>The Culture of Innovation in Ruby - Glenn Vanderburg</h3>
<p>Innovation in testing frameworks in Ruby was the topic of Glenn Vanderburg's talk.  Glenn discussed some of the interesting testings frameworks available in the Ruby community (<a href="http://rspec.info/">Rspec</a>, <a href="http://mocha.rubyforge.org/">Mocha</a>, <a href="http://onestepback.org/software/flexmock/">Flex Mock</a>, <a href="http://thoughtbot.com/projects/shoulda">Shoulda</a>) and compared them to some of the stagnant frameworks in the Java community (<a href="http://www.junit.org/">JUnit</a>, <a href="http://testng.org/doc/">TestNG</a>).  Glenn also pointed out how Ruby's testing frameworks tend to make it much easier to mock objects and create more thorough tests with much less effort than the equivalent tests in the Java world.</p>
<h3>Living on the Edge - Yehuda Katz</h3>
<p>Yehuda Katz of <a href="http://engineyard.com/">EngineYard</a> talked about some of the new(er) technologies that are emerging in the Ruby community including <a href="http://merbivore.com/">Merb</a>, <a href="http://datamapper.org/">DataMapper</a>, Sake, Thor, YARDoc, and <a href="http://github.com/">GitHub</a>.  DataMapper looks like an especially interesting alternative to the incumbent ORM ActiveRecord.  It promises thread safety and increased performance which are obviously two great things.  GitHub looks pretty cool too.  I'm not quite ready to abandon <a href="http://subversion.tigris.org/">Subversion</a> just yet, but I will definitely be checking out <a href="http://git.or.cz/">Git</a> in the near future.</p>
<h3>Lightning Talks</h3>
<p>Chris Bucchere, David Jones, Simon Kaczor, and Bryan Liles all gave lightening talks today on a variety of topics including social networking, state machines, command line libraries, and testing respectively.  All of the talks presented useful information, but Bryan Liles was without a doubt the most entertaining speaker of the day.  He made it through about 65 slides in 15 minutes and was still able to convey a very important message about how often developers should be testing their code.  Check out his blog at: <a href="http://smartic.us/">http://smartic.us/</a></p>
<h3>Archaeopteryx: A Ruby MIDI Generator - Giles Bowkett</h3>
<p>I actually wasn't able to attend Giles Bowkett's session because I had a previous engagement to attend, but I did get a chance to view some <a href="http://gilesbowkett.blogspot.com/2008/02/archaeopteryx-ruby-midi-generator.html">screencasts</a> that show off his Ruby MIDI Generator.  Pretty cool stuff.</p>
<h3>Tomorrow</h3>
<p>Tomorrow looks to be a pretty exciting day as well.  I'm especially looking forward to talks from my former co-worker Dave Bock and author Stuart Holloway.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/general/ruby-nation-day-1-wrap-up/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Putting Google Finance to REST with Ruby</title>
		<link>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-ruby/</link>
		<comments>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-ruby/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 06:43:10 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[REST]]></category>

		<category><![CDATA[Ruby]]></category>

		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=16</guid>
		<description><![CDATA[RubyNation is just a week and a half away and in order to prepare myself I thought I'd brush up on some Ruby and Rails in the days preceding the conference.  I don't use Ruby on a regular basis, but I'm a huge fan of dynamic languages so I'm really looking forward to attending [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.rubynation.org/">RubyNation</a> is just a week and a half away and in order to prepare myself I thought I'd brush up on some <a href="http://www.ruby-lang.org/">Ruby</a> and <a href="http://www.rubyonrails.org/">Rails</a> in the days preceding the conference.  I don't use Ruby on a regular basis, but I'm a huge fan of dynamic languages so I'm really looking forward to attending the conference and finding out what's new in the Ruby community.</p>
<p>By day I'm a Java developer, but I've also spent a fair amount of time studying Groovy.  Learning Groovy has been my "training wheels" approach to understanding dynamic languages.  Studying Groovy has helped me grasp new (new to me at least) concepts like <a href="http://www.fiascode.com/?s=metaprogramming">Metaprogramming</a> and Domain Specific Languages all from the comfort of my Java environment.</p>
<span id="more-16"></span>
<p>As a simple exercise I thought it would be interesting to rewrite the code from my <a href="http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/">last blog entry</a> in Ruby to see how it compares to the Groovy code I originally wrote.  So without further ado let's check out the code:</p>
<h3>Authenticating with Google</h3>
<p>In order to use the Google Finance API we need to first authenticate with Google by sending our <a href="https://www.google.com/accounts/NewAccount">Google Account</a> username and password to Google's client login URL: <strong>https://www.google.com/accounts/ClientLogin</strong>.</p>
<div class="codeBlock">
	<pre><code>def create_auth_token(username, password)
  https = Net::HTTP.new('www.google.com', <strong>443</strong>)
  <strong>https.use_ssl = true</strong>
  path = '/accounts/ClientLogin'

  query_string = "Email=#{username}&amp;Passwd=#{password}
                 &amp;service=finance&amp;source=company-groovyfinance-1.0"
                 
  https.verify_mode = OpenSSL::SSL::VERIFY_NONE # don't display warnings
  
  response = https.<strong>post(</strong>path, query_string<strong>)</strong>

  if response.code == '200'
    return response.body[/Auth=(.*)/, 1] # The authorization token
  end
  
  return "Error"
end</code></pre>	
</div>
<p>In the code above we create an <code>http</code> object and give it the correct URI and path to Google's login service.  We then send in a query string with our username, password, service, and source (application name).  If everything succeeds Google returns an Authentication token which we will set in the headers in subsequent calls to Google's service.</p>
<p>This code isn't much different from the Groovy code in my previous entry, but I do like the way Ruby allows <code>POST</code> calls directly on the <code><strong>http</strong></code> object.  This obsoletes the <code>processRequest()</code> method found in my Groovy code.</p>
<h3>Creating a Portfolio</h3>
<p>We can create a new portfolio in our Google Finance account by executing calls to the following method:</p>
<div class="codeBlock">
	<pre><code>def create_portfolio(authorization_token, portfolio_name)	                         	
  headers={}
  headers["Authorization"] = "GoogleLogin auth=#{authorization_token}"
  headers["Content-Type"] = "application/atom+xml"

  http = Net::HTTP.new('finance.google.com')
  path = "/finance/feeds/default/portfolios"

  atom_string = "&lt;?xml version='1.0'?&gt;
  &lt;entry xmlns='http://www.w3.org/2005/Atom'
         xmlns:gf='http://schemas.google.com/finance/2007'
         xmlns:gd='http://schemas.google.com/g/2005'&gt;
         &lt;title type='text'&gt;<strong>#{portfolio_name}</strong>&lt;/title&gt;
         &lt;gf:portfolioData currencyCode='USD'/&gt;
  &lt;/entry&gt;"

  response = <strong>http.post(</strong>path, atom_string, headers<strong>)</strong>
  
  if response.code == '201'
    doc = REXML::Document.new(response.body)
    return doc.root.elements["id"].text[/portfolios\/(.*)/, 1] #portfolio id
  end
  
  return "Error"
end</code></pre>	
</div>
<p>This code is almost identical to the Groovy code I wrote <a href="http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/">last time</a> but I do really like the way Ruby allows you to place header attributes into a <code>Hash</code> and send them directly with a call to <code><strong>http.post()</strong></code>.</p>
<h3>Placing an Order</h3>
<p>Just like the example above, placing an order (stock trade) means that we need to create an <code><a href="http://en.wikipedia.org/wiki/Atom_(standard)">Atom</a></code> feed with our transaction attributes (transaction type, number of shares, etc.) and send them to a Google resource end point.  This end point in our case is the URL of the specific portfolio in which we wish to place our new asset.</p>
<div class="codeBlock">
	<pre><code>def create_stock_transaction(authorization_token, ticker_symbol, 
                             number_of_shares, transaction_type, portfolio_id)
	                         	
  headers={}
  headers["Authorization"] = "GoogleLogin auth=#{authorization_token}"
  headers["Content-Type"] = "application/atom+xml"

  http = Net::HTTP.new('finance.google.com')
  path = "/finance/feeds/default/portfolios/<strong>#{portfolio_id}</strong>/positions/" +
         "<strong>#{CGI::escape(ticker_symbol)}</strong>/transactions"

  transaction_time = Time.now.strftime("%Y-%m-%dT%H:%M:%S.000")

  atom_string = "&lt;?xml version='1.0'?&gt;
  &lt;entry xmlns='http://www.w3.org/2005/Atom' 
         xmlns:gf='http://schemas.google.com/finance/2007' 
         xmlns:gd='http://schemas.google.com/g/2005'&gt;
         &lt;gf:transactionData date='<strong>#{transaction_time}</strong>' 
             shares='<strong>#{number_of_shares}</strong>' type='<strong>#{transaction_type}</strong>' /&gt;
  &lt;/entry&gt;"

  response = <strong>http.post(</strong>path, atom_string, headers<strong>)</strong>
  
  if response.code == '201'
    return response.body
  end
  
  return "Error"
end</code></pre>	
</div>
<p>Once again the Ruby code looks nearly identical to the Groovy code.  We set the correct headers, generate a well formed Atom feed, and the post our data to Google.  If all goes well, the transaction will be made and an <code>Atom</code> representation of the transaction will be returned to the client.</p>
<h3>Groovy vs. Ruby Thoughts</h3>
<p>There are probably "Rubyer" ways to write the code samples listed above, but I did find it interesting that the code I wrote in Ruby was so similar to the code that I wrote in Groovy.  I'm not sure whether or not the similarities are due to the subjective nature of having the same programmer write both samples or if it's due to the fact that the languages are so similar to begin with.</p>
<p>Either way, exploring a new language (albeit a similar language) did give me some additional perspective.  I found myself bouncing back and forth between the Groovy and Ruby code comparing how similar tasks were performed in each language.  This type of information is always useful when trying to determine which technology is the right tool to use for a specific job.</p>
<p>In addition, studying Ruby <a href="http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/#comments">helped me write better Groovy code</a>.  In the create_auth_token() method in the Ruby sample a <a href="http://en.wikipedia.org/wiki/Regular_expression">regular expression</a> is used to parse the authentication token from the returned string.  I was able to take this regular expression code and apply it to the same method (createAuthToken()) in my Groovy code to improve its readability.</p>
<h3>References</h3>
<br/><a href="http://www.fiascode.com/downloads/rubyfinance.zip">Download the Code</a><br/><br/>
<a href="http://code.google.com/apis/gdata/index.html">Google Data API Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/developers_guide_protocol.html">Google Finance Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/reference.html">Google Finance Reference</a><br/><br/>
<a href="http://code.google.com/support/bin/answer.py?answer=93164&amp;topic=12027">Using Ruby with the Google Data APIs</a><br/>
<a href="http://www.germane-software.com/software/rexml/docs/tutorial.html">REXML Guide</a><br/>
<h3>Disclaimer</h3>
<p>Again... I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-ruby/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Putting Google Finance to REST with Groovy</title>
		<link>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/</link>
		<comments>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 03:07:13 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Groovy]]></category>

		<category><![CDATA[REST]]></category>

		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=15</guid>
		<description><![CDATA[For a while now I've been interested in learning more about building and consuming REST based web services.  Fortunately, many tech giants including Google and Yahoo expose much of their data and functionality through REST based APIs.  These powerful APIs, combined with Groovy's concise, readable syntax make it very easy to learn about [...]]]></description>
			<content:encoded><![CDATA[<p>For a while now I've been interested in learning more about building and consuming <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a> based web services.  Fortunately, many tech giants including <a href="http://code.google.com/">Google</a> and <a href="http://developer.yahoo.com/">Yahoo</a> expose much of their data and functionality through REST based APIs.  These powerful APIs, combined with Groovy's concise, readable syntax make it very easy to learn about the REST software architecture approach.</p>
<p>This particular blog entry makes use of <a href="http://code.google.com/apis/finance/">Google's Finance Data API</a>.  I'll explain how it is possible to programmatically authenticate with Google, create a new stock portfolio, and create positions (buy and sell stocks) within this portfolio by making REST based service calls.  I won't dive too deep into the details of the REST architecture, but if you have a general understanding of XML and the HTTP protocol it won't be too difficult to follow along.  For more information on REST, please see the links in the <a href="#reference">Reference</a> section below.</p>
<span id="more-15"></span>
<div class="codeBlock">
<i><strong>Note:</strong> If you want to try the code samples on your own you will need to have a Google Account.  To sign up for a free account <a href="https://www.google.com/accounts/NewAccount">click here</a>.</i>
</div>
<h3 id="googauth">Authenticating with Google</h3>
<p>In order to use Google's service we must first authenticate by <code><strong>POST</strong></code>ing a query string containing our username, password, service identifier, and source (application name) to the following URL: <code><strong>https://www.google.com/accounts/ClientLogin</strong></code>.  This code snippet illustrates how a <code><strong>POST</strong></code> request can be made in Groovy:</p>
<div class="codeBlock">
	<pre><code>static <strong>createAuthToken(</strong>String username, String password<strong>)</strong>{
    def url = new URL(<strong>"https://www.google.com/accounts/ClientLogin"</strong>)
    def connection = url.openConnection()		
		
    def queryString = "<strong>Email</strong>=${username}&amp;<strong>Passwd</strong>=${password}" +
                      "&amp;<strong>service</strong>=finance&amp;<strong>source</strong>=company-groovyfinance-1.0"
		
    def returnMessage = <strong>processRequest(</strong>connection, queryString<strong>)</strong>
		
    if(returnMessage != "Error"){
        //the authtentication token
        return returnMessage.split(/Auth=/)[1].trim()
    }
}

static String <strong>processRequest(</strong>connection, dataString<strong>)</strong>{
    connection.<strong>setRequestMethod("POST")</strong>
    connection.doOutput = true
    Writer writer = new OutputStreamWriter(connection.outputStream)
    writer.write(dataString)
    writer.flush()
    writer.close()		
    connection.connect()
		
    if (connection.responseCode == 200 || connection.responseCode == 201)
        return connection.content.text									
			
    return "Error"
}</code></pre>	
</div>
<p>In the code above we create a <code>connection</code> to Google's authentication URL and <code>POST</code> the <code>queryString</code> by calling the reusable <code><strong>processRequest()</strong></code> method.  Within <code>processRequest()</code> we set the <code>connection's</code> request method type to "<code>POST</code>", create a <code>Writer</code>, and write the data to the supplied <code>connection</code>.</p>
<div class="codeBlock"><i><strong>Note:</strong> The code example for this blog post can be downloaded in its entirety by clicking the "Download the Code" link in the <a href="#reference">Reference</a> section below.</i></div>
<p>If our credentials are valid, Google will respond to our request with a string of name value pairs similar to this:</p>
<div class="codeBlock">
	<pre><code>SID=DQAAAIEAAAIgccs7qKgmwXGagt...lu6fg
LSID=DQAAAIIAAACsegj9oEm0Ob8pz...abyi5
Auth=<strong>DQAAAIMAAACgadj9oEm0Ob8pz...AGasG</strong></code></pre>	
</div>
<p>The only piece of information we are interested in is the authorization token value that follows the "<code><strong>Auth</strong></code>" label.  We will need to use this token in the rest of our requests in order to authenticate with Google.</p>
<h3 id="portfoliocreation">Creating a Portfolio</h3>
<p>When users log into <a href="http://www.google.com/finance">Google Finance</a> for the first time they will be presented by default with an empty portfolio called "My Portfolio".  <i><strong>Note</strong>: a portfolio is simply a collection of assets (stocks, bonds, mutual funds, cash, etc.).</i></p>
<a href="http://www.fiascode.com/images/empty_portfolio_large.jpg"><img alt="Empty Portfolio" class="centered" src="http://www.fiascode.com/images/empty_portfolio_small.jpg" /></a>
<p>Let's pretend however that we do not wish to use the default portfolio, but instead want to create our own. To create a new portfolio we simply need to send a well formed <a href="http://en.wikipedia.org/wiki/Atom_(standard)"><code>Atom</code></a> XML feed that contains the name of the new portfolio (and optionally a currency code) to this URL: <code><strong>http://finance.google.com/finance/feeds/default/portfolios</strong></code></p>
<div class="codeBlock">
<pre><code>static <strong>createPortfolio(</strong>String authorizationToken, String portfolioName<strong>)</strong>{
    def url = 
    	 new URL("<strong>http://finance.google.com/finance/feeds/default/portfolios</strong>")

    def connection = url.openConnection()		
    connection.setRequestProperty("<strong>Content-Type</strong>", <strong>"application/atom+xml"</strong>)
    connection.setRequestProperty("<strong>Authorization</strong>", 
                                  <strong>"GoogleLogin auth=${authorizationToken}"</strong>)
		
    def atomString = <strong>"""</strong>&lt;?xml version='1.0'?&gt;
    &lt;entry xmlns='http://www.w3.org/2005/Atom'
    	   xmlns:gf='http://schemas.google.com/finance/2007'
           xmlns:gd='http://schemas.google.com/g/2005'&gt;
        &lt;title type='text'&gt;<strong>${portfolioName}</strong>&lt;/title&gt;
        &lt;gf:portfolioData currencyCode='USD'/&gt;
    &lt;/entry&gt;<strong>"""</strong>
    
    def returnMessage = <strong>processRequest(</strong>connection, atomString<strong>)</strong>
    
    //Get the id of the newly created portfolio
    if(returnMessage != "Error"){
    	def entry = new <strong>XmlSlurper()</strong>.parseText(returnMessage)
    	def entryId = "${entry.id}"    	
    	
    	return entryId[entryId.lastIndexOf('/')+1..-1]
    }    	
}</code></pre>
</div>
<p>Once again we create a <code>connection</code>, but this time we also need to set two request header parameters: <code><strong>Content-Type</strong></code> and <code><strong>Authorization</strong ></code>.  We set these parameters to "<code><strong>application/atom+xml</strong></code>" and "<code><strong>GoogleLogin auth=${authorizationToken}</strong></code>" respectively.  Note that the <code>authorizationToken</code> variable stores the authentication token that was returned by the <code>createAuthToken()</code> method.</p>
<p>After the connection is created we again call the <code>processRequest()</code> method that was discussed in the <a href="#googauth">Authenticating with Google</a> section above.  If all goes well, Google will create the new portfolio and return an <code>Atom</code> representation of that new portfolio to the client.  If we are logged into our web based Google Finance account we can refresh the screen and will notice our newly created portfolio.</p>
<a href="http://www.fiascode.com/images/groovy_portfolio_large.jpg"><img  alt="Groovy Portfolio Added" class="centered" src="http://www.fiascode.com/images/groovy_portfolio_small.jpg" /></a>
<p>Two code features really shine through in the example above:  Groovy's Triple Quotes and Groovy's <code><strong><a href="http://groovy.codehaus.org/Reading+XML+using+Groovy's+XmlSlurper">XmlSlurper</a></strong></code>.  The triple quotes surrounding the <code>Atom</code> XML allow us to easily write multi-line XML strings without having to worry about escaping special characters.  The <code>XmlSluper</code> meanwhile allows us to easily parse and locate a specific attribute (the portfolio id in this case) within the returned XML string.  Imagine how many lines of Java code it would take to recreate this functionality.</p>
<h3>Placing an Order</h3>
<p>So far our portfolio is pretty boring.  Let's create some stock transactions to add some assets into our portfolio.</p>
<div class="codeBlock">
<pre><code>static <strong>createStockTransaction(</strong>authorizationToken, tickerSymbol, numberOfShares,
                              transactionType, portfolioId<strong>)</strong>{    
                              	
    StringBuffer transactionURL = new StringBuffer()              
    transactionURL.append("<strong>http://finance.google.com/finance/feeds/</strong>")
        .append("<strong>default/portfolios/${portfolioId}/positions/</strong>")
        .append("<strong>${URLEncoder.encode(tickerSymbol)}/transactions</strong>")
                                         	
    def url = new URL(transactionURL.toString())
    def connection = url.openConnection()

    connection.setRequestProperty("Content-Type", "application/atom+xml")
    connection.setRequestProperty("Authorization", 
                                  "GoogleLogin auth=${authorizationToken}")
    
    String timeFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
    SimpleDateFormat dateFormatter = new SimpleDateFormat(timeFormat)    
    String transactionDate = dateFormatter.format(new Date())
    
    def atomString = """&lt;?xml version='1.0'?&gt;
    &lt;entry xmlns='http://www.w3.org/2005/Atom'
    	xmlns:gf='http://schemas.google.com/finance/2007'
    	xmlns:gd='http://schemas.google.com/g/2005'&gt;	
    	  &lt;gf:transactionData date='<strong>${transactionDate}</strong>' 
    	      shares=<strong>'${numberOfShares}</strong>' type='<strong>${transactionType}</strong>' /&gt;  	
    &lt;/entry&gt;"""
    
    processRequest(connection, atomString)    
}</code></pre>
</div>
<p>The concept with this code is basically the same as the <a href="#portfoliocreation">portfolio creation</a> example above.  We create a connection with the correct <code>Content-Type</code> and <code>Authorization</code> headers, define some <code>Atom</code> XML with attributes about the transaction we would like to make, and then <code>POST</code> the XML to a specific URL.  The interesting thing to note about this code is that unlike the other two examples, the URL for creating transactions is not static.  Instead, this URL needs to be parameterized with the portfolio id and ticker symbol of the stock you wish to trade: <code><strong> http://finance.google.com/finance/feeds/default/portfolios/&lt;portfolio id&gt;/
positions/&lt;ticker symbol&gt;/transactions</strong></code>.</p>
<p>Method calls to <code>createStockTransaction()</code> might look something like this:</p>
<div class="codeBlock">
<pre><code>createStockTransaction(authorizationToken, "NASDAQ:JAVA", 10000.00, "Buy", pId)
<strong>sleep(</strong>2000<strong>)</strong>	
createStockTransaction(authorizationToken, "NYSE:F", 10000.00, "Buy", pId)
</code></pre>
</div>
<p>This would place an order for 10,000 shares of Sun Microsystems and Ford Motor Company stock.  Notice that the ticker symbol must be preceded by the name of the market on which it trades.  Therefore the ticker symbol we sent to Google to purchase Sun stock is: <strong>NASDAQ:JAVA</strong> because Sun trades on the NASDAQ stock exchange.  Stocks that trade on the New York Stock Exchange would be preceded by the acronym: NYSE (i.e. Ford = NYSE:F). Also notice that it is a good idea to "<code><strong>sleep</strong></code>" between service calls because sending too many requests to Google at once will result in errors.</p>
<p>When we refresh our Google Finance page we will notice these shares placed into our portfolio.</p>
<a href="http://www.fiascode.com/images/groovy_portfolio_sun_large.jpg"><img alt="Stocks Purchased" class="centered" src="http://www.fiascode.com/images/groovy_portfolio_sun_small.jpg" /></a>
<h3>Conclusion</h3>
<p>This blog post only skims the surface of what is possible using Google's Finance Data API.  The API also allows for RESTful calls to GET, UPDATE and DELETE specific portfolio and transaction feeds.  Overall, I've been incredibly impressed by all of the data and functionality made available through Google's Data APIs.</p>
<p>The code provided in this example should give you a solid foundation to start playing around with Google's Finance API, but it is far from bulletproof.  For example, I don't really do much in the way of error handling or input validation.  So you shouldn't be surprised if things bomb out if you try to sell shares of a stock that you don't own or create a portfolio with the same name as one of your existing portfolios.</p>
<p>The examples I've shown here are very low level because I wanted to learn the basics of REST.  A much easier way to implement the same functionality would be to use <a href="http://code.google.com/apis/gdata/clientlibs.html">Google's Data APIs Client Libraries</a> (which by the way work perfectly well with Groovy).</p>
<h3 id="reference">References</h3>
<br/><a href="http://www.fiascode.com/downloads/groovyfinance.zip">Download the Code</a><br/><br/>
<a href="http://code.google.com/apis/gdata/index.html">Google Data API Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/developers_guide_protocol.html">Google Finance Developers Guide</a><br/>
<a href="http://code.google.com/apis/finance/reference.html">Google Finance Reference</a><br/><br/>
<a href="http://www.xfront.com/REST-Web-Services.html">Building Web Services the REST Way</a><br/>
<a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST Wikipedia Entry</a>
<h3>Disclaimer</h3>
<p>I am in no way endorsing any of the companies mentioned in this blog entry and all company references are for example purposes only.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/putting-google-finance-to-rest-with-groovy/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Groovy Metaprogramming – Creating Behavior on the Fly</title>
		<link>http://www.fiascode.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/</link>
		<comments>http://www.fiascode.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/#comments</comments>
		<pubDate>Tue, 08 Jul 2008 04:07:37 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=14</guid>
		<description><![CDATA[In my previous post I talked about dynamically adding behavior to Groovy classes using either the ExpandoMetaClass or Categories.  These techniques are especially useful if you know which methods you would like to add to your classes prior to actually writing any code.  But what if you don't know which methods you will [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/">previous post</a> I talked about dynamically adding behavior to Groovy classes using either the <code>ExpandoMetaClass</code> or Categories.  These techniques are especially useful if you know which methods you would like to add to your classes prior to actually writing any code.  But what if you don't know which methods you will need before code writing time?  What if you want to allow yourself the flexibility to call methods arbitrarily without defining their implementation beforehand?</p>
<p>To the average Java programmer (myself included), the idea of generating methods on the fly might seem bizarre at first, but Groovy's built in method interception capabilities allow programmers to easily realize this type of functionality in their Groovy code.  In <a href="http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/">Groovy Metaprogramming - Adding Behavior Dynamically</a>, I discussed how to add a method to the <code>java.math.BigDecimal</code> class to allow for the conversion of U.S. Dollars (USD) into Euros (EUR).  What if, however, I wanted to convert from USD to British Pounds (GBP) or to Japanese Yen (JPY)?  I could certainly write a method for each of these conversions, but what if there was a better, cleaner, and more flexible way to build in this functionality?</p>
<span id="more-14"></span>
<h2>Groovy's <code>methodMissing()</code></h2>
<p>The magic behind Groovy's ability to create methods on the fly comes from the language's built in facilities for intercepting method calls.  In particular, one practice for intercepting calls in Groovy is to implement the <code>methodMissing()</code> method on your Groovy classes.  Before Groovy throws a <code>MissingMethodException</code> for calls that are made to methods not defined within a class, Groovy first routes the calls through an object's <code>methodMissing()</code> method.  This gives programmers a chance to intercept calls to these non-existing methods and define an implementation for them:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

def <strong>exchangeRates</strong> = ['GBP':0.501882, 'EUR':0.630159, 
                     'CAD':1.0127, 'JPY':105.87] // (7/2/2008)
             
<strong>BigDecimal.metaClass.methodMissing</strong> = { String methodName, args ->
    conversionType = methodName[2..-1]
    conversionRate = exchangeRates[conversionType]
   
    if(conversionRate){
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
        nf.setCurrency(Currency.getInstance(conversionType))      
      
        return nf.format(delegate * conversionRate)
    }
   
    "No conversion for USD to ${conversionType}"
}

println 2500.00.<strong>inGBP()</strong>
println 2500.00.<strong>inJPY()</strong>
println 2500.00.<strong>inXYZ()</strong></code></pre>
</div>
<p>Notice that in the example above we make calls to the methods: <code><strong>inGBP()</strong></code>, <code><strong>inJPY()</strong></code>, and <code><strong>inXYZ()</strong></code> on the <code>BigDecimal</code> object 2500.00.  Also notice however, that we did not actually define any of these methods on the <code>BigDecimal</code> class.  Instead we override <code>BigDecimal's <strong>methodMissing()</strong></code> method which allows us to intercept calls to these methods (<code>inGBP()</code>, <code>inJPY()</code>, etc.) and create an implementation for them.</p>
<p>Within the <code>methodMissing()</code> method we parse the name of the called method and look up the corresponding conversion rate from the <code><strong>exchangeRate</strong> HashMap</code> which stores conversion rate values for various countries.  In the future it might be nice if this code called a remote service to actually lookup the exchange rates, but for these examples I'll just keep it simple.  If no corresponding conversion rate is found then a message is returned stating that there is "No conversion for USD to &lt;the conversion type specified&gt;" (XYZ in our case).</p>
<div class="outputBlock">
<pre>GBP1,254.70
JPY264,675.00
No conversion for USD to XYZ</pre>
</div>
<h2>Method Caching</h2>
<p>One way to improve the performance of the previous example is to cache the implementation of the method calls that we have intercepted.  This will allow future calls to these methods to be invoked directly and prevent them from having to be routed through the <code>BigDecimal</code> class's <code>methodMissing()</code> method:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

def exchangeRates = ['GBP':0.501882, 'EUR':0.630159, 
                     'CAD':1.0127, 'JPY':105.87] // (7/2/2008)

BigDecimal.metaClass.methodMissing = { String methodName, args ->
    println "method missing called"
    
    def <strong>cachedMethod</strong> = { Object[] cmArgs ->
        conversionType = methodName[2..-1]
        conversionRate = exchangeRates[conversionType]
        
        if(conversionRate){
            NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
            nf.setCurrency(Currency.getInstance(conversionType))        
            
            return nf.format(delegate * conversionRate)
        }
        
        "No conversion for USD to ${conversionType}"
    }
    
    <strong>BigDecimal.metaClass."${methodName}" = cachedMethod</strong>
    
    return cachedMethod(args)
}

println 2500.00.inJPY()
println 2500.00.inGBP()
println 2500.00.inGBP()</code></pre>
</div>		
<p>In the example above notice that the functionality for the called method is implemented and stored within a closure called <code><strong>cachedMethod</strong></code>.  By storing the functionality within a closure we can then assign it to <code>BigDecimal's metaClass</code> so that subsequent method calls are invoked directly.</p>
<p>In the result we can see that the second call to <code>inGBP()</code> does not get routed through <code>BigDecimal's methodMissing()</code>:</p>
<div class="outputBlock">
<pre>method missing called
JPY264,675.00
method missing called
GBP1,254.70
<strong>GBP1,254.70</strong></pre>
</div>
<h2>Conclusion</h2>
<p>It's not too hard to think of ways that the given code samples could be improved.  Imagine that instead of assuming all <code>BigDecimal</code> objects were defined in USD, that they could represent any currency type and that our future method calls could actually look something like this:</p>
<div class="codeBlock">
	<pre><code>2500.00.fromEURtoCAD()</code></pre>
</div>
<p>The examples given in this blog entry are trivial, but they showcase the power and flexibility that can be gained by using Groovy's metaprogramming capabilities.  These metaprogramming techniques give programmers a powerful tool that can be used within their code, but with this power programmers need to show a great deal of caution.  Imagine if the following method was called on the <code>BigDecimal</code> object in our examples above:</p>
<div class="codeBlock">
	<pre><code>2500.00.someRandomMethod()</code></pre>
</div>
<p>I'm guessing the result would not be desirable.  Programmers should always be sure to code defensively and write unit tests when using Groovy's powerful metaprogramming capabilities.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Groovy Metaprogramming - Adding Behavior Dynamically</title>
		<link>http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/</link>
		<comments>http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 02:00:09 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=13</guid>
		<description><![CDATA[I've been fascinated with languages like Ruby and Groovy ever since being exposed to their dynamic capabilities.  I remember attending a No Fluff Just Stuff conference a few years ago and being awestruck while watching Dave Thomas build a full-blown Rails application within a matter of minutes.  Dynamic languages give programmers the ability [...]]]></description>
			<content:encoded><![CDATA[<p>I've been fascinated with languages like Ruby and Groovy ever since being exposed to their dynamic capabilities.  I remember attending a <a href="http://www.nofluffjuststuff.com/home.jsp">No Fluff Just Stuff</a> conference a few years ago and being awestruck while watching <a href="http://pragdave.blogs.pragprog.com/">Dave Thomas</a> build a full-blown Rails application within a matter of minutes.  Dynamic languages give programmers the ability to write powerful and flexible code that is both readable and concise.  But what is it that gives these languages such great power?  The secret is their metaprogramming capabilities.</p>
<p><a href="http://en.wikipedia.org/wiki/Metaprogramming">Metaprogramming</a> is the ability of a computer language to manipulate other programs (including itself) to add or create functionality in a dynamic fashion.  In Groovy, metaprogramming is especially useful because among other things it gives programmers the ability to easily implement <a href="http://en.wikipedia.org/wiki/Domain_Specific_Language">domain specific languages</a>, create <a href="http://groovy.codehaus.org/Builders">builders</a>, or generate mock objects for <a href="http://groovy.codehaus.org/Unit+Testing">unit testing</a>.  Adding functionality to pre-existing Java or Groovy code can be accomplished by using either the <code>ExpandoMetaClass</code> or Categories.</p>
<span id="more-13"></span>
<p><i>Note: the best way to test the code examples from this blog entry yourself is to simply copy and paste them into a text file saved with a <code>.groovy</code> extension and then run them from the command line.  Running these examples in the <code>GroovyConsole</code> may yield unpredictable results.</i></p>
<h3>The <code>ExpandoMetaClass</code></h3>
<p>The <code>ExpandoMetaClass</code> can be used to dynamically add methods, properties, and constructors to Groovy or Java objects.  These tasks can be accomplished by simply assigning a closure to an object's <code>MetaClass</code>.  For instance, let's pretend that we want to add a method to <code>java.math.BigDecimal</code> that will convert a <code>BigDecimal</code> (in U.S. Dollars) to its equivalent value in Euros.</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

<strong>BigDecimal.metaClass.inEuros</strong> = {
    def EXCHANGE_RATE = 0.634961 // (6/27/2008)
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
    nf.setCurrency(Currency.getInstance("EUR"))
    nf.format(<strong>delegate</strong> * EXCHANGE_RATE)
}

println 2500.00.inEuros()</code>
	</pre>
</div>
<p>To access <code>BigDecimal's MetaClass</code> we simply use the following syntax <strong><code>BigDecimal.metaClass.inEuros</code></strong> and assign it a closure.  Within the closure we set an exchange rate, create a <code>NumberFormat</code> instance, set the currency type to "EUR" (Euros), and multiply the <strong><code>delegate</code></strong> (the <code>BigDecimal</code> we specified) by the exchange rate.  Groovy automatically returns the last line of a closure so our call to <strong><code>println 2500.00.inEuros()</code></strong> will yield the following result:</p>
<div class="outputBlock">
<pre>EUR1,587.40</pre>
</div>
<p>It is also possible to make the code a bit more readable by dropping the parenthesis after the call to <code>inEuros()</code>.  This can be accomplished by setting up <code>inEuros</code> as a property on the <code>BigDecimal</code> class instead of as a method:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

<strong>BigDecimal.metaClass.getInEuros</strong> = {->
    def EXCHANGE_RATE = 0.634961 //June 27, 2008
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
    nf.setCurrency(Currency.getInstance("EUR"))
    nf.format(delegate * EXCHANGE_RATE)
}

<strong>println 2500.00.inEuros</strong></code>
	</pre>
</div>	
<p>Notice that instead of writing <code>inEuros</code> we create a property on the <code>MetaClass</code> by writing <code>getInEuros</code>.  This allows us to drop the parenthesis from <strong><code>println 2500.00.inEuros</code></strong> and yields the same result as the method injection technique described above:</p>
<div class="outputBlock">
<pre>EUR1,587.40</pre>
</div>
<p>For detailed information on the <code>ExpandoMetaClass</code> and all of its uses, be sure to check out the <a href="http://groovy.codehaus.org/ExpandoMetaClass">Groovy User Guide</a>.</p>
<h3 id="categories">Categories</h3>
<p>Methods, properties, and constructors that are injected into a class via the <code>ExpandoMetaClass</code> are available anywhere within your application.  This is a convenient feature if you plan on using the method multiple times but could cause confusion if you only want the changes to take place in isolation.  This is where Categories come into play.  Categories allow you to inject functionality into a class, but these changes only take affect while calling the method from within the built in <strong><code>use()</code></strong> method's code block.</p>
<p>In order to take advantage of the <code>use()</code> method you must provide it with a "Category". A Category is simply a class with static methods that you wish to inject into your class.  Again, the scope of the added functionality is limited to the <code>use()</code> method's calling block.  If we take the exchange rate example from above and modify it to be used as a Category the code will be as follows:</p>
<div class="codeBlock">
	<pre><code>import java.text.NumberFormat

class ExchangeRateUtil  {
    def static inEuros(<strong>self</strong>) {
        def EXCHANGE_RATE = 0.634961 //June 27, 2008
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US)
        nf.setCurrency(Currency.getInstance("EUR"))
        nf.format(self * EXCHANGE_RATE)
    }
}

<strong>use(</strong>ExchangeRateUtil<strong>)</strong>{
    println 2500.00.inEuros()
}

println 10000.00.inEuros() //throws MissingMethodException</code>
	</pre>
</div>	
<p>I've created a new class called <code>ExchangeRateUtil</code> and created a static method called <code>inEuros()</code> within this class.  Notice that method takes a parameter called <strong><code>self</code></strong> which is used to represent the <code>BigDecimal</code> that we specified.  The remainder of the code for the conversion is exactly the same.</p>
<p>To use this category we call the <code>use()</code> method and within its block call the <code>inEuros()</code> method the same way we did in the example above.  The output will be the same for the call that is made within the <code>use()</code> calling block, but when we try to call the <code>inEuros()</code> method outside of the <code>use()</code> block a <code>MissingMethodException</code> is thrown.</p>
<div class="outputBlock">
<pre>EUR1,587.40
Caught: groovy.lang.MissingMethodException: ...</pre>
</div>
<h3>Conclusion</h3>
<p>As you can see, using metaprogramming gives static language programmers a whole new set of tools that can be used to creatively and elegantly arrive at solutions that can otherwise be overly complex in static languages.  In my next blog entry, I'll expand upon this current discussion and explain how we can use metaprogramming to not only add functionality to a class, but to actually create it on the fly with no previous knowledge of the methods that will be called on our class.</p><!-- wp hack--><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/groovy-metaprogramming-adding-behavior-dynamically/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Easy AOP with GroovyInterceptable</title>
		<link>http://www.fiascode.com/programming/easy-aop-with-groovyinterceptable/</link>
		<comments>http://www.fiascode.com/programming/easy-aop-with-groovyinterceptable/#comments</comments>
		<pubDate>Wed, 18 Jun 2008 18:56:54 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://www.fiascode.com/?p=11</guid>
		<description><![CDATA[Aspect Oriented Programming (AOP) is a technique that can be used to eliminate the repetition of cross-cutting concerns (logging, security, transaction management, etc.) in code.  AOP is useful because it provides programmers with a single point at which code can be modified and take effect across an entire system, but integrating AOP frameworks into [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming (AOP)</a> is a technique that can be used to eliminate the repetition of cross-cutting concerns (logging, security, transaction management, etc.) in code.  AOP is useful because it provides programmers with a single point at which code can be modified and take effect across an entire system, but integrating AOP frameworks into traditional Java applications tends to be somewhat cumbersome and complex.  Conversely, adding AOP-like features into <a href="http://groovy.codehaus.org/">Groovy</a> code is as simple as implementing the <code>GroovyInterceptable</code> interface.</p>
<p>Any Groovy object that implements this interface will automatically have all of its method calls routed through its <code>invokeMethod()</code> (assuming of course that this method has been implemented on the Groovy object itself or on its MetaClass).</p>
<span id="more-11"></span>
<h3>A Simple Example</h3>
<p>Let's take a look at a quick example.  Assume that for whatever reason we want to know the time before and after each call to a method in a class called <code>SimplePOGO</code>.  To accomplish this task in Groovy, we simply implement the <code>GroovyInterceptable</code> interface and the <code>invokeMethod()</code> like this:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {
    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
    }

    void simpleMethod2(String param1, Integer param2){
        System.out.println("simpleMethod2(${param1},${param2}) called")
        System.out.println("sleeping...")
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not 
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}\n")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()
simplePogo.simpleMethod2("stringParam", 24)</code>
	</pre>
</div>	
<p>This code will produce the following output:</p>
<div class="outputBlock">
<pre>time before simpleMethod1 called: Wed Jun 18 12:07:06 EDT 2008
simpleMethod1() called
time after simpleMethod1 called: Wed Jun 18 12:07:06 EDT 2008

time before simpleMethod2 called: Wed Jun 18 12:07:06 EDT 2008
simpleMethod2(stringParam,24) called
sleeping...

time after simpleMethod2 called: Wed Jun 18 12:07:08 EDT 2008</pre>
</div>	
<p>Because <code>SimplePOGO</code> implements <code>GroovyInterceptable</code> all calls to its methods will first be routed through its <code>invokeMethod()</code>.  Within the <code>invokeMethod()</code> we print the current time, look up the actual method that was called, call that method, and then print out the current time after execution.</p>
<h3>An Example with Nested Methods</h3>
<p>What happens if we nest methods?  Take a look at this example:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
        <strong>simpleMethod2Nested("stringParam", 24)</strong>
    }

    void simpleMethod2Nested(String param1, Integer param2){
        System.out.println("simpleMethod2Nested(${param1},${param2}) called")
        System.out.println("\nsleeping...\n")
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not 
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>time before simpleMethod1 called: Wed Jun 18 12:07:35 EDT 2008
simpleMethod1() called
time before simpleMethod2Nested called: Wed Jun 18 12:07:35 EDT 2008
simpleMethod2Nested(stringParam,24) called

sleeping...

time after simpleMethod2Nested called: Wed Jun 18 12:07:37 EDT 2008
time after simpleMethod1 called: Wed Jun 18 12:07:37 EDT 2008</pre>
</div>	
<p>Not too surprising.  When <code>simpleMethod1()</code> is called, the <code>invokeMethod()</code> in <code>SimplePOGO</code> is called which prints the current time stamp and then executes the <code>simpleMethod1()</code>.  Notice however that <code>simpleMethod1()</code> calls <code>simpleMethod2Nested()</code>.  When this call is made <code>invokeMethod()</code> will again be called so that the "before" time stamp will be printed out again.  When <code>simpleMethod2Nested()</code> finishes executing an "after" time stamp is printed to the screen and control returns to <code>simpleMethod1()</code> which also finishes executing and prints the current time to the screen.</p>
<h3>Gotcha?</h3>
<p>You may have noticed that I used <code>System.out.println()</code> instead of the Groovier <code>println()</code> to print the output to the screen.  This is because <code>println()</code> is a method that is built into the <code>GroovyObject</code> which is extended by all other Groovy objects (including <code>SimplePOGO</code>).  If a call to <code>println()</code> is made within one of <code>SimplePOGO's</code> methods then the <code>invokeMethod()</code> on <code>SimplePOGO</code> will be called again which may lead to output that is not quite expected:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        println "simpleMethod1() called"
    }

    void simpleMethod2(String param1, Integer param2){
        println "simpleMethod2(${param1},${param2}) called"
        println "sleeping..."
        Timer.sleep(2000)
    }

    def invokeMethod(String name, args){
        System.out.println("time before ${name} called: ${new Date()}")

        //Get the method that was originally called.
        def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

        //The "?" operator first checks to see that the "calledMethod" is not 
	//null (i.e. it exists).
        calledMethod?.invoke(this, args)

        System.out.println("time after ${name} called: ${new Date()}")
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()
simplePogo.simpleMethod2("stringParam", 24)</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>time before simpleMethod1 called: Wed Jun 18 12:13:32 EDT 2008
<strong>time before println called: Wed Jun 18 12:13:32 EDT 2008</strong>
simpleMethod1() called
<strong>time after println called: Wed Jun 18 12:13:32 EDT 2008</strong>
time after simpleMethod1 called: Wed Jun 18 12:13:32 EDT 2008
time before simpleMethod2 called: Wed Jun 18 12:13:32 EDT 2008
time before println called: Wed Jun 18 12:13:32 EDT 2008
simpleMethod2(stringParam,24) called
time after println called: Wed Jun 18 12:13:32 EDT 2008
time before println called: Wed Jun 18 12:13:32 EDT 2008
sleeping...
time after println called: Wed Jun 18 12:13:32 EDT 2008
time after simpleMethod2 called: Wed Jun 18 12:13:34 EDT 2008</pre>
</div>	
<p>Worse still is if you try to place the <code>println()</code> method inside of the <code>invokeMethod()</code> itself.  This will lead to recursive calls and an eventual <code>StackOverflowError</code>:</p>
<div class="codeBlock">
	<pre><code>class SimplePOGO implements GroovyInterceptable {

    void simpleMethod1(){
        System.out.println("simpleMethod1() called")
    }

    def invokeMethod(String name, args){
    	try {
	    <strong>println("time before ${name} called: ${new Date()}")</strong>

	    //Get the method that was originally called.
	    def calledMethod = SimplePOGO.metaClass.getMetaMethod(name, args)

	    //The "?" operator first checks to see that the "calledMethod" is 
            //not null (i.e. it exists).
	    calledMethod?.invoke(this, args)

	    <strong>println("time after ${name} called: ${new Date()}\n")</strong>
	} catch (StackOverflowError soe) {
	    System.out.println("A StackOverflowError was caught")
	    System.exit(0)
	}
    }
}

simplePogo = new SimplePOGO()
simplePogo.simpleMethod1()</code>
	</pre>
</div>
<p>This code will produce the following output:</p>
<div class="outputBlock">
	<pre>A StackOverflowError was caught</pre>
</div>	
<h3>Conclusion</h3>
<p>The examples listed above are very simple, but they illustrate how easy it is to implement the powerful features of AOP in Groovy.  It's not too difficult to envision how such a capability could be built into an application to handle a lot of the boiler plate code that tends to crowd non AOP applications.</p><!-- wp hack--><p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.fiascode.com/programming/easy-aop-with-groovyinterceptable/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
