Example usage for twitter4j TwitterFactory getInstance

List of usage examples for twitter4j TwitterFactory getInstance

Introduction

In this page you can find the example usage for twitter4j TwitterFactory getInstance.

Prototype

public Twitter getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:crawltweets2mongo.CrawlTweets2Mongo.java

public static void getTweetByQuery(boolean loadRecords, String keyword) {

    if (collection != null) {
        final String api_key = "your api key in here";
        final String api_secret = "applied it from twitter website";
        final String access_token = "applied token from twitter website";
        final String access_token_secret = "applied it from twitter website";
        // The factory instance is re-useable and thread safe.
        if (twitter == null) {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(false).setOAuthConsumerKey(api_key).setOAuthConsumerSecret(api_secret)
                    .setOAuthAccessToken(access_token).setOAuthAccessTokenSecret(access_token_secret);
            TwitterFactory tf = new TwitterFactory(cb.build());
            twitter = tf.getInstance();
        }//from  w w  w.ja v  a  2  s .  c  om

        threadMessage("Starting MessageLoop thread");
        long startTime = System.currentTimeMillis();
        Thread t = new Thread(new MonoThread(collection, twitter));
        t.start();
        threadMessage("Waiting for MessageLoop thread to finish");
        // loop until MessageLoop           // thread exits
        while (t.isAlive()) {
            try {
                t.join(28000);

                t.join(28000);

                t.join(28000);
                if (((System.currentTimeMillis() - startTime) > 1000 * 60 * 60) // long patience = 1000 * 60 * 60;
                        && t.isAlive()) {
                    threadMessage("Tired of waiting!");
                    t.interrupt();
                    t.join();
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(CrawlTweets2Mongo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        threadMessage("Finally!");
    } else {
        System.out.println("MongoDB is not Connected! Please check mongoDB intance running..");
    }

}

From source file:d3V.GetFriendsIDs.java

License:Apache License

/**
 * Usage: java twitter4j.examples.friendsandfollowers.GetFollowersIDs [screen name]
 *
 * @param args message/*from w ww .  j  a v a  2  s .  c  o m*/
 */
public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Em3WTI7jc90HcvKzPkTLQ")
            .setOAuthConsumerSecret("vg4p6rOF32bmffqRR8m0jAUClrxvtGiMB5PrSr3Zsw")
            .setOAuthAccessToken("1681973072-1q0zI0VPjHD3ttNuaBOL94frzCI9sXInxAcDK0w")
            .setOAuthAccessTokenSecret("ZRLkOyjmhHBkU1iNyEVNyIgIBsKrl0DUDKOcOMneYFYEM");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    try {
        String core_user = "nytimes";
        FileWriter writer = new FileWriter(core_user + "_friends.txt", true);
        Twitter twitter = tf.getInstance();

        long cursor = -1;
        ArrayList<String> directFriends = new ArrayList<String>();
        PagableResponseList<User> tempFriends = null;

        System.out.println("Listing " + core_user + " friends's ScreenNames.");
        int count = 0;
        //boolean first = true;
        //getFriends(writer, twitter, cursor, count, core_user);
        do {
            tempFriends = twitter.getFriendsList(core_user, cursor);

            for (User user : tempFriends) {
                directFriends.add(user.getScreenName());
                writer.write(core_user + "\t" + user.getScreenName() + "\n");
            }

            count += tempFriends.size();
            System.out.println(core_user + ": " + count);
            if (count >= 100)
                break;

            Thread.sleep(300 * MILLISECOND);

        } while ((cursor = tempFriends.getNextCursor()) != 0);

        System.out.println("Size of DFs: " + directFriends.size());

        //            for (String user : directFriends){
        for (int i = 0; i < directFriends.size(); i++) {
            //                PagableResponseList<User> idrfriends = null;
            long _cursor = -1;
            int _count = 0;
            String _username = directFriends.get(i);
            System.out.println("\nFriends of Direct friend: " + _username + "(" + (i + 1) + ")");
            try {
                getFriends(writer, twitter, _cursor, _count, _username);
            } catch (TwitterException e) {
                e.printStackTrace();
                System.out.println("Failed to get friends' ids: " + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        writer.close();
        System.out.println(count);
        System.exit(0);
    } catch (TwitterException e) {
        e.printStackTrace();
        System.out.println("Failed to get friends' ids: " + e.getMessage());
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:de.ecw.ant.twitter.AntTwitterTask.java

License:Apache License

/**
 * Executes Ant task:// w w  w  .j av  a  2 s. c o  m
 * <ul>
 * <li>establish a connection to Twitter via twitter4j</li>
 * <li>if enabled, execute URL shortening via bitly</li>
 * <li>check the input message and split it into chunks if message is larger
 * than 140 characters</li>
 * <li>update status of every message</li>
 * </ul>
 */
public void execute() throws BuildException {
    String useMessage = getMessage();

    // validate Twitter parameters
    if ((getConsumerKey() == null) || ((getConsumerKey() != null) && (getConsumerKey().length() == 0))
            || (getConsumerSecret() == null)
            || ((getConsumerSecret() != null) && (getConsumerSecret().length() == 0))) {
        log("You have to enter a valid Twitter username/password combination, missing arguments!",
                Project.MSG_ERR);
        return;
    }

    // should URLs be shortened?
    if ((getEnableBitly() != null) && (getEnableBitly().toLowerCase().equals(TRUE))) {
        // validate bit.ly parameters
        if ((getBitlyUsername() == null) || ((getBitlyUsername() != null) && (getBitlyUsername().length() == 0))
                || (getBitlyApiKey() == null)
                || ((getBitlyApiKey() != null) && (getBitlyApiKey().length() == 0))) {
            log("You have enabled bit.ly support, but bit.ly username or API key is missing - bit.ly support is disabled",
                    Project.MSG_WARN);
        } else {
            useMessage = shortenUrls(message);
        }
    }

    // new Twitter client
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(getConsumerKey()).setOAuthConsumerSecret(getConsumerSecret())
            .setOAuthAccessToken(getAccessToken()).setOAuthAccessTokenSecret(getAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    // assume that all messages are longer than 140 chars
    List<String> messages = AntTwitterTask.splitMessage(useMessage);

    log("Twittering update (" + messages.size() + " tweets)", Project.MSG_INFO);

    int iTotalPosts = messages.size();
    int iSuccededUpdates = 0;

    try {
        // post every tweet
        for (int i = 0; i < iTotalPosts; i++) {
            String msg = messages.get(i);
            log(msg.length() + " chars: " + msg, Project.MSG_INFO);
            twitter.updateStatus(msg);
            iSuccededUpdates++;
        }
    } catch (TwitterException e) {
        log("Failed to update Twitter status", e, Project.MSG_ERR);
    }

    log("Tweets posted: " + iSuccededUpdates + "/" + iTotalPosts, Project.MSG_INFO);
}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

/**
 * Connect with twitter to get a new personalized twitter4j instance.
 *
 * @throws RuntimeException if verification or connecting failed
 *///from w w w  .  j  ava 2  s . c o  m
public TwitterSearch initTwitter4JInstance(String token, String tokenSecret, boolean verify) {
    if (consumerKey == null)
        throw new NullPointerException("Please use init consumer settings!");

    setupProperties();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(token).setOAuthAccessTokenSecret(tokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
    try {
        //            RequestToken requestToken = t.getOAuthRequestToken();
        //            System.out.println("TW-URL:" + requestToken.getAuthorizationURL());
        if (verify)
            twitter.verifyCredentials();

        String str = twitter.getScreenName();
        logger.info("create new TwitterSearch for " + str + " with verifification:" + verify);
    } catch (TwitterException ex) {
        //            if (checkAndWaitIfRateLimited("initTwitter", ex))
        //                return this;

        throw new RuntimeException(ex);
    }
    return this;
}

From source file:edu.allegheny.gatortweet.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {/*from   w  ww  .j  a  v  a  2 s . c om*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("rPtRCCRqdDyoxHS3E2UARA")
                .setOAuthConsumerSecret("hhDnR4NETStvN4F84km2xuBy3eXJ8l2FnjdL23YPs");
        // gets Twitter instance with default credentials
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        /* Twitter twitter = new TwitterFactory().getInstance(); */
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        //System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:edu.american.student.util.TwitterSpider.java

License:Open Source License

/**
 * Grabs the last 100 tweet objects (Status) from a handle
 * @param handle/*from   w ww .  j  a  v  a2 s . c  o  m*/
 * @return
 * @throws SpiderException
 */
public static List<Status> spider(String handle) throws SpiderException {
    //connect to Twitter
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.getTwitterOAuthConsumerKey())
            .setOAuthConsumerSecret(Constants.getTwitterOAuthConsumerSecret())
            .setOAuthAccessToken(Constants.getTwitterOAuthAccessToken())
            .setOAuthAccessTokenSecret(Constants.getTwitterOAuthAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());

    Twitter twitter = tf.getInstance();
    //get  tweets
    Query query = new Query("from:" + handle.replace("@", ""));
    query.setCount(100);
    QueryResult result;
    try {
        result = twitter.search(query);
        List<Status> toReturn = result.getTweets();
        return toReturn;
    } catch (TwitterException e) {
        String gripe = "Twitter spider failed to...err spider!";
        throw new SpiderException(gripe, e);
    }
}

From source file:edu.mum.cs.wap.TwitterUtil.java

private static Twitter getTwitter() {
    if (twitter == null) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("ZhsCVnhHjs54ZLCxgE82n6GEa")
                .setOAuthConsumerSecret("FixRe4imh376SRWcxgoF14GdyaQjW7tLHE13mxcgNXNiObwSnr")
                .setOAuthAccessToken("935445715-EcVDaqqw7QQgcviXSOWWDT5ZCT8LkHbBNP1Pzd1W")
                .setOAuthAccessTokenSecret("PJIEzaRZB21tZP01CAaZEoEaVEcVvIRK6jMOlDyqc0peL");
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
    }/* w ww.  ja v  a 2 s.c o  m*/
    return twitter;
}

From source file:edu.proyectofinal.integradorrs.services.tweets.impl.TweetsServiceImpl.java

@Override
public Collection<Status> getAllTweets(String email) {

    TwitterCredentials tc = TwitterCredentials.getInstance();
    ConfigurationBuilder cb = tc.GetCredentials(email);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    List<Status> statuses = null;
    try {//from   www  .  j  a v a 2 s  .c o  m
        statuses = twitter.getHomeTimeline();
    } catch (TwitterException ex) {
        Logger.getLogger(TweetsServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    Collection<Status> result = (Collection<Status>) statuses;
    return result;

}

From source file:edu.proyectofinal.integradorrs.services.tweets.impl.TweetsServiceImpl.java

@Override
public Collection<Status> getUserTimeline(String user, String email) {
    TwitterCredentials tc = TwitterCredentials.getInstance();
    ConfigurationBuilder cb = tc.GetCredentials(email);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    List<Status> statuses = null;
    Paging paging = new Paging(1, 30);
    try {/*  ww  w.  j  a  v  a2 s . c om*/
        statuses = twitter.getUserTimeline(user, paging);
    } catch (TwitterException ex) {
        Logger.getLogger(TweetsServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    Collection<Status> result = (Collection<Status>) statuses;
    return result;
}

From source file:edu.smc.mediacommons.panels.TwitterPanel.java

License:Open Source License

public TwitterPanel() {
    setLayout(null);//from w  ww  . jav  a  2 s. c o m

    jButton = Utils.createButton("Login", 210, 100, 100, 20, null);
    add(jButton);

    passwordField = new JPasswordField();
    passwordField.setBounds(110, 100, 100, 20);
    add(passwordField);

    message = Utils.createLabel("Sign-in to Authenticate API calls", 80, 70, 300, 20,
            Resources.VERDANA_14_BOLD);
    add(message);

    // You can use your own credentials, and choose to encrypt them or not

    /*
    String tempEncrypted = null;
            
            
    try {
    InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("YOUR_PATH");
    InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
    BufferedReader reader = new BufferedReader(streamReader);
    tempEncrypted = reader.readLine();
    } catch (IOException e) {
            
    }*/

    final String encrypted = null;

    jButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
                textEncryptor.setPassword(passwordField.getText());
                String[] decrypted = textEncryptor.decrypt(encrypted).split("\\$");

                ConfigurationBuilder cb = new ConfigurationBuilder();
                cb.setDebugEnabled(true).setOAuthConsumerKey(decrypted[0]).setOAuthConsumerSecret(decrypted[1])
                        .setOAuthAccessToken(decrypted[2]).setOAuthAccessTokenSecret(decrypted[3]);

                TwitterFactory tf = new TwitterFactory(cb.build());
                twitterModule = new TwitterModule(tf.getInstance());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(getParent(), "The input password was not correct.");
                return;
            }

            JOptionPane.showMessageDialog(getParent(), "Authentication successful.");
            restructurePanel();
        }
    });
}