Example usage for twitter4j Twitter setOAuthAccessToken

List of usage examples for twitter4j Twitter setOAuthAccessToken

Introduction

In this page you can find the example usage for twitter4j Twitter setOAuthAccessToken.

Prototype

void setOAuthAccessToken(AccessToken accessToken);

Source Link

Document

Sets the access token

Usage

From source file:com.robertszkutak.androidexamples.twitterexample.AndroidTwitterExample.java

License:Open Source License

public boolean isAuthenticated() {
    if (token == null || secret == null || token == "" || secret == "") {
        debug = "";
        debugStatus.setText(debug);/*  ww w. ja v a 2 s.c o  m*/
        return false;
    } else {
        AccessToken a = new AccessToken(token, secret);
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);

        try {
            twitter.getAccountSettings();
            return true;
        } catch (TwitterException e) {
            debug += "\n\n" + e.getMessage();
            debugStatus.setText(debug);
            return false;
        }
    }
}

From source file:com.robertszkutak.androidexamples.twitterexample.AndroidTwitterExample.java

License:Open Source License

public void sendTweetToTwitter(String msg) throws Exception {
    AccessToken a = new AccessToken(token, secret);
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
    twitter.setOAuthAccessToken(a);
    twitter.updateStatus(msg);//from   w  ww  . jav  a 2 s.c o  m
}

From source file:com.rsinghal.cep.sample.facebook.StreamCollector1.java

License:Apache License

public void start() {

    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {/*w  w  w .  j a v  a  2  s  . c om*/
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    twitter = null;

    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.rsinghal.cep.sample.twitter.StreamCollector1.java

License:Apache License

public void start() {

    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    long[] userIdsToTrack = new long[trackTerms.size()];
    for (int i = 0; i < trackTerms.size(); i++) {
        try {/*from ww w.  ja  v  a 2s.  com*/
            String screenName = StringUtils.substringAfter(trackTerms.get(i), "@");
            logger.info("Fetching user ID for - " + screenName);
            userIdsToTrack[i] = twitter.showUser(screenName).getId();
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    twitter = null;
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    twitterStream.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    twitterStream.addListener(listener2);
    // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, userIdsToTrack, trackTerms.toArray(new String[trackTerms.size()])));

    System.out.println("start() ...");
    /*   // Create an appropriately sized blocking queue
       BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000);
               
       // create the endpoint
       DefaultStreamingEndpoint endpoint = createEndpoint();
       System.out.println("endpoint created ...");
            
       endpoint.stallWarnings(false);
            
       // create an authentication
       Authentication auth = new OAuth1(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            
       // Create a new BasicClient. By default gzip is enabled.
       client = new ClientBuilder().name("sampleExampleClient")
    .hosts(Constants.STREAM_HOST).endpoint(endpoint)
    .authentication(auth)
    .processor(new StringDelimitedProcessor(queue)).build();
       System.out.println("client created ...");
            
       // Create an executor service which will spawn threads to do the actual
       // work of parsing the incoming messages and
       // calling the listeners on each message
       ExecutorService service = Executors
    .newFixedThreadPool(this.numberOfProcessingThreads);
            
       // Wrap our BasicClient with the twitter4j client
       Twitter4jStatusClient t4jClient = new Twitter4jStatusClient(client,
    queue, Lists.newArrayList(listener2), service);
            
       // Establish a connection
       t4jClient.connect();
               
       System.out.println("connection established ...");
            
       for (int threads = 0; threads < this.numberOfProcessingThreads; threads++) {
          // This must be called once per processing thread
          t4jClient.process();
          System.out.println("thread " + threads + " started ...");
            
       }*/
}

From source file:com.stepinmobile.fantasticbutton.api.ButtonHandle.java

License:Apache License

/**
 * Method post tweet.//from w  w  w  .  jav a  2s  .com
 */
private void postTweet() {
    Twitter twitter = new TwitterFactory().getInstance();
    AccessToken accessToken = new AccessToken(twitterHandle.getToken(), twitterHandle.getSecret());
    twitter.setOAuthConsumer(twitterAppId, twitterAppSecret);
    twitter.setOAuthAccessToken(accessToken);

    Status status = null;
    try {
        status = twitter.updateStatus(tweetToBeTweeted);
    } catch (TwitterException e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

From source file:com.temenos.interaction.example.mashup.twitter.Twitter4JConsumer.java

License:Open Source License

/**
 * @param otherUser/*from w  w  w  . java 2s .  com*/
 * @return
 */
public Collection<Tweet> requestTweetsByUser(String otherUser) {
    List<Tweet> tweets = new ArrayList<Tweet>();
    try {
        // The factory instance is re-useable and thread safe.
        Twitter twitter = new TwitterFactory().getInstance();
        AccessToken accessToken = loadAccessToken(1);
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(accessToken);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Fetching latest 100 tweets for [" + otherUser + "]");
        }
        // First param of Paging() is the page number, second is the number per page (this is capped around 200 I think.
        Paging paging = new Paging(1, 100);
        List<Status> statuses = twitter.getUserTimeline(otherUser, paging);
        for (Status status : statuses) {
            tweets.add(new Tweet(otherUser, status.getText(),
                    (status.getGeoLocation() != null
                            ? status.getGeoLocation().getLatitude() + ","
                                    + status.getGeoLocation().getLongitude()
                            : "")));
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                        status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error on requestTweetsByUser", e);
        throw new TwitterMashupException(e);
    }
    return tweets;
}

From source file:com.twitstreet.twitter.AnnouncerMgrImpl.java

License:Open Source License

public void loadAnnouncers() {
    Connection connection = null;
    PreparedStatement ps = null;/*from w  ww . j  a  v  a2 s  . c o  m*/
    ResultSet rs = null;
    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(LOAD_ANNOUNCER);
        rs = ps.executeQuery();
        while (rs.next()) {
            Announcer announcer = new Announcer();
            announcer.getDataFromResultSet(rs);
            announcerDataList.add(announcer);
            if (TWITSTREET_GAME.equals(announcer.getName())) {
                twitstreetGame = new TwitterFactory().getInstance();
                twitstreetGame.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
                twitstreetGame.setOAuthAccessToken(
                        new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
            } else {
                Twitter twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
                twitter.setOAuthAccessToken(
                        new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
                announcerList.add(twitter);
            }
        }
        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);

    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }

}

From source file:com.twitstreet.twitter.TwitterProxyImpl.java

License:Open Source License

@Inject
public TwitterProxyImpl(ConfigMgr configMgr, @Assisted("oauthToken") String oauthToken,
        @Assisted("oauthTokenSecret") String oauthTokenSecret) {
    this.configMgr = configMgr;
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(configMgr.getConsumerKey(), configMgr.getConsumerSecret());
    accessToken = new AccessToken(oauthToken, oauthTokenSecret);

    oToken = oauthToken;/*from  w w  w .ja  v a2s . c  om*/
    oSecret = oauthTokenSecret;

    twitter.setOAuthAccessToken(accessToken);
    this.setTwitter(twitter);

    //top
    woiedMap.put("Worldwide", 1);
    //1
    woiedMap.put("Argentina", 23424747);
    woiedMap.put("Australia", 23424748);
    woiedMap.put("Brazil", 23424768);
    woiedMap.put("Canada", 23424775);
    woiedMap.put("Chile", 23424782);
    woiedMap.put("Colombia", 23424787);
    woiedMap.put("Dominican Republic", 23424800);
    woiedMap.put("Ecuador", 23424801);
    woiedMap.put("France", 23424819);
    woiedMap.put("Germany", 23424829);
    woiedMap.put("Guatemala", 23424834);
    woiedMap.put("India", 23424848);
    //2
    woiedMap.put("Indonesia", 23424846);
    woiedMap.put("Ireland", 23424803);
    woiedMap.put("Italy", 23424853);
    woiedMap.put("Japan", 23424856);
    woiedMap.put("Malaysia", 23424901);
    woiedMap.put("Mexico", 23424900);
    woiedMap.put("Netherlands", 23424909);
    woiedMap.put("New Zeland", 23424916);
    woiedMap.put("Nigeria", 23424908);
    woiedMap.put("Pakistan", 23424922);
    woiedMap.put("Peru", 23424919);
    woiedMap.put("Philippines", 23424934);
    //3
    woiedMap.put("Russia", 23424936);
    woiedMap.put("Singapore", 23424948);
    woiedMap.put("South Africa", 23424942);
    woiedMap.put("Spain", 23424950);
    woiedMap.put("Sweden", 23424954);
    woiedMap.put("Turkey", 23424969);
    woiedMap.put("United Arab Emirates", 23424738);
    woiedMap.put("United Kingdom", 23424975);
    woiedMap.put("United States", 23424977);
    woiedMap.put("Venezuela", 23424982);
}

From source file:com.yattatech.dbtc.facade.SystemFacade.java

License:Open Source License

public void sendTwitterMsg(final String msg) {
    if (Debug.isDebugable()) {
        Debug.d(TAG, "sendTwitterMsg " + msg);
    }//  ww  w.jav  a  2  s  .co  m
    mExecutor.execute(new Runnable() {

        /*
         * (non-Javadoc)
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            final Twitter twitter = TwitterUtil.getTwitter();
            try {
                twitter.setOAuthAccessToken(mPrefs.getTwitterAccessToken());
                twitter.updateStatus(msg);
            } catch (TwitterException te) {
                Debug.d(TAG, "Failed: ", te);
            }
        }
    });
}

From source file:com.zisal.twit.crawl.core.Example.java

public static void main(String[] args) {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(ApplicationConstant.TwitterKey.CUSTOMER_KEY,
            ApplicationConstant.TwitterKey.CUSTOMER_SECRET);
    twitter.setOAuthAccessToken(
            new AccessToken(ApplicationConstant.TwitterKey.TOKEN, ApplicationConstant.TwitterKey.TOKEN_SECRET));
    /*try{// ww  w . jav a  2 s.c  om
    ResponseList<Status> responseList = twitter.getUserTimeline(new Paging(1, 5));
    for(Status s: responseList){
        System.out.println("Response List ".concat(s.getText()));
    }
    }catch(Exception e){
    e.printStackTrace();
    }
            
    long cursor = -1;
    IDs ids = null;
    System.out.println("Listing followers's ids.");
    do {
    try {
        ids = twitter.getFollowersIDs(ApplicationConstant.Twitter.SCREEN_NAME, cursor);
        for (long id : ids.getIDs()) {
            System.out.println(id);
            User user = twitter.showUser(id);
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
    } while ((cursor = ids != null ? ids.getNextCursor() : 0) != 0);*/

    long cursor = -1;
    PagableResponseList<User> pagableFollowings = null;
    List<User> listFriends = new ArrayList<>();
    do {
        try {
            pagableFollowings = twitter.getFriendsList(18211861, cursor);
            for (User user : pagableFollowings) {
                listFriends.add(user);
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend #1st level " + user.getName());
                /*PagableResponseList<User> _2ndLevelPageableFollowings = twitter.getFriendsList(user.getId(), cursor);
                for(User _2ndLevelFriend : _2ndLevelPageableFollowings){
                logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "added friend #2nd level "+ _2ndLevelFriend.getName());
                listFriends.add(_2ndLevelFriend);
                }*/
            }
        } catch (TwitterException e) {
            e.printStackTrace();
        }

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

    logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend total : " + listFriends.size());
    for (User user : listFriends) {
        logger.info(ApplicationConstant.LogTag.ZUNA_INFO, "friend : " + user.getName());
    }

    /*
            cursor = -1;
            PagableResponseList<User> pagableFollowers = null;
            List<User> listFollowers = new ArrayList<>();
            do {
    try {
        pagableFollowers = twitter.getFollowersList(twitter.getId(), cursor);
        for (User user : pagableFollowers) {
            listFollowers.add(user); // ArrayList<User>
            System.out.println(user.getName());
        }
    } catch (TwitterException e) {
        e.printStackTrace();
    }
            
            } while ((cursor = pagableFollowers.getNextCursor()) != 0);
    */

}