Simple Spring Social for Twitter Friends

*** Updated 25-Nov-11 for Spring Social 1.0.0 Release ***

The Spring Social project provides us developers with an easy way to interact with Twitter, Facebook, LinkedIn & TripIt via the familiar Template objects we have used. Spring has provided Templates for convenient interaction with JDBC, REST, Hibernate, JNDI, and more.

One of the simplest social media calls is to lookup someone’s Twitter friends with the TwitterTemplate.



1. Add the Spring Social project dependency to the pom.xml file

<dependencies>
  <dependency>
    <groupId>org.springframework.social</groupId>
    <artifactId>spring-social-core</artifactId>
    <version>1.0.0.RELEASE</version>
  </dependency>
  ...
</dependencies>

2. Create the TwitterTemplate, and ask for friends

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.List;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class TwitterTests {
  private static final Logger logger =
    LoggerFactory.getLogger(TwitterTests.class);
  private static final String GDICKENS = "gdickens";
  private final TwitterTemplate twitterTemplate =
    new TwitterTemplate();

  @Rule
  public TestName name = new TestName();

  @Test
  public void testTwitterFriends() {
    logger.debug("Running '{}'...", name.getMethodName());

    List<TwitterProfile> friends =
      twitterTemplate.friendOperations().getFriends(GDICKENS);

    assertNotNull(friends);
    assertTrue(friends.size() > 0);

    logger.debug(GDICKENS + "'s friends:");
    for (TwitterProfile coolPerson : friends) {
      logger.debug("\t{}", coolPerson.getName());
    }
  }

  @Test
  public void testTwitterWithRestTemplate() {
    logger.debug("Running '{}'...", name.getMethodName());

    final RestTemplate restTemplate = new RestTemplate();
    String search = "#phillyete";
    String results = restTemplate.getForObject(
      "http://search.twitter.com/search.json?q={search}",
    String.class, search);
    assertNotNull(results);
    logger.debug("Search Results: {}", results);
  }

  @Test
  public void testTwitterTimeline() {
    logger.debug("Running '{}'...", name.getMethodName());
    List<Tweet> userTimeline =
      twitterTemplate.timelineOperations().getUserTimeline(GDICKENS);

    assertNotNull(userTimeline);
    assertTrue(userTimeline.size() > 0);
    logger.debug("Total Messages {}", userTimeline.size());

    for (Tweet tweet : userTimeline) {
      String date = (new SimpleDateFormat("M/d/yy hh:mm")).format(tweet
      .getCreatedAt());
      logger.debug("Tweet on {} - {}",
        new String[]{date, tweet.getText()});
    }
  }
}

3. Use the code above anywhere in your application

About Gordon

Technology enthusiast primarily focused on Java and Open Source projects. Spring Certified Professional and Trainer. http://twitter.com/gdickens http://linkedin.com/in/gordondickens http://github.com/gordonad
This entry was posted in JUnit, Spring, Spring Social, Testing, Twitter and tagged , , , . Bookmark the permalink.

8 Responses to Simple Spring Social for Twitter Friends

  1. Pingback: Tweets that mention Technophile Blog ยป Simple Spring Social for Twitter Friends -- Topsy.com

  2. eggsy84 says:

    Hi there,

    Quick question on this tutorial.

    When you make the call to the Twitter template to getFriend is this Synchronous.

    IE Executions holds until the friends of chariotsolution are fetched?

    eggsy

  3. admin says:

    It is a single threaded method execution.

  4. Rbonazzo says:

    Try to use
    twTemplate.getFriends(“user”)
    but he give the following error
    org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type and content type [application/json;charset=utf-8]
    Any help pls

  5. Rbonazzo says:

    Solved, only a problem of library included in my project sorry
    Regards
    Rinaldo

  6. admin says:

    No suiteable converter would happen if you have no JSON converter registered. If you include <mvc:annotation-driven/> and the JSON library in your project (
    <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.4.2</version>
    </dependency>

  7. Manish Jain says:

    I tried using the same thing, and got the Exception: Exception in thread “main” org.springframework.web.client.ResourceAccessException: I/O error: Connection reset; nested exception is java.net.SocketException: Connection reset
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:453)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:415)
    at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:213)
    at org.springframework.social.twitter.api.impl.FriendTemplate.getFollowerIdsInCursor(FriendTemplate.java:155)
    at org.springframework.social.twitter.api.impl.FriendTemplate.getFollowerIds(FriendTemplate.java:148)
    at logan.First.main(First.java:13)

    Any Ideas why connection might have been reset?

  8. Gordon says:

    Manish,

    Thanks for the feedback. Yes, I know I have to update this blog. The API changed between when I wrote this and the official release of Spring Social.

    Regards,
    Gordon Dickens

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>