Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 117 ]

Reading raw JSON tweets is obviously not user friendly. Fortunately, thanks to the
vibrant developer community that has sprung up around Twitter APIs, there are
high-level client libraries for most languages, including Java, C++, PHP, and Ruby.
There are three Java-based client libraries to be found—Twitter4J, JTwitter, and
java-twitter. So far, there is no Groovy library listed, but because Groovy is fully
Java compatible, we can work with any of the Java libraries.


Using Twitter4J Java APIs


In the following examples, we will use Twitter4J by Yusuke Yamamoto. Twitter4J
is an excellent open source Java library for Twitter APIs, released under the BSD
license. Using Twitter4J greatly simplifies the code that we need to write in order
to build a simple DSL scripting interface for Twitter. Twitter4J can be downloaded
from http://yusuke.homeip.net/twitter4j/en/index.html. However, we
will simply add the twitter4j dependency to build.gradle in the code in the
example pack:


dependencies {
compile "org.twitter4j:twitter4j-core:4.0.2"
}

To begin with, let's try out the Twitter4J APIs and see what we can do with them.
Although Twitter4J is a Java API, all of the examples here will run as Groovy scripts.
If we were to write the same code as Java, we would need to build the examples
into full-blown classes with the main methods before we could see any results.
With Groovy, we can be up and running almost immediately.


In the following examples, we will use Groovy scripts. These scripts can be run from
the command line as follows:


$ groovy Script.groovy


We will use the @Grab annotation to resolve the Twitter 4J dependency in these
scripts. Each script therefore needs to begin with @Grab, but we will omit this in
the text for terseness sake:


@Grab(group='org.twitter4j', module='twitter4j-core',
version='[4.0,)')
import twitter4j.*

Our examples dip into Groovy features at times, but we could simply cut and paste
the sample code from the Twitter4J site and run it unchanged. Used in this way,
Groovy can be a sandbox for exploring the Twitter4J APIs even without writing any
Groovy code.

Free download pdf