Research Log of Web Science Students

Computer Science is not simply programming

Twitter4j Oauth + Spring: Class Twitter across multiple requests

leave a comment »

The way I use the Twitter class in Twitter4j, I have to instantiate a new Twitter class for every request I receive.

For example in a Spring Controller,

Twitter twitter = new Twitter();

that’s very trivial to wire but my problem is what happens next:

Twitter twitter = new Twitter();
twitter.setOauthConsumer("consumerKey",consumerSecret");

How on earth will I wire something like that in Spring?

I first tried out making a Twitter factory:

public class TwitterFactory {
	public String consumerKey;
	public String consumerSecret;
	public Twitter getInstance(){
		Twitter twitter = new Twitter();
		twitter.setOAuthConsumer(consumerKey,
                          consumerSecret);
		return twitter;
	}
	public void setConsumerKey(String consumerKey) {
		this.consumerKey = consumerKey;
	}
	public void setConsumerSecret(String consumerSecret) {
		this.consumerSecret = consumerSecret;
	}
}

and wired it up like this:

 <bean id="twitter-factory"
          class="com.hardwire.factories.TwitterFactory">
<property name="consumerKey">
		 <value>consumerKey</value>
           </property>
<property name="consumerSecret">
           	<value>consumerSecret</value>
           </property>
 </bean>

 <bean id="twitter"
          class="twitter4j.Twitter"
          factory-bean="twitter-factory"
          factory-method="getInstance"
          scope="prototype">
</bean>

<bean id="AuthController"=
         class="com.hardwire.controller.AuthController">
<property name="twitter" ref="twitter"/>
</bean>

The problem
Ok on my first login everything was okay. I was able to print my Twitter account’s description, screename and even retrive my picture using a url that links back to them.

But when I asked my friend to login to see if it works for him, he gets this error:

Uncaught exception from servlet
twitter4j.TwitterException: 401:Authentication credentials
             were missing or incorrect.
Failed to validate oauth signature and token

What works:
Having this code across all the controllers that need to access data from Twitter:

Twitter twitter = new Twitter();
twitter.setOauthConsumer("consumerKey",consumerSecret");

That’s bad if you ask me. I hope to find a workaround.

Advertisements

Written by Jose Asuncion

September 5, 2009 at 7:21 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: