DropWizard to Twitter

A quick example of creating a DropWizard service to post to Twitter.

You’ll need to register a new app with Twitter, and note down the API keys so it works with your account (instructions provided if you’ve never done this).


I’m using my basic DropWizard service as a starting point, and renaming all the files to something appropriate.

You’ll have to register a new app with Twitter.
New Twitter App - Initial Details

You should then click the “Create your Twitter application” button to take you to the overview screen.
Twitter App Overview

On the Permissions tab, change to “Read and Write”, then click the “Update Settings” button.

Changing the App Permissions

On the “API Keys” tab, click the “Create my access token” button (you may need to refresh a few times for the access token values to appear). You’ll want to note down:-

  • API key (this is the Consumer Key)
  • API secret (this is the Consumer Secret)
  • Access token (this is the Access Token)
  • Access token secret (this is the Access Token Secret)

Getting the App's API keys

We’ll use the Twitter4J library, by adding it into our pom.xml.

            org.twitter4j
            twitter4j-core
            [4.0,)

I’m going to use environment variables for the API keys, but you can’t have key names with dots in it, so I mangle the 4 key names plus the debug flag so I can use them:-

    @POST
    @Timed
    public Response tweetMessage(@QueryParam("tweet") String tweet) {
        Response result = new Response();
        result.setGuid(UUID.randomUUID().toString());
        result.setSuccess(Boolean.FALSE);
 
        // Can't export environment variables with dots in the key, so name munging happens here
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(Boolean.parseBoolean(System.getenv("twitter4j_debug")))
                .setOAuthConsumerKey(System.getenv("twitter4j_oauth_consumerKey"))
                .setOAuthConsumerSecret(System.getenv("twitter4j_oauth_consumerSecret"))
                .setOAuthAccessToken(System.getenv("twitter4j_oauth_accessToken"))
                .setOAuthAccessTokenSecret(System.getenv("twitter4j_oauth_accessTokenSecret"));
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
 
        try {
            Status status = twitter.updateStatus(tweet);
            result.setMessage("Successfully updated the status to [" + status.getText() + "].");
            result.setSuccess(Boolean.TRUE);
        } catch (TwitterException e) {
            result.setMessage(e.getMessage());
            result.setSuccess(Boolean.FALSE);
        }
        return result;
    }

// Can’t export environment variables with dots in the key, so name munging happens here
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(Boolean.parseBoolean(System.getenv("twitter4j_debug")))
.setOAuthConsumerKey(System.getenv("twitter4j_oauth_consumerKey"))
.setOAuthConsumerSecret(System.getenv("twitter4j_oauth_consumerSecret"))
.setOAuthAccessToken(System.getenv("twitter4j_oauth_accessToken"))
.setOAuthAccessTokenSecret(System.getenv("twitter4j_oauth_accessTokenSecret"));
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();

try {
Status status = twitter.updateStatus(tweet);
result.setMessage("Successfully updated the status to [" + status.getText() + "].");
result.setSuccess(Boolean.TRUE);
} catch (TwitterException e) {
result.setMessage(e.getMessage());
result.setSuccess(Boolean.FALSE);
}
return result;
}

The Response object contains a success flag, a GUID (so subsequent calls can be identified), and a message.

The full project can be downloaded from GitHub.

Unzip the source code, change into that directory and run

mvn clean package

which builds a single executable fat jar.

To run it, you need to export the API keys which you noted above.

export twitter4j_debug=true
export twitter4j_oauth_consumerKey=your_consumer_key
export twitter4j_oauth_consumerSecret=your_consumer_secret
export twitter4j_oauth_accessToken=your_access_token
export twitter4j_oauth_accessTokenSecret=your_access_token_secret
 
java -jar target/SimpleDropWizardTwitter-1.0.1-SNAPSHOT.jar server

java -jar target/SimpleDropWizardTwitter-1.0.1-SNAPSHOT.jar server

In another terminal, you can test this via CURL with

curl -X POST http://localhost:8080/tweet?tweet=Test%20123

(note that you’ll have to URL-encode the tweet message (eg replace spaces with %20, etc). You should then see the tweet appear in your timeline.

This is my personal blog - all views are my own.

Tagged with: , ,