List of usage examples for twitter4j.auth AccessToken AccessToken
public AccessToken(String token, String tokenSecret)
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 w w w . j a v a2s . c o m 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.rsinghal.cep.sample.twitter.TwitterBot.java
License:Apache License
public void start() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setJSONStoreEnabled(true);//from w w w . jav a 2 s . c o m twitter = new TwitterFactory(cb.build()).getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); userIdsToTrack = new long[trackTerms.size()]; for (int i = 0; i < trackTerms.size(); i++) { try { 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()]))); jedis = new Jedis(redisHostname, redisPort, 1800); jedis.connect(); 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.saugereau.spout.TwitterSpout.java
License:Apache License
@Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;//from ww w . jav a 2s . c om StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { queue.offer(status); } @Override public void onDeletionNotice(StatusDeletionNotice sdn) { } @Override public void onTrackLimitationNotice(int i) { LOG.info("Got track limitation notice:" + i); } @Override public void onScrubGeo(long l, long l1) { } @Override public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; _twitterStream = new TwitterStreamFactory(new ConfigurationBuilder().setJSONStoreEnabled(true).build()) .getInstance(); _twitterStream.addListener(listener); _twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); _twitterStream.setOAuthAccessToken(token); if (keyWords.length == 0) { _twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); query.language(new String[] { "en" }); _twitterStream.filter(query); } }
From source file:com.soomla.profile.social.twitter.SoomlaTwitter.java
License:Apache License
/** * {@inheritDoc}/* w w w. j a v a 2 s . com*/ */ @Override public void login(final Activity parentActivity, final AuthCallbacks.LoginListener loginListener) { if (!isInitialized) { SoomlaUtils.LogError(TAG, "Consumer key and secret were not defined, please provide them in initialization"); return; } SoomlaUtils.LogDebug(TAG, "login"); WeakRefParentActivity = new WeakReference<Activity>(parentActivity); RefProvider = getProvider(); RefLoginListener = loginListener; preformingAction = ACTION_LOGIN; mainRequestToken = null; twitter.setOAuthAccessToken(null); // Try logging in using store credentials String oauthToken = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_OAUTH_TOKEN)); String oauthTokenSecret = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_OAUTH_SECRET)); if (!TextUtils.isEmpty(oauthToken) && !TextUtils.isEmpty(oauthTokenSecret)) { twitter.setOAuthAccessToken(new AccessToken(oauthToken, oauthTokenSecret)); twitterScreenName = KeyValueStorage.getValue(getTwitterStorageKey(TWITTER_SCREEN_NAME)); loginListener.success(RefProvider); clearListener(ACTION_LOGIN); } else { // If no stored credentials start login process by requesting // a request token twitter.getOAuthRequestTokenAsync(oauthCallbackURL); } }
From source file:com.spec.CityTwitterSource.java
License:Apache License
/** * Start processing events. This uses the Twitter Streaming API to sample * Twitter, and process tweets.//w w w. j a v a2s . c o m */ @Override public void start() { // The channel is the piece of Flume that sits between the Source and Sink, // and is used to process events. final ChannelProcessor channel = getChannelProcessor(); final Map<String, String> headers = new HashMap<String, String>(); // The StatusListener is a twitter4j API, which can be added to a Twitter // stream, and will execute methods every time a message comes in through // the stream. StatusListener listener = new StatusListener() { // The onStatus method is executed every time a new tweet comes in. public void onStatus(Status status) { // The EventBuilder is used to build an event using the headers and // the raw JSON of a tweet flag = false; for (int i = 0; i < cities.length; i++) { if (status.getUser().getLocation().toLowerCase().contains(cities[i].toLowerCase())) flag = true; } if (flag) { logger.debug(status.getUser().getLocation() + " : " + flag); headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime())); Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status.getUser()).getBytes(), headers); channel.processEvent(event); } } // This listener will ignore everything except for new tweets public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning sw) { } }; //logger.debug("Setting up Twitter sample stream using consumer key {} and" + // " access token {}", new String[] { consumerKey, accessToken }); // Set up the stream's listener (defined above), and set any necessary // security information. twitterStream.addListener(listener); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); twitterStream.setOAuthAccessToken(token); // Set up a filter to pull out industry-relevant tweets if (keywords.length == 0) { logger.debug("Starting up Twitter sampling..."); twitterStream.sample(); } else { logger.debug("Starting up Twitter filtering..."); FilterQuery query = new FilterQuery().track(keywords); twitterStream.filter(query); } super.start(); }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
private void checkTwitterID() { /* Get Access Token after login*/ try {//from ww w . ja v a 2 s . co m ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); // Access Token String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, ""); // Access Token Secret String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, ""); AccessToken accessToken = new AccessToken(access_token, access_token_secret); Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken); // Getting user details from twitter // For now i am getting his name only twitterID = accessToken.getUserId(); User user = twitter.showUser(twitterID); userName = user.getName(); //Toast.makeText(TraqComplaintTaxi.this, Long.toString(twitterID) + userName, Toast.LENGTH_SHORT).show(); // Displaying in xml ui //lblUserName.setText(Html.fromHtml("<b>Welcome " + username + "</b>" + description)); } catch (TwitterException e) { // Error in updating status Log.d("Twitter Update Error", e.getMessage()); } catch (Exception e) { // Error in updating status Log.d("error!", e.getMessage()); } }
From source file:com.sstrato.flume.source.TwitterSource.java
License:Apache License
/** * Start processing events. This uses the Twitter Streaming API to sample * Twitter, and process tweets./* ww w .ja v a2 s.co m*/ */ @Override public void start() { // ? ? final ChannelProcessor channel = getChannelProcessor(); final Map<String, String> headers = new HashMap<String, String>(); // ? twitter4j? StatusListener ? ?. StatusListener listener = new StatusListener() { // The onStatus method is executed every time a new tweet comes in. public void onStatus(Status status) { // header raw json ? ? . logger.debug(status.getUser().getScreenName() + ": " + status.getText()); headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime())); Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers); channel.processEvent(event); } // This listener will ignore everything except for new tweets public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onException(Exception ex) { } @Override public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}", new String[] { this.consumerKey, this.accessToken }); // Set up the stream's listener (defined above), and set any necessary // security information. twitterStream.addListener(listener); twitterStream.setOAuthConsumer(this.consumerKey, this.consumerSecret); AccessToken token = new AccessToken(this.accessToken, this.accessTokenSecret); twitterStream.setOAuthAccessToken(token); // Set up a filter to pull out industry-relevant tweets if (keywords.length == 0) { logger.debug("Starting up Twitter sampling..."); twitterStream.sample(); } else { logger.debug("Starting up Twitter filtering..."); // ? . FilterQuery query = new FilterQuery().track(keywords); twitterStream.filter(query); } super.start(); }
From source file:com.stepinmobile.fantasticbutton.api.ButtonHandle.java
License:Apache License
/** * Method post tweet./*from w w w . j a v a2s . c om*/ */ 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.storm.demo.TwitterSampleSpout.java
License:Apache License
@Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<String>(1000); _collector = collector;/* ww w . java 2s.c o m*/ // StatusListener listener = new StatusListener() { // // @Override // public void onStatus(Status status) { // System.out.println(DataObjectFactory.getRawJSON(status)); // queue.offer(status); // } // // @Override // public void onDeletionNotice(StatusDeletionNotice sdn) { // } // // @Override // public void onTrackLimitationNotice(int i) { // } // // @Override // public void onScrubGeo(long l, long l1) { // } // // @Override // public void onException(Exception ex) { // } // // @Override // public void onStallWarning(StallWarning arg0) { // // TODO Auto-generated method stub // // } // // }; RawStreamListener rawListener = new RawStreamListener() { @Override public void onMessage(String rawJSON) { //System.out.println(rawJSON); queue.offer(rawJSON); } @Override public void onException(Exception ex) { ex.printStackTrace(); } }; TwitterStream twitterStream = new TwitterStreamFactory( new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance(); //twitterStream.addListener(listener); twitterStream.addListener(rawListener); twitterStream.setOAuthConsumer(consumerKey, consumerSecret); AccessToken token = new AccessToken(accessToken, accessTokenSecret); twitterStream.setOAuthAccessToken(token); if (keyWords.length == 0) { twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); twitterStream.filter(query); } }
From source file:com.thesmartweb.swebrank.TwitterAnalysis.java
License:Apache License
/** * Method to get tweets regarding a string * @param query_string the string to search for * @param config_path the directory with the twitter api key * @return the tweets in a string// ww w . j av a 2s .co m */ public String perform(String query_string, String config_path) { try { List<String> twitterkeys = GetKeys(config_path); //configuration builder in order to set the keys of twitter ConfigurationBuilder cb = new ConfigurationBuilder(); String consumerkey = twitterkeys.get(0); String consumersecret = twitterkeys.get(1); String accesstoken = twitterkeys.get(2); String accesstokensecret = twitterkeys.get(3); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerkey).setOAuthConsumerSecret(consumersecret) .setOAuthAccessToken(accesstoken).setOAuthAccessTokenSecret(accesstokensecret); TwitterFactory tf = new TwitterFactory(cb.build()); AccessToken acc = new AccessToken(accesstoken, accesstokensecret); Twitter twitter = tf.getInstance(acc); //query the twitter Query query = new Query(query_string); int rpp = 100; query.count(rpp); query.setQuery(query_string); //----------get the tweets------------ QueryResult result = twitter.search(query); List<Status> tweets = result.getTweets(); RateLimitStatus rls = result.getRateLimitStatus(); String tweet_txt = ""; for (Status tweet : tweets) { tweet_txt = tweet_txt + " " + tweet.getText(); } DataManipulation txtpro = new DataManipulation(); Stopwords st = new Stopwords(); tweet_txt = txtpro.removeChars(tweet_txt); tweet_txt = st.stop(tweet_txt); tweet_txt = txtpro.removeChars(tweet_txt); return tweet_txt; } catch (TwitterException ex) { String tweet_txt = ""; Logger.getLogger(TwitterAnalysis.class.getName()).log(Level.SEVERE, null, ex); return tweet_txt = "fail"; } }