Example usage for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

List of usage examples for twitter4j.conf ConfigurationBuilder ConfigurationBuilder

Introduction

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

Prototype

ConfigurationBuilder

Source Link

Usage

From source file:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException//from  w ww . jav  a 2s.c om
 * @throws java.io.IOException
 */
public static void main(String[] args) throws TwitterException, IOException {

    /* ---------------------------Setting up twitter account authentication-------------------------------*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS")
            .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO")
            .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP")
            .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG");

    /* ---------------------------------File Writing Variables------------------------------------------------*/

    File outfile = new File("output.txt");
    FileWriter fwriter = new FileWriter(outfile);

    try (PrintWriter pWriter = new PrintWriter(fwriter)) {

        /*----------------------------------Search Parameters-------------------------------------*/

        String search = "chinese food";
        String lang = "en";
        /*------------------------End Search Parameters----------------------------------------*/

        int numTweets = 0;
        long maxID = -1;
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        try {

            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            //System.out.println(rateLimitStatus);
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

            /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(),
                searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());
            */

            for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) {

                System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n");

                if (searchTweetsRateLimit.getRemaining() == 0) {
                    System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                            searchTweetsRateLimit.getSecondsUntilReset());
                    Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                }
                //here is where we can send an object to the query
                Query query = new Query(search);
                query.setCount(tweetsPerQuery);
                query.resultType(Query.ResultType.recent);
                query.setLang(lang);

                if (maxID != -1) {
                    query.setMaxId(maxID - 1);
                }

                QueryResult result = twitter.search(query);

                if (result.getTweets().size() == 0) {
                    break;
                }

                for (Status s : result.getTweets()) {

                    numTweets++;

                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }

                    System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(),
                            s.getUser().getScreenName(), cleanText(s.getText()));

                    pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName()
                            + " " + cleanText(s.getText()));

                }

                searchTweetsRateLimit = result.getRateLimitStatus();

            }

        }

        catch (Exception e) {

            System.out.println("Broken");

            e.printStackTrace();
        }
        System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets);
        pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n");
        pWriter.close();

        /*while (result.hasNext()){
            numTweets += result.getCount();
        System.out.println(numTweets);
         for (Status status : result.getTweets()) {
             System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
         }  
         result.nextQuery();
        }
                   
                     
                 
                 
        /*
         QueryForm qf = new QueryForm();
           qf.show();
        */

    }

}

From source file:twittertimeline.MainFrame.java

public void SetTwitter() throws TwitterException {
    //Keys/*from w w w  .java 2 s  . c o m*/
    ConfigurationBuilder cf = new ConfigurationBuilder();
    cf.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("")
            .setOAuthAccessTokenSecret("");

    //Create twitter object
    tw = new TwitterFactory(cf.build());
    twt = tw.getInstance();

    //Setting the photo of login user 
    BufferedImage img = null;
    try {
        img = ImageIO.read(new URL(twt.showUser("username").getOriginalProfileImageURL()));
        photo.setIcon(
                new ImageIcon(img.getScaledInstance(photo.getWidth(), photo.getHeight(), img.SCALE_DEFAULT)));

    } catch (Exception e) {
        photo.setText("Photo Error");
    }

    pg = new Paging(pageCounter);
    pageCounter++;

    //Get first page of timeline        
    status1 = twt.getHomeTimeline(pg);

    rtList = new ArrayList<Long>();
    fwList = new ArrayList<Long>();
    getTweets();
    showTweets();

}

From source file:twittertweetscollection.TwitterTweetsCollection.java

public List<Status> execute() throws TwitterException {

    final List<Status> statuses = new ArrayList();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("I7WYWBE6eSNKdV4FYSyiuP0uk")
            .setOAuthConsumerSecret("oft7Y6WcUCvxovPU5modCZ3BOlHH2z9Px73UkFMILN4ltBhOni")
            .setOAuthAccessToken("3524247253-o7zXFn3r8PwPb4IUTYqHRQzVabTzfoFn9Ck7FzW")
            .setOAuthAccessTokenSecret("V7zkLiJmF0vsdX8rUdkXo3q1ha452vKqVtB5OoCuQWAgR");

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

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            statuses.add(status);/*from  w  ww  .j  a  v  a 2 s.  c  om*/
            System.out.println(statuses.size() + ":" + status.getText());
            if (statuses.size() > 100) {
                synchronized (lock) {
                    lock.notify();
                }
                System.out.println("unlocked");
            }
        }

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

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

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

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

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println(sw.getMessage());

        }
    };

    //FilterQuery fq = new FilterQuery();
    //String keywords[] = { "SuperBowlSunday"};

    //fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.sample();
    //twitterStream.filter(fq);

    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("returning statuses");
    twitterStream.shutdown();
    return statuses;
}

From source file:twittervis.TwitterVis.java

public void initiate() {
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(KEY).setOAuthConsumerSecret(SECRET).setOAuthAccessToken(TOKEN)
            .setOAuthAccessTokenSecret(TOKENSECRET);
    tf = new TwitterFactory(cb.build());

    // Retrieve tweets for two topics using keyword1 and keyword2
    // the "true" and "false" values represent the binary status of two topics.
    // true = the 1st topic, and false = the 2nd topic
    retrieveTweets(keyword1, true);// ww w .j a va  2s .  co m
    retrieveTweets(keyword2, false);
}

From source file:twitter_app_p1.Twitter_app_p1.java

public static void initialize_stuff() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("T9Gl1DWeRjeBazUInktTNtEtD")
            .setOAuthConsumerSecret("3NXrL1qGpF3WPVyJQ7ytInlhNjIsMgT6s7bJOIDhD1uotzZ958")
            .setOAuthAccessToken("2428771880-4e3LHhOzmiYx4lChlAEYtJ6sB2oetARYbXcqfyU")
            .setOAuthAccessTokenSecret("7HLOf3dafjJEGoioWOMHfgiNrhBDb66YJZgSzrDkTNA9x")
            .setJSONStoreEnabled(true);/* w  w w  . j a  va2  s  .  co  m*/

    TwitterStreamFactory twitterStreamFact = new TwitterStreamFactory(cb.build());
    twitterStream = twitterStreamFact.getInstance();
}

From source file:twitter_contornos.Metodos.java

/**
 * Introducir claves para que se conecte a tu cuenta de Twitter y puedas utilizar 
 * este programa sin errores.//from   w  ww . j a  va 2 s . c o m
 * Los * representan donde tienes que introducir las claves.
 */
public void clave() {
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("LvDvh1O59uDWrShwe7kBUXPfG")
            .setOAuthConsumerSecret("r0xXqIZVjuSi11v0OAUCIJVjaunEUTfIsTw0HVAxgUyFyHDzoc")
            .setOAuthAccessToken("847339034858762240-vEg6mva8GnITk37oiJlA008xKFUA0M5")
            .setOAuthAccessTokenSecret("LnrfJbq0TkvGK2wMUVzDtb0oF4q49XhT78dLtS7IaQ9jF");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:twittterbot08.TwittterBot08.java

/**
 * @param consumerKey//  www.j  a  v  a  2  s  .  c  o  m
 * @param consumerSecret
 * @param accessToken
 * @param accessTokenSecret
 * @return 
 */

public Twitter intializeToken(String consumerKey, String consumerSecret, String accessToken,
        String accessTokenSecret) {

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessTokenSecret);
    Configuration configuration = configurationBuilder.build();

    if (configuration != null)
        System.out.println("Configuration is Authenticated!");

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();

    return twitter;
}

From source file:twittynumnum.TwittyNumNum.java

public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("6id0aTmQrXrfnijhEsC5wfzTO")
            .setOAuthConsumerSecret("E8A8nvssRUvQ0B9Td32L8hW4wyMyZwPQeAPsvj1EF1WK4HUTou")
            .setOAuthAccessToken("4350904703-rrfWDlkfRi5l2iwKj1EMpbzxmXu44aqfPL9LOlX")
            .setOAuthAccessTokenSecret("dS3dT6JNDD1ih6EHXCnBrBm7vDrMWFjcDCupyyiL6RkEu");

    //TwitterFactory tf = new TwitterFactory(cb.build());
    //Twitter twitter = tf.getInstance();
    //BackwardGrinder backy = new BackwardGrinder(twitter);
    // backy.grind("#glutenfree");
    PrintWriter out;/* ww  w.j  av  a  2s  . c o m*/
    try {
        out = new PrintWriter("data/#DebatRegionales.txt");
        TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
        FutureListener future = new FutureListener(twitterStream, out);
        String[] keywords = { "#Paris" };
        future.listen(keywords);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TwittyNumNum.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ua.group06.logic.TwitterAuthentication.java

public String getauthenticationURL(/*String requestURL*/) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    // cb.setApplicationOnlyAuthEnabled(true);

    //cb.setOAuth2TokenType(token.getTokenType());
    //cb.setOAuth2AccessToken(token.getAccessToken());
    cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET);
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    this.twitter = twitter;
    //request.setAttribute("twitter", twitter);
    RequestToken requestToken = twitter.getOAuthRequestToken(/*requestURL*/);
    this.requestToken = requestToken;
    //request.getSession().setAttribute("requestToken", requestToken);
    return requestToken.getAuthenticationURL();
}

From source file:uk.ac.susx.tag.method51.twitter.params.TwitterAccountParams.java

License:Apache License

private ConfigurationBuilder newConfigurationBuilder() {
    return new ConfigurationBuilder().setOAuthConsumerKey(getConsumerKey())
            .setOAuthConsumerSecret(getConsumerSecret()).setOAuthAccessToken(getAccessToken())
            .setOAuthAccessTokenSecret(getAccessTokenSecret());
}