lunedì 2 luglio 2007

RESTful Web Services Example 2.4 - a del.icio.us client

Example 2.4 is a simple del.icio.us client that prints the most recent bookmarks added to an account.

The Squeak Smalltalk version is the following:
Chapter2>>deliciousRecent: username password: password
| deliciousURI xml document |
"Code taken from RESTful Web Services. Copyright © 2007 O'Reilly Media, Inc.
All rights reserved. Used with permission."
deliciousURI := 'https://{1}:{2}@api.del.icio.us/v1/posts/recent'.
xml := Curl new getContentsUrl: (deliciousURI format: {username. password}).
document := XMLDOMParser parseDocumentFrom: xml readStream.
document posts post
do: [:each |
Transcript
show: (each at: #description) , ': ' , (each at: #href);
cr]

If we compare it with the Ruby example in the book, there are a couple of differences.

The first one is the use of the Curl plugin, as anticipated in the previous post.
This forces us to insert username and password in the URI that we pass to #getContentsUrl:. In order to do this we use a relatively obscure feature of Squeak's String class: the #format: message. This message behaves like the C standard function printf().

Another difference is in the object returned by #getContentsUrl:. Instead of returning a Stream object, this message returns a string; but since XMLDOMParser requires a Stream object, we create one by sending #readStream to the string.

Once we have a DOM tree, we can select the post elements by sending
    document posts post

thus retrieving all the post elements. We then iterate over all these elements to print the description and href attributes.

The book provides two other Ruby versions of this example: one using the SAX parser, the other using the pull parser. I won't convert these two examples, since I don't think they're really significant in this context.

The code for this method is available on the RWS repository, in the RWS-gc.6 package.

In the next post, we'll see a new version of #yahooWebSearch: that uses JSON as the output format.

Nessun commento: