Example usage for twitter4j.conf ConfigurationBuilder build

List of usage examples for twitter4j.conf ConfigurationBuilder build

Introduction

In this page you can find the example usage for twitter4j.conf ConfigurationBuilder build.

Prototype

public Configuration build() 

Source Link

Usage

From source file:Twitter.Twitter.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("8e27WtNVhuIOt1EAyAdqV51Yk")
            .setOAuthConsumerSecret("dsgPVnwV53UwiPuAA5r0CbNykubjxmGHe7csf0Y1zGOV8KVe0r")
            .setOAuthAccessToken("4143520821-ZgULKYSyMRbrXytCvkmdGeXbd7L0bx4NOiM4fKC")
            .setOAuthAccessTokenSecret("jju1OwDCromI9r0QK1gU18MrFOkw1jsKFCQtXjFbv5G8A");

    TwitterFactory tf = new TwitterFactory(cb.build());

    twitter4j.Twitter tw = tf.getInstance();

    Status stat;/*from   ww w . ja  v  a 2  s.  c  o m*/
    try {
        stat = tw.updateStatus(tweet.getText());

        //System.out.println("twitter updated");
    } catch (TwitterException ex) {
        Logger.getLogger(Twitter.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:TwitterAnalytics.TwitterAPI.java

private TwitterAPI() {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumeSecretKey);
    builder.setOAuthAccessToken(accessToken);
    builder.setOAuthAccessTokenSecret(accessSecretToken);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);

    twitter = factory.getInstance();//from www. ja  v a2 s  .  co  m
}

From source file:twitterAPI.Twitter_testing.java

private void connectTwitter() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(OAuthConsumerKey);
    cb.setOAuthConsumerSecret(OAuthConsumerSecret);
    cb.setOAuthAccessToken(AccessToken);
    cb.setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterFactory = new TwitterFactory(cb.build());
    twitter = twitterFactory.getInstance();
    System.out.println("connected");
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

public static void main(String[] args) throws IOException, TwitterException {

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(//from w  w w . j  a v a 2 s .co m
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        System.out.println("status.toString() = " + status.toString());
        System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
        System.out.println("status.getSource() = " + status.getSource());
        System.out.println("status.getText() = " + status.getText());
        System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
        System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
        System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
        System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
        System.out.println("status.getId() = " + status.getId());
        System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
        System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
        System.out.println("status.getPlace() = " + status.getPlace());
        System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
        System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
        System.out.println("status.getUser() = " + status.getUser());
        System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
        System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
        System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
        if (status.getRateLimitStatus() != null) {
            System.out.println(
                    "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
            System.out.println("status.getRateLimitStatus().getRemaining() = "
                    + status.getRateLimitStatus().getRemaining());
            System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + status.getRateLimitStatus().getResetTimeInSeconds());
            System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + status.getRateLimitStatus().getSecondsUntilReset());
        }
        System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}

From source file:twitterapp.TwitterApp.java

public static void streamTweets() throws TwitterException {
    /*getting the trends */
    ConfigurationBuilder cb2 = new ConfigurationBuilder();

    cb2.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge");

    TwitterFactory tf = new TwitterFactory(cb2.build());
    Twitter twitter = tf.getInstance();//  w  ww. j a v a 2  s.  c  o  m
    Trends trends = twitter.getPlaceTrends(23424977);

    String top_trend = "";
    int top = 0;
    for (Trend trend : trends.getTrends()) {
        if (top < 1) {
            top_trend = trend.getName();
            top++;
        }
    }

    System.out.println("top trend : " + top_trend);

    //Using the Streaming API to get real time tweets based on the trending topics as keywords
    /* configurating twiter4j */

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge")
            .setJSONStoreEnabled(true);
    /* end of configuration */

    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("myTweetdb2");
    MongoCollection<Document> collection = database.getCollection("myTweetCol5");
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {

            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            Document doc = Document.parse(rawJSON);

            collection.insertOne(doc);

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    // twitterStream.sample();
    twitterStream.addListener(listener);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { top_trend };
    fq.track(keywords);
    twitterStream.filter(fq);
}

From source file:TwitterCrawler.PrintSampleStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {

    System.getProperties().put("http.proxyHost", "127.0.0.1");
    System.getProperties().put("http.proxyPort", "8580");

    //final PrintSampleStream pr = new PrintSampleStream();

    try {// w ww  . j a  va2 s. c om
        pr.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("7ZVgfKiOvBDcDFpytRWSA")
            .setOAuthConsumerSecret("JmeJVeym78arzmGthrDUshQyhkq6nWA9tWLUKxc")
            .setOAuthAccessToken("321341780-Zy7LptVYBZBVvAeQ5GFJ4aKFw8sdqhWBnvA3pDuO")
            .setOAuthAccessTokenSecret("foi8FnQCeN0J5cdwad05Q6d7dbytFayQn1ZOvmhF6Qc");
    cb.setJSONStoreEnabled(true);

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception ex) {
            // TODO Auto-generated method stub
            ex.printStackTrace();
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // TODO Auto-generated method stub
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());

        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            // TODO Auto-generated method stub
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());  
            //System.out.println(status);  
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);  
                DBObject dbObject = (DBObject) JSON.parse(str);
                pr.collection.insert(dbObject);
                System.out.println(dbObject);
                pr.count++;
                /* if(pr.count>300000) {  
                pr.mongo.close();  
                System.exit(0);  
                 }  */
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // TODO Auto-generated method stub
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);

        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }

    };
    twitterStream.addListener(listener);

    //String[] Track = {"why Obama look like he about to drop the best album of 2013?"}; 
    String[] trackArray = { "Mac", "App", "Store" };
    //trackArray[1] = ;  

    // Create a FilterQuery object and then set the items to track
    FilterQuery filter = new FilterQuery();

    // Create an array of items to track
    //String[] itemsToTrack = {""}; 
    // Set the items to track using FilterQuerys' track method.
    //filter.track(Track); 
    filter.track(trackArray);

    // Assuming you have already created Twitter/TwitterStream object, 
    // use the filter method to start streaming using the FilterQuery object just created.
    twitterStream.filter(filter);

    /* String[] username = {"katyperry"};
     twitterStream.addListener(userlistener);  
     twitterStream.user();*/
    //pr.mongo.close();
}

From source file:TwitterDownload.TwitterHandler.java

public TwitterHandler() {
    try {//from   w  w w . j a  v a  2 s  . com
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET_KEY)
                .setOAuthAccessToken(null).setOAuthAccessTokenSecret(null);
        TwitterFactory tf = new TwitterFactory(cb.build());
        twitter = tf.getInstance();
    } catch (IllegalStateException ex) {
        String s = ex.toString();
    } catch (Exception ex) {
        String s = ex.toString();
    }
}

From source file:twitterlab.TwitterLab.java

/**
 * @param args the command line arguments
 *///from w w w. j  a  v a 2 s .  co  m
public static void main(String[] args) {
    // TODO code application logic here
    Users = new ArrayList();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("yBSAPlE6wiAQU6CyIiXHSapwN");
    cb.setOAuthConsumerSecret("3CjbEkYyIZvNZ07KYpC55v9vpqxoNmMs1IkC48Wqr5tKXjUnZk");
    cb.setOAuthAccessToken("858371720-0RASIMJeaMbWr2YPmCPyh5OgCP6Kesgz0WvdsLz7");
    cb.setOAuthAccessTokenSecret("cfi5JDGLTUOKHNj7yFIdivg0Hr1bCml3VlQXj5XCOyoFr");

    try {
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter tw = tf.getInstance();
        IDs ids = tw.getFriendsIDs(-1);
        long[] ID;
        if (ids.getIDs().length > 10) {
            ID = new long[10];
            System.arraycopy(ids.getIDs(), 0, ID, 0, 10);
        } else {
            ID = ids.getIDs();
        }
        ResponseList<User> Friends = tw.lookupUsers(ID);
        User[] A = new User[10];
        if (Friends.toArray().length > 0) {
            Users.add(new ArrayList(Arrays.asList(Friends.toArray(A))));
        }
        for (int i = 0; i < ID.length; i++) {
            IDs idsFriend = tw.getFriendsIDs(ID[i], -1);
            long[] IDfriend;
            if (idsFriend.getIDs().length > 10) {
                IDfriend = new long[10];
                System.arraycopy(idsFriend.getIDs(), 0, IDfriend, 0, 10);
            } else {
                IDfriend = idsFriend.getIDs();
            }
            ResponseList<User> FriendsFriend = tw.lookupUsers(IDfriend);
            A = new User[10];
            if (FriendsFriend.toArray().length > 0) {
                Users.add(new ArrayList(Arrays.asList(FriendsFriend.toArray(A))));
            }
            //System.out.println("Sleep?");
            TimeUnit.SECONDS.sleep(60);
        }

        for (int i = 0; i < Users.size(); i++) {
            for (int j = 0; j < Users.get(0).size(); j++) {
                System.out.println(Users.get(i).get(j).getScreenName());
            }
        }

    } catch (Exception e) {
        // Thread.currentThread().interrupt();
        e.printStackTrace();
    }

}

From source file:twittermongodbapp.CollectTweets.java

static public void collectTweets(DB db, ConfigurationBuilder cf1, twitter4j.Twitter twitter) {

    TwitterStream twitterStream = new TwitterStreamFactory(cf1.build()).getInstance();

    DBCollection collection = db.getCollection("collection");
    DBCollection collection2 = db.getCollection("collection2");
    BasicDBObject document0 = new BasicDBObject();
    collection.remove(document0);//from   w  w  w. j a  v a 2  s  . com
    collection2.remove(document0);
    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {
            if (collection2.getCount() == 15000)
                System.exit(0);
            String json = DataObjectFactory.getRawJSON(status);
            DBObject doc = (DBObject) JSON.parse(json);
            try {
                collection2.insert(doc);
            } catch (Exception e) {
                System.out.println("MongoDB Connection Error : " + e.getMessage());
            }

            System.out.println("Collected tweets :" + collection2.getCount());

        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub
            System.out.println(arg0);
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub
            System.out.println(arg0);
        }
    };
    getTopTrends(twitter, twitterStream, listener);
}

From source file:twittermongodbapp.TwitterMongoDBApp.java

public static void main(String[] args) throws TwitterException {

    ConfigurationBuilder cf1 = new ConfigurationBuilder();
    ConfigurationBuilder cf2 = new ConfigurationBuilder();
    init(cf1);//from   w  w w .  jav a  2 s.c o m
    init(cf2);

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("tweetsTest");

    TwitterFactory tf = new TwitterFactory(cf2.build());
    twitter4j.Twitter twitter = tf.getInstance();
    /*
            
     System.out.println("Select option :");
     System.out.println("Collect tweets from Greece: 1");
     System.out.println("Save these tweets: 2");
     System.out.println("Exit: 0");
      Scanner scanner = new Scanner(System.in);
     int input = scanner.nextInt();
     if(input==1){
     CollectTweets ct = new CollectTweets();
     ct.collectTweets(db,cf1,twitter);
     }else if(input==2){
     SaveTweets st = new SaveTweets();
     st.saveTweets(db,twitter);
     }else if (input==0){
     mongoClient.close(); 
     return ;
     }else{
      System.out.println("Select property");
      System.out.println("Select option");
     System.out.println("Collect 20 tweets from Greece: 1");
     System.out.println("Save these tweets: 2");
     System.out.println("Exit : 0");
     }
    */
    SaveTweets st = new SaveTweets();
    st.saveTweets(db, twitter);
}