<?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; Web Services</title>
	<atom:link href="http://www.justinspradlin.com/tag/web-services/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.justinspradlin.com</link>
	<description>Coding and such...</description>
	<lastBuildDate>Sun, 06 Mar 2011 06:19:59 +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>Introducing GMoney – A RubyGem for Interacting with the Google Finance API</title>
		<link>http://www.justinspradlin.com/programming/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/</link>
		<comments>http://www.justinspradlin.com/programming/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 06:00:30 +0000</pubDate>
		<dc:creator>Justin Spradlin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Open Source]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://www.justinspradlin.com/?p=87</guid>
		<description><![CDATA[That's why I wrote GMoney, a <a href="http://docs.rubygems.org/">RubyGem</a> for interacting with the <a href="http://code.google.com/apis/finance/">Google Finance API]]></description>
			<content:encoded><![CDATA[<div class="blockquote"> 
<p><strong>Update March 03, 2010:</strong></p><p>Due to changes in the Google Finance API only GMoney gem versions >= 0.4.3 are working.  If you run <code>gem update gmoney</code> to get the latest version or install the gem from scratch you will be fine.</p>
</div>
<p>Let&#8217;s pretend the year is 2007 and I have a close &#8220;friend&#8221; who is really excited about the upcoming <a href="http://www.fifa.com/worldcup/">2010 World Cup</a>.  My friend is not too naive and realizes that airfare to Africa, lodging, tickets to the games, and Safaris are all very expensive.  My friend has a little extra cash to save each month and with a three year time horizon he figures he can stow away a little money in a moderately aggressive mutual fund in order to take advantage of some growth opportunities.</p>
<p>Unfortunately for my friend the next two years would be some of the <a href="http://en.wikipedia.org/wiki/Financial_crisis_of_2007%E2%80%932010">worst the world economy has ever seen</a>.  Like many people, my friend <a href="http://idioms.thefreedictionary.com/took+a+bath#MainTxt">took a bath</a> on his investments and his hopes and dreams of going to the World Cup went down the drain along with his money.</p>
<p>It&#8217;s too bad my friend didn&#8217;t keep better track of his investments.  Perhaps if he had he could have pulled his money out of the stock market and salvaged his vacation.  Since my friend is an avid Ruby lover I figured I&#8217;d help make sure he doesn&#8217;t end up in this situation ever again.  That&#8217;s why I wrote GMoney, a <a href="http://docs.rubygems.org/">RubyGem</a> for interacting with the <a href="http://code.google.com/apis/finance/">Google Finance API</a>.</p>
<span id="more-87"></span>
<h3>Background</h3>
<p>The Google Finance API allows users to interact with <a href="http://www.google.com/finance">Google Finance</a> and can help developers programmatically &#8220;request a list of a user&#8217;s portfolios, retrieve performance and return statistics on an existing portfolio, query the positions and transactions in a portfolio, and create new portfolios and transactions.&#8221;</p>
<p>GMoney is a wrapper for this API and allows developers to take advantage of the API&#8217;s functionality using the <a href="http://www.ruby-lang.org/en/">Ruby programming language</a>.  To minimize the learning curve I tried to give GMoney an interface similar to that of <a href="http://ar.rubyonrails.org/">ActiveRecord</a> so that developers would have a familiar starting point.</p>
<h3>Google Finance Model</h3>
<p>The Google Finance model is pretty simple.  It is made up of the following three entities:</p>
<p><strong>Portfolios</strong></p>
<div class="blockquote"> 
<p>A portfolio is a collection of positions that the user holds in various securities, plus metadata.  Each portfolio entry contains the portfolio&#8217;s title along with data such as currency and total market value. Each portfolio entry also contains a link to the portfolio&#8217;s position feed (i.e. a Portfolio &#8220;has_many&#8221; Positions).</p>
</div>
<p><strong>Positions</strong></p>
<div class="blockquote"> 
<p>A position is a collection of information about a security that the user holds.  Each position entry contains the ticker exchange and symbol for a stock, mutual fund, or other security, along with the number of units of that security that the user holds. Each position entry also contains a link to the position&#8217;s transaction feed (i.e. a Position &#8220;has_many&#8221; Transactions).</p>
<p>You can&#8217;t directly create or update position entries; positions are derived from transactions.</p>
</div>
<p><strong>Transactions</strong></p>
<div class="blockquote"> 
<p>A transaction is a collection of information about an instance of buying or selling a particular security.  Each transaction entry contains a transaction type (such as buy or sell), a number of units, the price, and so on.</p>
</div>
<h3>Installation</h3>
<p>To install GMoney simply run the following command:</p>
<div class="codeBlock"> 
	<pre><code>gem install gmoney</code></pre> 
</div> 
<h3>Login</h3>
<p>You will need a <a href="http://www.google.com/accounts">Google account</a> in order to use the Google Finance API.  Once you have obtained an account you can login via GMoney using the following code:</p>
<div class="codeBlock"> 
	<pre><code>require 'rubygems'
require 'gmoney'

GMoney::GFSession.login('&lt;YOUR GOOGLE USER ID&gt;','&lt;YOUR GOOGLE PASSWORD&gt;')</code></pre> 
</div>
<h3>Create a portfolio</h3>
<p>If you were to login to Google Finance for the first time using a browser you would see the following screen showing the default Google Finance Portfolio called &#8220;My Portfolio&#8221;:</p>
<p><a href="http://www.justinspradlin.com/images/default_portfolio.jpg"><img src="http://www.justinspradlin.com/images/default_portfolio_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<p>To create your own Portfolio using GMoney use the following code:</p>
<div class="codeBlock"> 
	<pre><code>portfolio = GMoney::Portfolio.new
portfolio.title = "My New Ruby Portfolio"
portfolio.save</code></pre> 
</div>
<p>After executing the code and refreshing the browser you should see that the &#8220;My New Ruby Portfolio&#8221; has been created.</p>
<p><a href="http://www.justinspradlin.com/images/create_portfolio.jpg"><img src="http://www.justinspradlin.com/images/create_portfolio_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Create a transaction(s)</h3>
<p>As mentioned above transactions are used to buy and sell stocks within a given portfolio.  The positions within your portfolio will be based on the transaction information.  Running the following code will buy shares of Apple, Red Hat, Google, and Microsoft and place them into your portfolio:</p>
<div class="codeBlock"> 
	<pre><code>stocks = {"NASDAQ:GOOG" => 529.00, 
          "NASDAQ:AAPL" => 192.00, 
          "NYSE:RHT" => 27.00, 
          "NASDAQ:MSFT" => 28.00}
 
stocks.each do |symbol, price| 
  transaction = GMoney::Transaction.new
  #pid is the human readable id of the portfolio created above
  transaction.portfolio = portfolio.pid
  transaction.type = GMoney::BUY
  transaction.shares = 50
  transaction.ticker = symbol
  transaction.price = price  
  transaction.save
end</code></pre> 
</div>
<p>The result of running the code is as follows:</p>
<p><a href="http://www.justinspradlin.com/images/buy_stocks.jpg"><img src="http://www.justinspradlin.com/images/buy_stocks_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Update Transaction</h3>
<p>If you actually meant to buy 100 shares of Goolge instead of 50 you can update the transaction using the following code:</p>
<div class="codeBlock"> 
	<pre><code>#I know the transaction id is '4'
transaction = GMoney::Transaction.find "#{portfolio.pid}/NASDAQ:GOOG/4"
transaction.shares = 100
transaction.save</code></pre> 
</div>
<p>The result:</p>
<p><a href="http://www.justinspradlin.com/images/update_goog.jpg"><img src="http://www.justinspradlin.com/images/update_goog_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Delete Transaction</h3>
<p>We can delete a transaction like so:</p>
<div class="codeBlock"> 
	<pre><code>GMoney::Position.find("#{portfolio.pid}/NASDAQ:MSFT").delete</code></pre> 
</div>
<p>Now we have no more MSFT stock:</p>
<p><a href="http://www.justinspradlin.com/images/delete_trans.jpg"><img src="http://www.justinspradlin.com/images/delete_trans_s.jpg" class="center" alt="Create Portfolio" /></a></p>
<h3>Reading all the Positions in a Porfolio</h3>
<p>If we&#8217;d like to see all of the positions within our portfolio we can execute this code:</p>
<div class="codeBlock"> 
	<pre><code>portfolio.positions.each do |position| 
  puts position.title
end</code></pre> 
</div>
<p><strong>Output:</strong></p>
<div class="outputBlock"> 
<pre>Red Hat, Inc.
Apple Inc.
Google Inc.</pre> 
</div> 
<h3>Gotcha</h3>
<p>There is a bit of a &#8220;gotcha&#8221; right now with the Google Finance API.  For whatever reason, stock returns information is not being sent by Google.  I figured it was something I was doing wrong in my code, but then I used <a href="http://code.google.com/apis/gdata/docs/client-libraries.html">Google&#8217;s official API client</a> and was still unable to retrieve the returns data.  I&#8217;ll be sure to file a <a href="http://code.google.com/p/gdata-issues/issues/list">bug report</a> with Google over the next few days.</p>
<h3>Conclusion</h3>
<p>GMoney offers a lot more features than what has been written about here.  Be sure to check out the documentation and the source code on <a href="http://github.com/jspradlin/gmoney">Github</a>.  The full script of the code used for this blog entry can also be found on <a href="http://github.com/jspradlin/justinspradlin.com-blog-examples/tree/master/2010-02-01_Introducing-GMoney-A-RubyGem-for-Interacting-with-the-Google-Finance_API/">Github</a>.</p>
<p>Overall building GMoney was an incredible learning experience.  It was my first significant Ruby project and also my first Open Source project.  As of today GMoney has been downloaded almost <a href="http://gemcutter.org/gems/gmoney">200 times</a>.  I&#8217;ve tested GMoney on Windows and Linux using Ruby versions 1.8.6, 1.8.7, and 1.9.1 (via <a href="http://rvm.beginrescueend.com/">RVM</a>).  Feedback and bug reports are more than welcome.</p>
<p>With GMoney in place my friend will be sure to keep much better track of his investments and is looking forward to the <a href="http://en.wikipedia.org/wiki/2014_FIFA_World_Cup">2014 World Cup in Brazil</a>.</p>
<p><i>Disclaimer:</i> 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/introducing-gmoney-a-rubygem-for-interacting-with-the-google-finance-api/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Putting Google Finance to REST with Ruby</title>
		<link>http://www.justinspradlin.com/programming/putting-google-finance-to-rest-with-ruby/</link>
		<comments>http://www.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.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.justinspradlin.com/programming/putting-google-finance-to-rest-with-ruby/feed/</wfw:commentRss>
		<slash:comments>15</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>11</slash:comments>
		</item>
	</channel>
</rss>

