Jul 21 2009

Toolbars with HotCocoa

3407707273_c05017779fI had the opportunity to add a toolbar to my Silver Lining app the other day and though I’d write down how I did it. This would, probably, have been easier if I had an understanding of the Cocoa Toolbar.

The main thing that kept tripping me up is that you don’t add toolbar items directly to the toolbar. Each item you want to add to the toolbar is given an identifier (HotCocoa will generate one from the label if needed). Then, when you create your toolbar, you specify which toolbar items are in the toolbar by default and which items are available to be put in the bar.

Once the toolbar is created we don’t just append it to the window with the normal << operator. We need to use toolbar= to assign the toolbar to the window.

silverlining_toolbarThe toolbar we’re going to create is fairly simple. We want a button, with image, on the left for reloading and a search field on the right. We’ll put a flexible spacer in the middle to put them on opposite sides of the screen. (Note, there is currently a bug in HotCocoa where our specified items will be to the right and the spacer to the left. Things may not look correct until fixed.)

reload_item = toolbar_item(:label => "Reload",
                           :image => image(:named => "reload"))
reload_item.on_action { reload_instances }

The first toolbar item we create is the reload button. We set the image on the button to a file in the resources folder called reload.png. When the button is clicked, we want to execute the reload_instances method.

search_item = toolbar_item(:identifier => "Search") do |si|
  search = search_field(:frame => [0, 0, 250, 30],
                        :layout => {:align => :right, :start => false})
  search.on_action { |sender| filter_instances(search) }

  si.view = search
end

The second item is the search box. You’ll notice we’re setting the :identifier instead of the :label as we did for the reload button. The difference being, the label will appear below the button and we don’t want Search appearing below the search box. The reload button will have an identifier of Reload created for it by HotCocoa.

With the search toolbar item in hand we create a search_field. The search field is then assigned as the view in the search toolbar item using si.view=.

@toolbar = toolbar(:default => [reload_item, :flexible_space, search_item]) do |tb|
  win.toolbar = tb
end

Finally, we create our toolbar. This is done with the toolbar method. We want our default set of items to be the reload_item, :flexible_space and search_item. We then assign the toolbar to our window with win.toolbar = tb.

There are a few default toolbar items you can use, similar to :flexible_space. They are:

  • :separator
  • :space
  • :flexible_space
  • :show_colors
  • :show_fonts
  • :customize
  • :print

That’s all folks. Have fun.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Jul 15 2009

EventMachine Screencast — EM-HTTP-Request

IMG_6037I decided to try my hand at creating a screencast the other day. I took a look at the EventMachine EM-HTTP-Request library and created a simple shell program to do single and multi requests. Take a look and let me know what you think.

require ‘rubygems’
require ‘eventmachine’
require ‘em-http’
require ‘pp’

$stdout.sync = true

class KeyboardHandler < EM::Connection
  include EM::Protocols::LineText2
 
  def post_init
    print "> "
  end
 
  def receive_line(line)
    line.chomp!
    line.gsub!(/^\s+/, )
   
    case(line)
    when /^get (.*)$/ then
      site = $1.chomp
      sites = site.split(‘,’)
     
      multi = EM::MultiRequest.new
      sites.each do |s|
        multi.add(EM::HttpRequest.new(s).get)
      end
      multi.callback {
        puts ""
        multi.responses[:succeeded].each do |h|
          pp h.response_header.status
          pp h.response_header
        end
        multi.responses[:failed].each do |h|
          puts "#{h.inspect} failed"
        end
        print "> "
      }
      print "> "

    when /^exit$/ then
      EM.stop

    when /^help$/ then
      puts "get URL[,URL]*   – gets a URL"
      puts "exit      - exits the app"
      puts "help      - this help"
      print "> "
    end
  end
end

EM::run {
  EM.open_keyboard(KeyboardHandler)
}
puts "Finished"

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Jul 07 2009

Google Analytics, OAuth and Ruby. Oh, my.

Categories: Computers, Programming
Tags: , ,

IMG_6658I recently had the opportunity to take a peek at accessing Google Analytics data using their OAuth endpoint. We did this in Ruby using the Ruby OAuth gem. There were a few snags along the way so I figured I’d put up some notes for other people to take a peek.

First, you’re going to need a newer version of the OAuth gem (0.3.5 seems to work). Google uses some features from the 1.0a version of the OAuth spec, the oauth_verifier specifically, that aren’t available in older versions of the OAuth gem. That took a while to track down.

The second thing you’re going to need is a consumer token and secret from google. You can retrieve this from your domain management page (here as it’s a bit difficult to find.)

require ‘oauth’
con = OAuth::Consumer.new(CONSUMER_TOKEN, CONSUMER_SECRET,
                              {:site => ‘https://www.google.com’,
                               :request_token_path => ‘/accounts/OAuthGetRequestToken’,
                               :access_token_path => ‘/accounts/OAuthGetAccessToken’,
                               :authorize_path => ‘/accounts/OAuthAuthorizeToken’})

To start we create our OAuth connection. You’ll need to substitute your token and secret for the consumer constants above. We need to specify all of the OAuth paths to match the endpoints provided by Google.

rt = con.get_request_token({}, {:scope => ‘https://www.google.com/analytics/feeds’})

We use the connection to create a request token. get_request_token takes two parameters. The token parameters and other parameters. Above, I’m not specifying any request parameters but, if you want Google to redirect the user to a site of your choice you would provide {:oauth_callback => URL} as the token parameter. After authenticating the user would be redirected to the provided URL and the parameters oauth_token=TOKEN and oauth_verifier=VERIFIER will be passed to the URL. You’ll need to use those parameters when creating the access token.

The second parameter when creating the request token is used by Google to restrict the users access to specific portions of Google. In our case we’re requesting access to the Analytics data. A list of available scopes is here. You can specify multiple scope values by putting a space between them. e.g. "http://www.google.com/calendar/feeds/%20http://docs.google.com/feeds/".

rt.authorize_url       => "https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=4%2F-1o2aZgHxJmjhaExv9htRsGWLlwy"

google-1With our request token in hand we can use it to generate the authorization URL. You’ll need to redirect the user to this URL to do the authentication.

Since we aren’t providing a callback URL our users will just get redirected to a standard Google page and you’ll need to copy their verifier code into the application.

at = rt.get_access_token(:oauth_verifier => ‘vQH9bpXateNpsISpEDZax’)

google-2When the user has authorized we either get them to paste the verifier code or we can retrieve it from the parameters passed to our oauth_callback. We use the verifier code to create an access token. This is the token we’ll be using to access the Google resources. We can save the at.token and at.secret values into our database to create new access tokens next time the user needs data from Google. We don’t need to authenticate each time.

at = OAuth::AccessToken.new(con, USER_TOKEN, USER_SECRET)

We can also, if we’re using the oauth_callback store some of our request token information to the session. If we store rt.token and rt.secret we can re-build our request token in a simlar fashion to the access token.

rt = OAuth::RequestToken.new(con, REQUEST_TOKEN, REQUEST_SECRET)

With the authentication out of the way we can get on with accessing the analytics data.

puts at.get("https://www.google.com/analytics/feeds/accounts/default?prettyprint=true").body

We grab our profile data first. You’ll need the dxp:tableId value in order to make calls to get profile specific analytic data. (The prettyprint=true is a handy little flag to get Google to nicely indent the XML returned. Makes for easier reading/debugging.)

< ?xml version=‘1.0′ encoding=‘UTF-8′?>
<feed xmlns=‘http://www.w3.org/2005/Atom’ xmlns:openSearch=‘http://a9.com/-/spec/opensearchrss/1.0/’ xmlns:dxp=‘http://schemas.google.com/analytics/2009′>
  <id>http://www.google.com/analytics/feeds/accounts/dan.sinclair@gmail.com</id>
  <updated>2009-07-06T11:00:09.000-07:00</updated>
  <title type=‘text’>Profile list for dan.sinclair@gmail.com</title>
  <link rel=’self’ type=‘application/atom+xml’ href=‘http://www.google.com/analytics/feeds/accounts/default’/>
  <author>
    <name>Google Analytics</name>
  </author>
  <generator version=‘1.0′>Google Analytics</generator>
  <opensearch :totalResults>1</opensearch>
  <opensearch :startIndex>1</opensearch>
  <opensearch :itemsPerPage>1</opensearch>
  <entry>
    <id>http://www.google.com/analytics/feeds/accounts/ga:123xxxx</id>
    <updated>2009-07-06T11:00:09.000-07:00</updated>
    <title type=‘text’>everburning</title>
    <link rel=‘alternate’ type=‘text/html’ href=‘http://www.google.com/analytics’/>
    <dxp :tableId>ga:123xxxx</dxp>
    <dxp :property name=‘ga:accountId’ value=‘73xxxx’/>
    <dxp :property name=‘ga:accountName’ value=‘everburning’/>
    <dxp :property name=‘ga:profileId’ value=‘123xxxx’/>
    <dxp :property name=‘ga:webPropertyId’ value=‘UA-73xxxx-1′/>
    <dxp :property name=‘ga:currency’ value=‘USD’/>
    <dxp :property name=‘ga:timezone’ value=‘America/Toronto’/>
  </entry>
</feed>

puts at.get("https://www.google.com/analytics/feeds/data?ids=ga:123xxxx&start-date=2009-06-05&end-date=2009-06-06&dimensions=ga:pagePath&metrics=ga:pageviews,ga:uniquePageviews&prettyprint=true").body

The data I want from Google Analytics is the number of ga:pageviews and ga:uniquePageviews for each ga:pagePath between June 5th and 6th.

< ?xml version=‘1.0′ encoding=‘UTF-8′?>
<feed xmlns=‘http://www.w3.org/2005/Atom’ xmlns:openSearch=‘http://a9.com/-/spec/opensearchrss/1.0/’ xmlns:dxp=‘http://schemas.google.com/analytics/2009′>
  <id>http://www.google.com/analytics/feeds/data?ids=ga:123xxxx&amp;dimensions=ga:pagePath&amp;metrics=ga:pageviews,ga:uniquePageviews&amp;start-date=2009-06-05&amp;end-date=2009-06-06</id>
  <updated>2009-06-06T16:59:59.999-07:00</updated>
  <title type=‘text’>Google Analytics Data for Profile 123xxxx</title>
  <link rel=’self’ type=‘application/atom+xml’ href=‘http://www.google.com/analytics/feeds/data?end-date=2009-06-06&amp;start-date=2009-06-05&amp;metrics=ga%3Apageviews%2Cga%3AuniquePageviews&amp;ids=ga%3A123xxxx&amp;dimensions=ga%3ApagePath’/>
  <author>
    <name>Google Analytics</name>
  </author>
  <generator version=‘1.0′>Google Analytics</generator>
  <opensearch :totalResults>52</opensearch>
  <opensearch :startIndex>1</opensearch>
  <opensearch :itemsPerPage>52</opensearch>
  <dxp :startDate>2009-06-05</dxp>
  <dxp :endDate>2009-06-06</dxp>
  <dxp :aggregates>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:pageviews’ type=‘integer’ value=‘162′/>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:uniquePageviews’ type=‘integer’ value=‘152′/>
  </dxp>
  <dxp :dataSource>
    </dxp><dxp :tableId>ga:1239xxxx</dxp>
    <dxp :tableName>everburning</dxp>
    <dxp :property name=‘ga:profileId’ value=‘123xxxx5′/>
    <dxp :property name=‘ga:webPropertyId’ value=‘UA-73xxxx-1′/>
    <dxp :property name=‘ga:accountName’ value=‘everburning’/>
 
  <entry>
    <id>http://www.google.com/analytics/feeds/data?ids=ga:123xxxx&amp;ga:pagePath=/&amp;start-date=2009-06-05&amp;end-date=2009-06-06</id>
    <updated>2009-06-05T17:00:00.001-07:00</updated>
    <title type=‘text’>ga:pagePath=/</title>
    <link rel=‘alternate’ type=‘text/html’ href=‘http://www.google.com/analytics’/>
    <dxp :dimension name=‘ga:pagePath’ value=‘/’/>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:pageviews’ type=‘integer’ value=‘9′/>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:uniquePageviews’ type=‘integer’ value=‘8′/>
  </entry>
  <entry>
    <id>http://www.google.com/analytics/feeds/data?ids=ga:123xxxx&amp;ga:pagePath=/quotes/&amp;start-date=2009-06-05&amp;end-date=2009-06-06</id>
    <updated>2009-06-05T17:00:00.001-07:00</updated>
    <title type=‘text’>ga:pagePath=/quotes/</title>
    <link rel=‘alternate’ type=‘text/html’ href=‘http://www.google.com/analytics’/>
    <dxp :dimension name=‘ga:pagePath’ value=‘/quotes/’/>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:pageviews’ type=‘integer’ value=‘6′/>
    <dxp :metric confidenceInterval=‘0.0′ name=‘ga:uniquePageviews’ type=‘integer’ value=‘6′/>
  </entry>
</feed>

You may notice that all of the paths returned are relative to some base URL. I haven’t been able to figure out how to get Google Analytics to tell me what that base URL happens to be. If you figure it out, please leave a comment so I can update my code.

That’s it. You can take a deeper look at the Google Analytics API documentation to learn about the different dimensions and metrics that can be queried.

If you’re doing this in Ruby you may also want to take a look at the Happy Mapper gem to make your XML using life easier.

Have fun.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]