Java Tweet Class

package StatTrader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.*;

/**
 *
 * @author grahamgiller
 * @website http://blog.gillerinvestments.com
 */
public class Tweet {

    // you will need to go to http://dev.twitter.com, login, and register an app to get a consumer key and secret pair
    private String _consumerKey = ""; // store your app's consumer key here
    private String _consumerSecret = ""; // store the consumer secret here
    
    // if you have a default account you want to use then put the token key and secret associated with the account and app here
    private String _tokenKey="";
    private String _tokenSecret="";

    // object storage
    protected AccessToken _token;
    protected Twitter _twitter;
    protected TwitterFactory _factory;
    
    // call this constructor if you have set default consumer and default token key and secret pairs
    public Tweet() throws Exception {
        
        _token = new AccessToken(_tokenKey,_tokenSecret);
        _factory = new TwitterFactory();
        _twitter = _factory.getInstance();
        _twitter.setOAuthConsumer(_consumerKey,_consumerSecret);
        _twitter.setOAuthAccessToken(_token);        
    }
    
    // call this constructor if you have a default consumer but different token key and secret pairs
    public Tweet(final String tokenKey_,final String tokenSecret_) throws Exception {
        
        _token = new AccessToken(tokenKey_,tokenSecret_);
        _factory = new TwitterFactory();
        _twitter = _factory.getInstance();
        _twitter.setOAuthConsumer(_consumerKey,_consumerSecret);
        _twitter.setOAuthAccessToken(_token);        
    }
        
    // call this constructure if you want to specify everything yourself
    public Tweet(final String consumerKey_,final String consumerSecret_,final String tokenKey_,final String tokenSecret_) throws Exception {
        
        _token = new AccessToken(tokenKey_,tokenSecret_);
        _factory = new TwitterFactory();
        _twitter = _factory.getInstance();
        _twitter.setOAuthConsumer(consumerKey_,consumerSecret_);
        _twitter.setOAuthAccessToken(_token);        
    }

    // this method sends the tweet
    public Long Update(final String tweet_) throws Exception {
        
        long _started=System.nanoTime();
        _twitter.updateStatus(tweet_);        
        return System.nanoTime()-_started;
    }
    
    // this static method is used to generate an access token via out-of-band authentication with twitter
    // you need to supply your consumer key and consumer secret and then go to twitter.com to obtain
    // a pin number used to generate an associated token key and token secret
    // you should then serialize the token keys for later re-use i.e. you only need to do this once per twitter account used
    static public AccessToken Generate(final String consumerKey_,final String consumerSecret_) throws Exception {

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(consumerKey_,consumerSecret_);
        AccessToken at = null; 
        RequestToken rt = twitter.getOAuthRequestToken();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (at==null) {

            System.out.println("\nOpen the following URL and grant access to your account: "+rt.getAuthorizationURL());
            System.out.print("Enter the PIN returned by twitter: ");
            String pin = br.readLine();

            try {

                if (pin.length()>0) {

                    at = twitter.getOAuthAccessToken(rt,pin);

                }
                else {

                    at = twitter.getOAuthAccessToken();
                }
            } 
            catch (TwitterException te) {

                if (te.getStatusCode()==401) {

                    System.err.println("Error: unable to get the access token.");
                }
                else {

                    te.printStackTrace();
                }
            }
        }
        
        return at;
    }
}


Bookmark and Share

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant



RecentComments

Comment RSS

About the Author

Graham Giller - Headshot GRAHAM GILLER
Dr. Giller holds a doctorate from Oxford University in experimental elementary particle physics. His field of research was statistical astronomy using high energy cosmic rays. After leaving Oxford, he worked in the Process Driven Trading Group at Morgan Stanley, as a strategy researcher and portfolio manager. He then ran a CTA/CPO firm which concentrated on trading eurodollar futures using statistical models. From 2004, he has managed a private family investment office. In 2009, he joined a California based hedge fund startup, concentrating on high frequency alpha and volatility forecasting. My updated resume is on LinkedIn.

Pages


Disclaimer

Nothing on this site should be construed as a reccommendation to buy or sell any specific security nor as a solicitation of an order to buy or sell any specific security. Before making any trade for any reason you should consult your own financial advisor. The author may hold long or short positions in any of the securities discussed either before or after publication of an article mentioning such a security.

Copyright Notice

All post on this blog are © Copyright property of Giller Investments (New Jersey), LLC. All comments are the property of their respective authors and neither the author or this blog nor any entity associated with him are responsible for or accept any responsibility for their content. Offensive comments and spam may be removed at the authors discretion.

Data provided on this blog or through links to this blog are either property of Giller Investments (New Jersey), LLC or publicly available or derived from data that is publically available. Any data that is proprietary to Giller Investments (New Jersey), LLC is published here for the public interest and may be reproduced for private research or in public forums provided that suitable attribution and acknowledgement of ownership is made.

Privacy Policy

We use third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.