Making Java Groovy: A Celebrity (Non-)Endorsement

Several of my book author friends on the No Fluff, Just Stuff tour told me that writing a book would open doors for me. That doesn’t explain, though, why I seem to insist on climbing through windows.

I mean, writing Making Java Groovy put me on the NFJS tour, helped me become a speaker at Gr8 conf, DevNexus, and JavaOne*, gave me lots of new professional contacts, and means my author page at Amazon has some actual content. Sweet. But I’m always wondering what else I can do with it that most authors are too experienced, too normal, or maybe just too sane to consider.

*My evals so far from my presentation at JavaOne have been really good, so I’m still hoping that I’m awarded JavaOne Rock Star status. I totally want to party like a JavaOne rock star, party like a JavaOne rock star, etc.

For example, there are certain people that I only know through Twitter or other online media who I would live to meet. As one of my Silly Marketing Ideas (abbreviated SMI, as opposed to my Serious Marketing Ideas, abbreviated SMI), I thought if I could get one or more of them to endorse my book, that would be seriously cool, not to mention whatever it did for sales.

Of course, the silly part is that most of the people I want to approach aren’t even developers, to say nothing of Java people. If you place all this in a larger context, I call this entire effort an “experiment in accidental celebrity”, meaning I want to achieve D-List Twitter Celebrity status, but only if I can do the whole thing as a gag and blog about it here.

To that end, a couple weeks ago I chose four of the people I would love to meet somehow and sent them individualized emails.

That’s a long shot, since I’m sure the people I contacted get flooded with emails on a regular basis. Still, I had to start somewhere, and it’s not like I have a budget for this or anything.

What I do have is a set of author copies for my book. I showed the set in my last blog post when I arranged them on the coffee table in our living room:
coffeetablebook

After giving away a few to friends and family, I decided that I could part with a few more if they acted as my introduction to unsuspecting victims I wanted to meet. If they ultimately decided they loved the book, or even just the joke itself, and wanted to endorse it, so much the better.

One of the people I contacted was a person I truly enjoy and admire, Wil Wheaton. If you lost track of him after Stand By Me and his classic role as the much-loathed-but-not-his-fault-he-was-stuck-with-those-lines Wesley Crusher from Star Trek: The Next Generation, then you’ve missed a lot (here’s his IMDB page). His blog is excellent. I read his Just a Geek book, which I really enjoyed, and his Memories of the Future, Volume 1 book is among the funniest I’ve ever read. My wife and I have also enjoyed his guest appearances on Eureka, Criminal Minds, Leverage, and, of course, The Big Bang Theory.

He’s also great on Twitter, under the handle @wilw. If you follow him, be sure to also follow his wife, @AnneWheaton. I often say that following Wil is fun and following Anne is fun, but following both together is wonderful.

As I said, I ultimately mustered up my courage (which meant suppressing the nauseous feeling that this was not only particularly silly, but actively embarrassing), dug up his email address, and sent him a message. To summarize the message, I:

  • explained who I was and that I had just published a book
  • mentioned I was a fan and personalized the evidence enough to prove I wasn’t kidding
  • explained that this was a Silly Marketing Idea which he was free to ignore but gave me a hopefully non-creepy opportunity to contact him directly
  • asked him for a mailing address so I could send him a signed copy of my book

I didn’t get anything back right away, but I didn’t really expect to. I imagine he is inundated with email, and I’m sure I was one of millions. I expected that I would have to resend it roughly once a week to see what would happen**.

**I got that idea from The Shawshank Redemption. Andy sent a request for money to the town council once a week for two years until they finally realized he wouldn’t go away and sent some money for his prison library. I’ve always wondered about that, by the way. Did he send the same letter, or did he rewrite it each time? Did he vary the wording or the basic content? How did he keep from letting his annoyance or anger at being ignored seep into the letter? Neither the movie nor the original Stephen King story get into details.

Then, however, fate took hold. On 10/17, Anne Wheaton tweeted:

Anne Witchon ‏@AnneWheaton 17 Oct
Texas tweety buddies! 10/17 Austin: bit.ly/WilPSAustin
10/18 Houston: bit.ly/WilPSHouston
10/20 Dallas: bit.ly/WilPSDallas”

I knew I was traveling to Dallas this week, but it suddenly occurred to me his show was on Sunday and I was flying in on the same day. I checked my flight arrangements and realized I could actually make the show. I quickly bought a ticket online (not many were left, but I only needed one), donned my Star Trek polo shirt (the blue science officer one I use when I’m making Groovy presentations about the Spock testing framework) and drove over to the Granada Theater.

I brought a book with me, of course, but I didn’t sign it because I wasn’t sure I actually was going to meet Wil. I’m not the sort of person who goes to conventions, or even events like this, so I don’t really know how they work. In fact, I almost didn’t go at all***, because I was very tired after the flights and didn’t particularly want to leave my hotel room after I arrived. I went anyway, of course, or this would be a much shorter blog post.

***I know my wife Ginger will be shocked, SHOCKED! to hear that.

The show was called Wil Wheaton vs Paul and Storm. Here’s the poster:

wilwheatonpaulandstorm_400

I have to admit that I didn’t know Paul and Storm at all, except from Wil or Anne’s tweets about them. I knew they were a musical / comedy duo who wrote their own funny songs, but that’s about it.

Here’s the marquee from the theater:
granadatheater

The show was a blast. Before the show, the theater used a Twitter site that showed all tweets directed to the theater. I don’t remember many, but among the funniest were things like:

– What does the FOX say? Sorry we canceled Firefly

– Told my blind date I was the guy with the beard wearing a funny T-shirt. Crap.

– [Paul of Paul and Storm] Hanging out with this girl who was supposed to meet some guy with a beard and a funny T-shirt. Playing it cool…

Wil introduced the show, saying that any and all recordings were allowed as long as they were released under the Creative Commons license (“and if you don’t know what that is, ask a nerd and he’ll explain it to you in far more detail than you ever wanted”), but not to use flash photography because that distracted the performers and not to do anything to interfere with other audience members.

“In short,” he said, using one of his signature catch phrases, “Don’t Be A Dick, and you’ll be fine”.

Paul and Storm did their set first, and it was fantastic. Intelligent people tend to be quite clever but not comedian-level funny****. Both Paul and Storm were both. I highly recommend that you check out their website, listen to their music, buy their stuff, and go see them if at all possible. They are masters of the “X is my Y cover band” style of joke. I’d mention some here, but I don’t want to include any spoilers and I can’t remember them anyway. I guess I’ll just have to go see them again.

****I often put myself in that category.

After the intermission, Wil came out and told personal stories in the form of a comedy monologue. There were great (and no spoilers here), but the biggest impression I get from him is I never realized, even reading his Twitter feed, just how filthy he is. Even in his 40s he still looks like this pleasant guy next door, and you don’t expect him to be quite so foul. It works, though. 🙂

Wil and Paul and Storm then came out together and did a few songs filled with random riffs that the audience loved. Here is a link to some pictures from the show.

Here’s a Vine video Paul posted.

Finally, here’s a screen capture from that video showing the audience, with a circle showing me:

audience_at_wilvps

During the entire show, I was holding my book, hoping that I’d get a chance to meet Wil and explain why I was foisting it on him. I also had idle daydreams of him letting me take a picture of him holding it and tweeting it to his 2.4 million followers (!), thinking if only 1% of them bought it…

After the show, a line quickly formed in the lobby. It turned out that the rules were that Wil and Paul and Storm would sign autographs for everybody who wanted one, but that if you wanted a posed picture you’d have to get in the back of the line again.

I didn’t have anything to sign, but the couple in front of me in line gave me a few blank cards from a game called The World of Munchkin, which now gives me a perfect opportunity to show the difference between Paul and Storm and Wil Wheaton. Here are my autographs from Paul and Storm:
paulandstorm

They’re basically illegible, sure, but I’m not one to talk. My signature is appalling. Anyway, here’s what Wil drew:
bagof
Yup. That’s the Wil Wheaton Experience right there.

While he was signing, I gave him my book. I told him I had just published it (“Hey, congratulations!” “Thanks!”), showed him where I had already signed it for him and Anne (“Cool!”), told him that I had sent him email if he was curious about me, and told him what a fan I was (yeah, I talked fast).

The rest of the conversation went something like this:

Wil: Will this help me learn this stuff if I don’t know anything about Java?

Me: Uh, some. Maybe. I’ll be happy to answer questions about it online if you like. That’s what I do. I teach technical training classes. I’ll come back around for a picture, but I was wondering if maybe I could get a picture with the book in it…

Wil: No, I can’t do that. That would be like an endorsement.

Me: (sound of internal imaginary bubble popping) I completely understand.

And I do understand. As I say, this is for fun, and if something else comes of it, fine, but if not, maybe I made an impression on him that the average fan doesn’t.

I did come back around for a picture. As we were setting up, I said:

Me: I meant to tell you that the front matter is pretty funny.

Wil: Great!

Me: Also, do you mind if I blog about this?

Wil: Of course!

Here’s my picture with my new buddies Paul and Storm and Wil and Anne Wheaton:
wilandanneandme
From left to right, that’s Storm, Anne, Me, Wil, and Paul. Or maybe Paul, Anne, Me, Wil, and Storm. (Just kidding. It’s the former. I think. Hey, I bought the USB drive with all their music on it, so I can make one joke at their expense.)

I have to say, I’m still basking in the afterglow. They show was fun, meeting them was fun, and getting the picture was even better. I’m really glad I gave him the book, too, though I have to point out that this does not in any way constitute an endorsement of Making Java Groovy (which is getting really great reviews at Amazon).

Yet. Now if I can only get him to read it…

(Upon re-reading this, it’s starting to sound a bit too mercenary. Look, all I want is my book to last a while, and maybe to make enough money that I can keep doing what I’m doing. It took me 40 years to find my dream job, and now that I have it I don’t want to give it up. Also, it’s kind of fun coming up with silly ideas like this, just to see if I can bring myself to actually do some of them. My next post will get back to technical issues, I promise.)

Making Java Groovy, the Listicle

[Note: I accidentally published this the first time before it was ready. It’s updated now.]

Unlike my previous posts about Making Java Groovy, this post concerns one of my Silly Marketing Ideas (SMI)*. The goal is to break out from the Groovy community and start selling to the larger Java community. Actually, I’m already doing that, so the real goal is to sell to developers in general. Of course, that’s not really enough. The real goal is to have my book become the first Java/Groovy integration book ever to make the New York Times Best Sellers list.

*Naturally, those are as opposed to my Serious Marketing Ideas (SMI).

That’s a somewhat ambitious goal, and to achieve it I’m going to have to appeal to the public at large, including people who have no interest whatsoever in a developer book. The goal of this particular post is to give people who never plan to write a line of code a reason to buy my book anyway.

That brings me to the listicle.

What is a listicle, you say? According to Google, which in this case means Wikipedia, a listicle is “a short form of writing using a list as its thematic structure, but is fleshed out with sufficient copy to be published as an article”. It also has some pretty serious negative connotations on the web, as they’re often displayed one item at a time in order to increase page views, which is basically evil.

This post won’t be like that. Or, rather, it does use a list as the thematic structure, but I’ll put the whole thing here and I’m not making any money from it no matter how it’s presented. In fact, this post was inspired by a tweet in my timeline:

Dan Woods (@danveloper)
“Groovy and Java are like Frodo and Samwise Gamgee, [headed into Mordor] … trying to defeat … clueless managers …” – @kenkousen lol
10/10/13 3:44 PM

(See https://twitter.com/danveloper/status/388389569189539840 for the full version.)

That’s an extract from the preface to my book. At some point I’ll post the whole preface here, but for the record, the full version of that quote is:

Groovy and Java are like Frodo and Samwise Gamgee, headed into the black depths of Mordor, battling privation and despair, desperately trying to defeat the horrible programming challenges that await them, as well as any orcs, Nazgul, or clueless managers they might encounter along the way.

That’s a little dark. Plus, I have no idea what the Ring of Power is in this analogy, or why you’d want to destroy it*.

*I do hope that if you’re holding a print copy of the book (that is, dead-treeware), no Ents were involved.

To segue into the actual purpose of this post, later in the front matter there is a section called “about this book”, and in it I say that, “I expect you are a developer and are at least comfortable with Java”. This is followed by an extensive footnote where I claim that you don’t really need to be a developer, since there are many reasons to buy my book that don’t involve actually reading it.

At long last, that brings me to the listicle that is the real subject of this post. In case you’re already thinking about what to buy your mom for the holidays, let me present:

The Top Ten Ways To Take Advantage Of Making Java Groovy
That Don’t Involve Actually Reading It

10. Prop open a door (a classic)

doorstop

That’s not a great picture of propping open a door, but hopefully it worked for you.

9. Level a table

propuptable

Note especially the use of a coaster to keep from damaging the book cover.

8. Shield against assorted non-lethal weaponry

shield

This is my son Xander’s first appearance in my blog, and note that he managed to stay hidden. The nerf weapon is visible, though.

7. Looks good on your bookshelf

bookshelf

I don’t collect print books like I used to. Most of my books are ebooks these days. Still, I was able to fill out the shelf with as many Groovy-related books as I could find, some of which are getting rather dated. I have the updated books, they’re not in print yet. If you’re in the Groovy community, how many can you identify?

6. Excellent coffee table book

coffeetablebook

This involved actually clearing off the coffee table in the living room, which made my wife Ginger happy.

5. Ugly bug / insect / big, hairy arachnid pulverizer

I’ve never taken a Vine video before. This is my first attempt, which I downloaded as an mp4 file. Hopefully it’s visible.

4. Make a book fort

bookfort

I got Xander to build the fort around a black cat we have on display for Halloween.

3. Learn balance by walking with it on your head

Remember when that used to be a thing? Neither do I, never having been to a “finishing” school, but it made for a decent video.

2. Fan yourself by riffling through the pages

To be honest, Ginger said it was better to just wave the book at herself than breeze through the pages, but so be it.

1. Impress your parents

This one requires some explanation. As the parent of a young adult (and as the child of high-achieving parents), I understand that parents are sometimes more concerned with your financial future than you are. You and I are often more interested in what we’re doing than whether it’s for a productive future.

The point is, sometimes we need a way to convince our parents that we’re making progress, thereby getting the time and space we need to do what we have to do. I’d like to believe my book can help you do that. My resume has always opened doors for me, and if somehow you can take advantage of it, so much the better. So use my book as a way to convince whoever needs convincing that you’re moving into a bold, new, financially lucrative area, whether you really are or not.

Besides, the footnotes are still pretty funny. 🙂

Carlos Ray and Spring’s RestTemplate

Normally I prefer causing trouble to getting in trouble, but this time the temptation is just too great.

In my last blog post, I described how I made an Android app that was a front-end on the ICNDB web site, the Internet Chuck Norris Database, only to receive a take-down email from Patton Boggs, LLP, the attorneys for Carlos Ray “Chuck” Norris. Since all I was doing was consuming JSON data from a public web site and not charging anything, I ignored the notice, only to have Google Play suspend my app shortly thereafter.

Normally my response to that would be to just let it go. I really don’t like getting into trouble. I checked out Mr. Norris on Wikipedia, however, and discovered:

  • The star of Lone Wolf McQuade is actually 73 years old (though I have no doubt he could still kick my a**).
  • He is supposedly worth $70 million dollars, making it hard for me to imagine that my little free app (which again is only consuming publicly-available data) “severely harms [him] and jeopardizes his existing business relationships”.

So, despite the fact that he’s fabulously wealthy and that he’s still a martial arts master, both of which mean he could swat me like a fly without even trying, I couldn’t resist rising to the challenge.

If you search the Google Play store for the words “Carlos Ray”, you will find an app called Internet Carlos Ray DB. I know it has at least four installs, because at the last No Fluff, Just Stuff event in Minneapolis, I installed it on two devices and a friend I was hanging out with at the hotel bar also installed it on two devices. The app also has a five-star rating, which I added myself.

You’ll also see that I even added the lawyer’s names to the main icon:
ICRDB
Talk about waving a red flag in front of a bull. When I inevitably get gored, I’ll be sure to blog about it.

When you create an Android app, you have to select a package name for it, and that name has to be unique among all the apps you deploy to Google Play. If you check out the code in my GitHub repository, you’ll see that on the “carlosray” branch I changed the package to com.kousenit.icrdb (ICRDB == Internet Carlos Ray Database, of course).

In order to discuss something technical that might actually be useful to any readers, let me address how I retrieved the JSON data and parsed it. The Android API has both some enhanced HTTP classes (similar to those from regular Java’s java.net package) and a version of Apache’s HTTP Client package. In addition, the API includes an org.json package for working with JSON data. It includes classes like JSONArray, JSONObject, and JSONTokenizer.

All of the above provide a reasonable way to download and parse JSON data, but I have a different recommendation.

From its name, the Spring Android project sounds like a way to embed a Spring container inside an Android app. While that’s actually a rather appealing idea, that’s not what the project contains. If you look at the reference guide, you’ll see the project includes an authorization module, which I didn’t need, and a REST template, which rocks.

The best part is that if you include the Jackson JSON parser jar files in your application, the REST template will automatically convert JSON data to classes and back.

Using it is easy. It’s easier, in fact, to show the code than to explain it first, so here are some snippets from my main activity class:

public class MainActivity extends Activity {
    private Button jokeButton;
    private TextView jokeView;

    // "true" ctor arg --> add default message converters
    private RestTemplate template = new RestTemplate(true);

    private static final String URL = 
       "http://api.icndb.com/jokes/random?limitTo=[nerdy]" +
               "&firstName=Carlos&lastName=Ray";
// ...
}

I have a button to get the next joke and I have a label (which for some odd reason Android calls a TextView) to display it. I also added the RestTemplate as an attribute of the class. By instantiating it with the constructor arg “true“, it loads the default message converters.

(Those are the same message converters that Spring MVC uses for its RequestBody and ResponseBody processing, by the way, which is how I learned about them.)

The URL points to the ICNDB web site, and I’ve limited the jokes to just the nerdy ones and changed the first and last name of the hero to Carlos Ray, as you can see.

Here’s my onCreate method, which looks up the GUI elements and sets the on-click listener for the button:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    jokeView = (TextView) findViewById(R.id.text_view);
    jokeButton = (Button) findViewById(R.id.icndb_button);
    jokeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JokeTask().execute();
        }
    });
}

Downloading a joke goes over the network, which is not something you want to do on the UI thread. The recommended way to handle that is to create a subclass of android.os.AsyncTask, which contains methods to do the work and update the UI when it’s finished. My JokeTask is just such a class:

private class JokeTask extends AsyncTask<Void, Void, String> {
    @Override
    protected String doInBackground(Void... params) {
        IcndbJoke joke = template.getForObject(URL, IcndbJoke.class);
        return joke.getJoke();
    }
        
    @Override
    protected void onPostExecute(String result) {
        jokeView.setText(result);
    }
}

The three generic parameters on AsyncTask represent the parameters to the doInBackground method, the progress data type (which I’m not using here), and the return type on doInBackground, which is also the argument to the onPostExecute method. Work done inside doInBackground is automatically off the UI thread, and then code in onPostExecute is back on the UI thread.

The cool part is the template.getForObject method. It takes a String representing the URL and a class to populate with the result. If the JSON structure matches the class attributes, the conversion is done automatically. Therefore, all I need to do is to supply the IcndbJoke class.

According to the ICNDB site, the JSON structure is:

{ "type": "success", "value": { "id": 268, "joke": "Time waits for no man. Unless that man is Chuck Norris." } }

With that in mind, here’s my IcndbJoke class:

package com.kousenit.icrdb;

@SuppressWarnings("unused")
public class IcndbJoke {
    private String type;
    private Joke value;

    // helper method to extract the joke string from inner class    
    public String getJoke() {
        return value.getJoke();
    }
    
    public String getType() { return type;}
    public void setType(String type) { this.type = type; }
    
    public Joke getValue() { return value; }
    public void setValue(Joke value) { this.value = value; }
    
    private static class Joke {
        private int id;
        private String joke;
        private String[] categories;
        
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }

        public String getJoke() { return joke; }
        public void setJoke(String joke) { this.joke = joke; }
        
        public String[] getCategories() { return categories; }
        public void setCategories(String[] categories) { this.categories = categories; }
    }
}

Other than the extra helper method used to make it easier to grab the joke string directly, this is a straight map from the JSON structure to nested classes with getters and setters.

(Oh how I wish I could use Groovy here. I could cut all this down by about 80%. Sigh.)

That’s the whole story. The getForObject method on the RestTemplate accesses the web site, downloads the JSON data, and converts it to an instance of my IcndbJoke class. Then I extract the joke string from it and update the GUI.

The only complication was that for a long time the ICNDB web site didn’t properly set the Content-Type header in the response. The RestTemplate only uses the JSON parser if the Content-Type header is set to application/json. By default the web site returned text/html, so for a time I had to convert that to a String instead of my joke class. Then I used Google’s GSON parser to convert that to my IcndbJoke class and went from there. Now that the web site sets the Content-Type header correctly, I’m able to simplify the code again. Feel free to grab it if you like.

If you like the RestTemplate, be sure to check out the documentation here and the javadocs for it here. I had to add the relevant jar files to the project, but that’s all I needed in order to use it.

Eventually I plan to migrate the whole thing over to use the Gradle plugin for Android, but that’s a post for another day.

Before I finish this post, I should mention that Making Java Groovy now has two reviews at Amazon.com. Better yet, both reviewers clearly understood what the book was trying to accomplish and they both liked it. Based on my sales so far, the Amazon sales rank has reached as high as #62,521, though I’m now back down to #131,928. (Not that I’m obsessing over the numbers or anything.) Of course, Amazon doesn’t count ebooks, nor does it report on sales from the Manning web site, which is where you have to go if you want to use one of coupon codes they periodically make available.

Though I don’t have anything Groovy-related to say this week myself, I want to mention that Bobby Warner has recorded another one of his excellent Grails videos. The subject this time is the REST improvements that come with Grails 2.3, and I highly recommend it.

On a personal note, I have to say that I’m enjoying these weekly blog posts, though now I have to stop and get some REST.

(Ha! Thought I was going to make it through without one REST joke, did you? Not a chance.)

Making Java Groovy: ratpack, MongoDB, and Chuck Norris

Before I get to the good parts of this post (the technical content), let me take care of a few marketing issues.

First, as I mentioned in my last post, I gave my “Making Java Groovy” presentation at JavaOne last week. If you were there and you haven’t completed your Session Surveys, please do so. I really want to Party Like a (JavaOne) Rock Star, Party Like a (JavaOne) Rock Star, etc., though I expect in reality that would involve sharing a quiet dinner at home with my wife. She probably wouldn’t appreciate it if I trashed the room, too, at least not more than it’s already trashed*.

*Yeah, my 21 year old son still does live at home, why do you ask?

That did give me the opportunity to see my book on the shelf of a book store for the first time:

book_shelf_photo

I should also mention that as of 9/30, if you buy the book at Manning, you can now get all the electronic formats (pdf, mobi, and epub).

Finally, I got my first Amazon review today, and was so good I walked around with a smile all day.

Now on to the real content. In my Groovy presentations, I often like to access a RESTful web service and show (1) how easy it is to make a GET request using Groovy, and (2) how to use a JsonSlurper to parse a JSON response to get the information inside it. For this purpose my default site is ICNDB, the Internet Chuck Norris Database.

That site has caused me problems, though. First, it resulted in my first ever take down notice from a lawyer, which I’ll show in a moment. Seriously. As part of my Android presentations at No Fluff, Just Stuff conferences I build a simple app to access that site, parse the results (using a GSON parser, since I don’t have Groovy available) and update the display. When running, the app looks like:

icndb_emulator_image

To make it easy for the attendees of my Android talks to play with, I uploaded the app to the Google Play store. That was fun until I received the following email, from an address I’ll leave out:

Dear Sir/Madam:

Patton Boggs LLP represents Carlos Ray Norris, aka Chuck Norris, the famous actor and celebrity.

We are contacting you because we recently learned that you have developed and are distributing a software application that uses Mr. Norris’s name and/or image without authorization on Google Play.

Mr. Norris appreciates all of his fans. However, the unauthorized use of his name and/or image severely harms my client and jeopardizes his existing business relationships.

Mr. Norris owns legal rights in his name and image which includes copyright, trademark, and publicity rights (the “Norris Properties”). He uses the Norris Properties regularly in his own business endeavors. Therefore we have asked Google to remove your application from Google Play because it violates Mr. Norris’s intellectual property rights.

We request that you (1) immediately stop developing and distributing “Chuck Norris” applications; (2) remove all “Chuck Norris” applications that you have developed or control from all websites under your control; and (3) do not use Mr. Norris’s name or image, or any cartoon or caricature version of Mr. Norris’s name or image for any endeavor, including in connection with software applications, without Mr. Norris’s permission.

Thank you for honoring Mr. Norris’s legal rights. Please contact me if you have questions.

Sincerely, …

A few points immediately come to mind:

  • Carlos Ray Norris? Seriously? I had no idea.
  • Does it matter that my app is free and only consumes data from a publicly available web site? Apparently not.
  • If I changed the icon and replaced the words “Chuck” and “Norris” everywhere with the words “Patton” and “Boggs” (the name of the law firm :)), could I upload it again?

I’m still not exactly sure what I was doing wrong, but of course I did not want to cross Carlos Ray “Chuck” Norris, to say nothing of his lawyers. But after talking to a few people, I decided to ignore the letter, at least until any money was involved.

I haven’t heard anything since, but about a week later Google Play took down my app.

So be it. If you want the source code, though, check out the ICNDB project in my GitHub repository. It’s mostly just a demonstration of how to Spring’s RestTemplate, Google’s GSON parser, and an Android AsyncTask together. In the repo is another branch that uses a Java Timer to refresh the joke every 10 seconds.

The real question is, why haven’t the barracudas lawyers gone after the original ICNDB site? Worse, what happens to my poor app (and, more importantly, my presentation) when they do?

I decided my best course of action was to download as many of the jokes as possible and be ready to serve them up locally in case I need them. That, at long last, brings me to the technical part of this blog post.

The original web site returns jokes in JSON format. That means storing them in a MongoDB database is trivial, because Mongo’s native format is BSON (binary JSON) and I can even query on the joke properties later.

How do I grab all the jokes? There’s no obvious query in the API for that, but there is a work around. If I first access http://api.icndb.com/jokes/count, I can get the total number of jokes. Then there is a URL called http://api.icndb.com/jokes/random/:num, which fetches num random jokes. According to the web site, it returns them in the form:

{ "type": "success", "value": [ { "id": 1, "joke": "Joke 1" }, { "id": 5, "joke": "Joke 5" }, { "id": 9, "joke": "Joke 9" } ] }

The value property is a list containing all the individual jokes.

To work with MongoDB, I’ll use the driver from the GMongo project. It follows the typical Groovy idiom, in that it takes an existing Java API (in this case, the ugly and awkward Java driver for Mongo) and wraps it in a much simpler Groovy API. As a beautiful illustration of the process, here’s an excerpt from the com.gmongo.GMongo class:

class GMongo {

  @Delegate
  Mongo mongo

  // ... lots of overloaded constructors ...

  DB getDB(String name) {
    patchAndReturn mongo.getDB(name)
  }

  static private patchAndReturn(db) {
    DBPatcher.patch(db); return db
  }
}

Note the use of the @Delegate annotation, which exposes all the methods on the existing Java-based Mongo class through the GMongo wrapper.

Based on that, here’s my script to download all the jokes and store them in a local MongoDB database:

import groovy.json.*
import com.gmongo.GMongo

GMongo mongo = new GMongo()
def db = mongo.getDB('icndb')
db.cnjokes.drop()

String jsonTxt = 'http://api.icndb.com/jokes/count'.toURL().text
def json = new JsonSlurper().parseText(jsonTxt)
int total = json.value.toInteger()

jsonTxt = "http://api.icndb.com/jokes/random/${total}".toURL().text
json = new JsonSlurper().parseText(jsonTxt)
def jokes = json.value
jokes.each {
    db.cnjokes << it
}
println db.cnjokes.find().count()

Note the nice overloaded left-shift operator to add each joke to the collection.

I’ve run this script several times and I consistently get 546 total jokes. That means the entire collection easily fits in memory, a fact I take advantage of when serving them up myself.

My client needs to request a random joke from the server. I want to do this in a public forum, so I’m not interested in any off-color jokes. Also, the ICNDB server itself offers a nice option that I want to duplicate. If you specify a firstName or lastName property on the URL, the joke will replace the words “Chuck” and “Norris” with what you specify. I like this because, well, the more I find out about Carlos Ray the more I wish I didn’t know.

Here’s my resulting JokeServer class:

package com.kousenit

import java.security.SecureRandom
import com.gmongo.GMongo
import com.mongodb.DB

@Singleton
class JokeServer {
    GMongo mongo = new GMongo()
    Map jokes = [:]
    List ids = []
    
    JokeServer() {
        DB db = mongo.getDB('icndb')
        def jokesInDB = db.cnjokes.find([categories: [$ne : 'explicit']])
        jokesInDB.each { j ->
            jokes[j.id] = j.joke
        }
        ids = jokes.keySet() as List
    }
    
    String getJoke(String firstName = 'Chuck', String lastName = 'Norris') {
        Collections.shuffle(ids)
        String joke = jokes[ids[0]]
        if (!joke) println "Null joke at id=$id"
        if (firstName != 'Chuck')
            joke = joke.replaceAll(/Chuck/, firstName)
        if (lastName != 'Norris')
            joke = joke.replaceAll(/Norris/, lastName)
        return joke
    }
}

MongoDB has a JavaScript API which uses qualifiers like $ne for “not equals”. The Groovy API wrapper lets me add those as keys in a map supplied to the find method.

I added the @Singleton annotation on the class, though that may be neither necessary or appropriate. I may want multiple instances of this class for scaling purposes. I’ll have to think about that. Let me know if you have an opinion.

I’m sure there’s an easier way to get a random joke out of the collection, but I kept running into issues when I tried using random integers. This way works, though it’s kind of ugly.

The getJoke method uses Groovy’s cool optional arguments capability. If getJoke is invoked with no arguments, I’ll use the original version. If firstName and/or lastName are specified, I use the replaceAll method from the Groovy JDK to change the value in the joke. Strings are still immutable, though, so the replaceAll method returns a new object and I have to reuse my joke reference to point to it. I actually missed that the first time (sigh), but that’s what test cases are for.

Speaking of which, here’s the JUnit test (written in Groovy) to verify the JokeServer is working properly:

package com.kousenit

import static org.junit.Assert.*

import org.junit.Before
import org.junit.Test

class JokeServerTest {
    JokeServer server = JokeServer.instance

    @Test
    public void testGetJokeFirstNameLastName() {
        String joke = server.getJoke('Patton', 'Boggs')
        assert !joke.contains('Chuck')
        assert !joke.contains('Norris')
        assert joke.contains('Patton')
        assert joke.contains('Boggs')
    }

    @Test
    public void testGetJoke() {
        assert server.joke
    }
}

I can invoke the getJoke method with zero, one, or two arguments. The basic testGetJoke method uses zero arguments. Or, rather, it accesses the joke property, which then calls getJoke() using the usual Groovy idiom.

Now I need to use this class inside a web server, and that gave me a chance to dig into the ratpack project. Ratpack is a Groovy project and I’ve checked out the source code from GitHub, but there’s a simpler way to create a new ratpack application based on the Groovy enVironment Manager (gvm) tool.

First I used gvm to install lazybones:

> gvm install lazybones

Then I created my ratpack project:

> lazybones create ratpack icndb

That creates a simple structure (shown in the ratpack manual) with a Gradle build file. The only modification I made to build.gradle was to add “compile 'com.gmongo:gmongo:1.0'” to the dependencies block.

Here’s the file ratpack.groovy, the script that configures the server:

import static org.ratpackframework.groovy.RatpackScript.ratpack

import com.kousenit.JokeServer

JokeServer server = JokeServer.instance

ratpack {
    handlers {
        get {
            String message
            if(request.queryParams.firstName || request.queryParams.lastName) {
                message = server.getJoke(
                    request.queryParams.firstName, 
                    request.queryParams.lastName)
            } else {
                message = server.joke
            }
            response.headers.set 'Content-Type', 'application/json'
            response.send message
        }
    }
}

I configured only a single “get” handler, which is invoked on an HTTP GET request. I check to see if either a firstName or lastName query parameter is supplied, and, if so, I invoke the full getJoke method. Otherwise I just access the joke property. I made sure to set the Content-Type header in the response to indicate I was returning JSON data, and sent the message.

If I type ./gradlew run from the command line, ratpack starts up its embedded Netty server on port 5050 and serves jokes on demand. Here’s a picture of the default request and response (using the Postman plugin in Chrome):

postman_icndb_default

Here is the response if I specify a first and last name:

postman_patton_boggs

There you have it. I wanted to write a test inside ratpack to check my hander, but the infrastructure for that appears to still be under development. I tried to imitate one of the samples and extend the ScriptAppSpec class, but that class isn’t in my dependent jars. I also tried to follow the Rob Fletcher’s mid-century ipsum example, but while I was able to create the test, it failed when running because it couldn’t find the ratpack.groovy file inside the ratpack folder, since it expected it to be in the root. The right approach would probably be to turn the contents of my get block into a separate Handler, because the manual talks about how to test them, but I haven’t done that yet.

As they say, if you live on the cutting edge, sometimes you get cut. I expect that will all settle down by 1.0.

For my presentations, I now need to update my Android client so that it accesses http://localhost:5050 and understands that the JSON coming back is a bit simpler than that served up by the original server. That’s beyond the scope of this (way too long) blog post, however.

I haven’t yet committed the application to GitHub, but I will eventually. In the meantime I just have to hope that my new app also doesn’t run afoul of Carlos, Ray, Patton, and Boggs, Esq.

%d bloggers like this: