Archive for June, 2008

Dreaming the Right Dreams

Thursday, June 5th, 2008

In the world of technology, progress is king. Every morning I ride the elevator up 30 floors to a bunch of people who are interested in finding solutions for the world, making it better, stronger, more efficient. They are innovators, they are optimists; there is no gap in technology that they don’t want to fill with some snazzy code and a slick interface.

It’s refreshing as hell.

I’m new to this world. I spent my first week gawking at my computer screen, discovering application after application that solved problems for me: Money management! Whiteboard scanning!. I had no idea people were even thinking about making these areas of my life better, let alone providing them for free on the Internet. Judge if you want, but I’m a pretty normal prototype of what Geoffrey Moore refers to as the “Pragmatists” (not super tech-savvy, but willing to get excited about using it when it fits just right). And as a social 20-something professional living in New York, I’m splat in the middle of the consumer group that software products want to court.

Which is why I bring a different perspective to the making of software. I’m surrounded by people who dream up big ideas on a daily basis, who notice the collaborative instinct we have here at Arc90 and write applications to harness that energy. And though I’m incredibly impressed by the ways people could use technology to evolve what they deem unsuitable, I’m also in a unique position to wonder about whether we should.

One of the issues I seem to keep stubbing my toe against is that of information storage. As members of this industry, we’re getting so much better about storing and sorting, recording and re-finding information that we come across, that we’re afraid to let anything go. In recent planning meetings for a new Arc product, we’ve discussed the extent to which users or ideas should be deleted- as in, gone. FOREVER. Everyone gets a little uneasy when that part of the conversation comes up- we’re afraid that our users are going to accidentally do something undoable that they regret. We want to protect them, either because we’re very sweet and we don’t want to see them scrape their knees, or because we’re cynical about the idea of being inundated with emails from people who never quite learned to read directions.

A recent tour of the web-application Evernote, whose insane motto is “Remember Everything,” sticks out as a prime example. Essentially, it has the capacity to store EVERY possible thing for later use—notes on a napkin, a photo of your favorite bottle of sake, information on a web page. Everything you encounter in your life can be saved, tagged, and stored in your Evernote account. It’s searchable and it’s sexy (in the tour video, a search for a hotel results in images of a hand-written post-it labeled “The Venetian” stuck to the dude’s old airplane tickets). But come on. Who has the time to invest in it all?

The whole scenario screams the question: are we living in the age of narcissism (in which we think everything we doodle on a napkin is worth keeping) or the age of progress (in which we become uber-efficient because we never waste time searching for anything, from our car keys to the genius invention you scribbled on a Post-it in 1998)?

The more I learn about the technology universe, the more I realize how crowded it is and how over-extended our potential users are. Applications like Evernote appeal to the control-freak within us, but won’t ever reach broad consumption. Given the choice between scanning her old airline tickets into Evernote and spending a few minutes window-shopping, I think we know what the average Jane is going to pick. For that reason, if we want the Pragmatists as clients, we have to create software that’s flashy enough for the technologists, but fulfills the true needs of the average consumer.

Building RESTful Web Apps with Groovy and Restlet, Part 1: Up and Running

Wednesday, June 4th, 2008

Here at Arc90, we love REST. We’ve implemented RESTful web apps using ColdFusion, Java, .NET/C#, and PHP. We’re big fans of Restlet, a Java REST framework. I’ve also recently started experimenting with Groovy, “an agile dynamic language for the Java Platform,” and so far I’m liking it.

So it’s a no-brainer for us to put Groovy and Restlet together and see what happens. So far, I like what I see. That said, it’ll be tough to convince some of my PHP-loving and Pythonistic colleagues to even consider Groovy, given its Java roots. Some of them fairly shudder when they hear those two syllables “ja-va”. Ooh, scary.

This blog series will be my attempt to present how Groovy and Restlet together create a compelling platform for rapid RESTful web application development.

So let’s get started with the classic Hello world!

Prerequisites

Before we get started, two prerequisites:

  1. Java 1.5 or newer – download (I used 1.5.0_13)
  2. Groovy 1.5 or newer – download (I used 1.5.6)

Setup

  1. Download the latest version of Restlet 1.1 – link – and extract it anywhere
  2. Create a folder named restfulapp
  3. Create a file named restfulapp.groovy
  4. Copy two files from the Restlet distribution’s lib folder to restfulapp:
    • org.restlet.jar
    • com.noelios.restlet.jar

I’m specifying Restlet 1.1, which hasn’t yet hit final release, as opposed to the stable 1.0 branch, because it has a built-in HTTP server and client, which makes it really easy to just dive right into development and have something up and running quickly. These built in HTTP components aren’t production-class, but they’re very convenient for our purposes here.

The Code

Before we get into the code, please note: this code does not demonstrate best practices, and is not production ready; at this point I just want to establish basic concepts.

restfulapp.groovy

Copy the following code into restfulapp.groovy:

#!/usr/bin/env groovy -classpath org.restlet.jar:com.noelios.restlet.jar
import org.restlet.*
import org.restlet.data.*
// RequestHandler will handle all of our requests
class RequestHandler extends Restlet
{
// handle() is called by the framework whenever there's a HTTP request
def void handle(Request request, Response response)
{
/* The only method that's allowed is GET, so check it -- if it's GET,
return a representation, and the default status will be returned,
which is 200 OK. If not, set the response status to an error. */
if (request.method == Method.GET)
{
/* handle() returns void, for reasons that will become clear
later. The way to output content is modify the passed-in response
by setting the Entity of the response. Restlet refers to the
Representation as an "entity"; I'm actually not 100% sure why. */
response.setEntity("Hello, world!", MediaType.TEXT_PLAIN)
}
else
{
// The request method is not GET, so set an error response status
response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED)
response.setAllowedMethods([Method.GET] as Set)
}
}
}
/* Create a new HTTP Server on port 3000, pass it a new instance of RequestHandler,
to which it will pass all incoming Requests, and start it. */
new Server(Protocol.HTTP, 3000, new RequestHandler()).start()

I’m hoping this code illustrates some of the great aspects of Restlet and Groovy. Restlet’s class model is clear and intuitive because it was designed specifically to model REST concepts, so a server is a Server, a method is a Method, a Request is a request, etc. And because this app is a Groovy script, we can use inline class definitions, and the syntax is nice and clean and easy.

I particularly like that Groovy maps the == operator to “value equality” as opposed to “identity equality” as in Java. The Java equivalent of line 16 would be:

if (request.getMethod().equals(Method.GET))

This also illustrates Groovy’s automatic getter referencing: to retrieve the method of the request, in Groovy I can use the syntax request.method, and Groovy automatically converts it into request.getMethod(). Nice!

Up and Running

Unices

$ chmod +x restfulapp.groovy
$ ./restfulapp.groovy

Windows

Launch a command prompt window, navigate to restfulapp, and run the command:

groovy -classpath org.restlet.jar;com.noelios.restlet.jar restfulapp.groovy

Test!

If you have cURL installed, you can run a quick ad-hoc test with the following command:

curl -v http://localhost:3000

But Groovy can make unit testing really easy:

Create a new file named testfulapp.groovy and copy the following code into it:

#!/usr/bin/env groovy -classpath org.restlet.jar:com.noelios.restlet.jar
import org.restlet.*
import org.restlet.data.*
client = new Client(Protocol.HTTP)
response = client.get("http://localhost:3000/")
assert response.status.code == 200
assert response.entity.mediaType.equals(MediaType.TEXT_PLAIN, true)
assert response.entity.size == 13
assert response.entity.text == "Hello, world!"
println "\nAll tests passed successfully!\n"

Open a new command prompt window, alongside the one already running restfulapp.groovy, and run testfulapp.groovy using the same steps outlined above for restfulapp.groovy for your OS. If all goes well, you should see “All tests passed successfully!” as the result!

Performance

Just for fun, if you’ve got a copy of ab installed:

ab -c 2 -t 10 http://localhost:3000/

Any numbers you see from ab can only be compared to your own, because everyone’s hardware and software varies, but it’s still fun to try pounding on your code and see what happens. I got 713 requests per second on my 2.2 GHz Santa Rosa Core 2 Duo MacBook, on OS X 10.5.3 and Java 1.5.0_13 – not bad!

That’s all, folks!

And that’s all for now. I hope this has been interesting and/or informative. I’d love to hear some feedback from readers: has this article made you interested in learning more about Groovy and/or Restlet?

Coming soon: Part 2: Resources.

Update, June 13th: Just published Part 2: Resources.

Twitter API Client Released

Tuesday, June 3rd, 2008

Here at Arc90, we love Twitter! Okay, okay – maybe not all of us love Twitter…some of us… I mean, well, at least one of us! Anyway, recently in need of Twitter’s services for an office side-project, we decided to write our own client that would integrate nicely with our existing PHP libraries.

The default content type for returned data is JSON (we love JSON!), but all of Twitter’s supported content types are available (XML, JSON, and in some cases RSS and ATOM).

Sound useful? Head on over to the lab and check it out!

Also…

Our Twitter client was largely inspired by the great web service clients available through the Zend Framework. Zend offers clients for several great web services like del.icio.us and Flickr; but Twitter is conspicuously absent from the list…While we’re not really sure why Zend has (so far) decided not to offer a Twitter client, we may also release a fully Zend-tastic version of the client leveraging Zend_Client_Rest, Zend_Date, etc in the near future. If you develop with Zend Framework and would find this useful, let us know!

A More Convenient Zend_Registry

Monday, June 2nd, 2008

The Zend_Registry is a pretty useful part of the MVC architecture of the Zend Framework. It’s a singleton class that keeps the developer from having to define global variables throughout their application. The downside is that retrieving the variables stored in the Zend_Registry can be tedious and annoying if you’re doing it often. Here’s an example:

$config = Zend_Registry::get('config');

Pretty verbose, huh? From that point on you can access the variables inside of config:

if($config->settings->environment == 'development') …

Wouldn’t it be much simpler if, whenever you needed to retrieve something from the Zend_Registry inside of your controllers, you could access them inline? For example:

$this->registry->config->settings->environment

In order to get this to work, you need to extend the Zend_Controller_Action class and overload the __get method. Here’s the code:

class Zarc_Controller_Action extends Zend_Controller_Action
{
/**
* overload __get in order to easily retrieve values from the Registry
* and other sources. Throw an exception if the param could not be found.
*/
public function __get($param)
{
if($param == 'registry' || $param == 'r')
{
return new Zarc_Registry();
}
else
{
throw new Exception("Could not find property {$param}");
}
}
}

All of your controller classes should now extend the new controller class you just created. For example:

Class IndexController extends Zarc_Controller_Action

Next, you need to write a class that searches the Zend_Registry for the property that is being requested.

/**
* Applies an interface to the Zend_Registry that is cleaner and more
* accessible than doing it the verbose Zend Framework way.
*/
class Zarc_Registry
{
public function __get($param)
{
if(Zend_Registry::isRegistered($param))
{
return Zend_Registry::get($param);
}
else
{
throw new Zarc_Exception("Could not find property {$param}");
}
}
}

Then, save the two classes you created to your include path. Now, from your controller action methods you can access any variable stored in the Zend_Registry like this:

$this->registry->param
and this:
$this->r->param

This saves some time and makes your code much cleaner. You can also do this with sessions. Try it out, or ask us questions! If you need a deeper understanding leave us some comments and we’ll help you out.