<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Justin Spradlin &#187; Groovy</title>
	<atom:link href="http://www.justinspradlin.com/tag/groovy/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.justinspradlin.com</link>
	<description>Coding and such...</description>
	<lastBuildDate>Wed, 03 Mar 2010 17:52:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Groovy Domain Specific Language Tutorial</title>
		<link>http://www.justinspradlin.com/programming/groovy-domain-specific-language-tutorial/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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 capabilities 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 capabilities 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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/groovy-domain-specific-language-tutorial/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Putting Google Finance to REST with Groovy</title>
		<link>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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 authentication 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.justinspradlin.com/images/empty_portfolio_large.jpg"><img alt="Empty Portfolio" class="centered" src="http://www.justinspradlin.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.justinspradlin.com/images/groovy_portfolio_large.jpg"><img  alt="Groovy Portfolio Added" class="centered" src="http://www.justinspradlin.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.justinspradlin.com/images/groovy_portfolio_sun_large.jpg"><img alt="Stocks Purchased" class="centered" src="http://www.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/putting-google-finance-to-rest-with-groovy/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Groovy Metaprogramming – Creating Behavior on the Fly</title>
		<link>http://www.justinspradlin.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/groovy-metaprogramming-creating-behavior-on-the-fly/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Groovy Metaprogramming &#8211; Adding Behavior Dynamically</title>
		<link>http://www.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/groovy-metaprogramming-adding-behavior-dynamically/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Easy AOP with GroovyInterceptable</title>
		<link>http://www.justinspradlin.com/programming/easy-aop-with-groovyinterceptable/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/easy-aop-with-groovyinterceptable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
