List of usage examples for twitter4j.conf ConfigurationBuilder setOAuthConsumerKey
public ConfigurationBuilder setOAuthConsumerKey(String oAuthConsumerKey)
From source file:com.tweet.HelperMethods.java
License:Apache License
public static void postToTwitterWithImage(Context context, final Activity callingActivity, final String message, final TwitterCallback postResponse) { if (!LoginActivity.isActive(context)) { postResponse.onFinsihed(false);//from w w w.jav a 2 s . c om return; } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key)); configurationBuilder .setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret)); configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context))); configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context)); Configuration configuration = configurationBuilder.build(); final Twitter twitter = new TwitterFactory(configuration).getInstance(); //final File file = new File(imageUrl); new Thread(new Runnable() { @Override public void run() { boolean success = true; try { if (StaticData.graphFile.exists()) { Calendar cal = Calendar.getInstance(); StatusUpdate status = new StatusUpdate(message + "\n@" + cal.getTime().toString()); status.setMedia(StaticData.graphFile); twitter.updateStatus(status); } else { Log.d(TAG, "----- Invalid File ----------"); success = false; } } catch (Exception e) { e.printStackTrace(); success = false; } final boolean finalSuccess = success; callingActivity.runOnUiThread(new Runnable() { @Override public void run() { postResponse.onFinsihed(finalSuccess); } }); } }).start(); }
From source file:com.tweet.LoginActivity.java
License:Apache License
private void askOAuth() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(twitterConsumerKey); configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret); Configuration configuration = configurationBuilder.build(); twitter = new TwitterFactory(configuration).getInstance(); new Thread(new Runnable() { @Override// w ww .j av a2 s. co m public void run() { try { requestToken = twitter.getOAuthRequestToken(AppConstant.TWITTER_CALLBACK_URL); } catch (Exception e) { final String errorString = e.toString(); LoginActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mAlertBuilder.cancel(); Toast.makeText(LoginActivity.this, errorString.toString(), Toast.LENGTH_SHORT).show(); finish(); } }); return; } LoginActivity.this.runOnUiThread(new Runnable() { @Override public void run() { twitterLoginWebView.loadUrl(requestToken.getAuthenticationURL()); } }); } }).start(); }
From source file:com.twitter4rk.TwitterAuthFragment.java
License:Apache License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTwitterWebView = new WebView(getActivity()); final Bundle args = getArguments(); if (args == null) { // This wont be case because startTwitterAuth() handles args for // fragment throw new IllegalArgumentException( "No arguments passed to fragment, Please use startTwitterAuth(...) method for showing this fragment"); }/*from w w w . j a v a2s . co m*/ // Get builder from args mBuilder = args.getParcelable(BUILDER_KEY); // Hide action bar if (mBuilder.hideActionBar) mBuilder.activity.getActionBar().hide(); // Init progress dialog mProgressDialog = new ProgressDialog(mBuilder.activity); mProgressDialog.setMessage(mBuilder.progressText == null ? "Loading ..." : mBuilder.progressText); if (mBuilder.isProgressEnabled) mProgressDialog.show(); // Init ConfigurationBuilder twitter4j final ConfigurationBuilder cb = new ConfigurationBuilder(); if (mBuilder.isDebugEnabled) cb.setDebugEnabled(true); cb.setOAuthConsumerKey(mBuilder.consumerKey); cb.setOAuthConsumerSecret(mBuilder.consumerSecret); // Web view client to handler url loading mTwitterWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // Get url first final Uri uri = Uri.parse(url); // Check if we need to see for callback URL if (mBuilder.callbackUrl != null && url.contains(mBuilder.callbackUrl)) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If no callback URL then check for info directly } else if (uri.getQueryParameter("oauth_token") != null && uri.getQueryParameter("oauth_verifier") != null) { // Get req info String oauthToken = uri.getQueryParameter("oauth_token"); String oauthVerifier = uri.getQueryParameter("oauth_verifier"); if (mListener != null) mListener.onSuccess(oauthToken, oauthVerifier); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); mIsAuthenticated = true; removeMe(); return true; // If nothing then its failure } else { // Notify user if (mListener != null) mListener.onFailure( new Exception("Couldn't find the callback URL or oath parameters in response")); if (mBuilder.isActionBarVisible && mBuilder.hideActionBar && getActivity() != null) getActivity().getActionBar().show(); removeMe(); return false; } } }); // Web Crome client to handler progress dialog visibility mTwitterWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { if (mProgressDialog.isShowing()) mProgressDialog.dismiss(); } } }); final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { try { final TwitterFactory twitterFactory = new TwitterFactory(cb.build()); final Twitter twitter = twitterFactory.getInstance(); RequestToken requestToken = null; if (mBuilder.callbackUrl == null) requestToken = twitter.getOAuthRequestToken(); else requestToken = twitter.getOAuthRequestToken(mBuilder.callbackUrl); final RequestToken finalRequestToken = requestToken; handler.post(new Runnable() { @Override public void run() { final String url = finalRequestToken.getAuthorizationURL(); mTwitterWebView.loadUrl(url); } }); } catch (TwitterException e) { e.printStackTrace(); } } }).start(); return mTwitterWebView; }
From source file:com.unisa.flume.source.TwitterSource.java
License:Apache License
/** * The initialization method for the Source. The context contains all the * Flume configuration info, and can be used to retrieve any configuration * values necessary to set up the Source. *///from w ww . j a v a 2 s . co m @Override public void configure(Context context) { consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY_KEY); consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET_KEY); accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN_KEY); accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET_KEY); String keywordString = context.getString(TwitterSourceConstants.KEYWORDS_KEY, ""); if (keywordString.trim().length() == 0) { keywords = new String[0]; } else { keywords = keywordString.split(","); for (int i = 0; i < keywords.length; i++) { keywords[i] = keywords[i].trim(); } } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey(consumerKey); cb.setOAuthConsumerSecret(consumerSecret); cb.setOAuthAccessToken(accessToken); cb.setOAuthAccessTokenSecret(accessTokenSecret); cb.setJSONStoreEnabled(true); cb.setIncludeEntitiesEnabled(true); twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); }
From source file:Control.MyOwnTwitterFactory.java
License:Open Source License
public Twitter createOneTwitterInstance() { Twitter twitter;/*from ww w . j av a 2s . co m*/ ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(APIkeys.getTwitterAPIKey()); builder.setOAuthConsumerSecret(APIkeys.getTwitterAPISecret()); builder.setUseSSL(true); Configuration configuration = builder.build(); twitter4j.TwitterFactory factory = new twitter4j.TwitterFactory(configuration); twitter = factory.getInstance(); return twitter; }
From source file:crawler.TwitterFeed.java
/** * */// ww w .ja v a 2 s . com public void get_tweets() throws SQLException { CSVReader cr = new CSVReader(); ArrayList<String> names = new ArrayList<>(); Map<String, String> name_ticker; names = cr.get_company_names(tickers); System.out.println(names); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey("WNSycI2GS33ZAwHJ9Fb4A"); cb.setOAuthConsumerSecret("BBWeSThT3ZV2g9c5BDuUduDyNAWyzouMI0XjQy7KUc"); cb.setOAuthAccessToken("1852271029-SLfE061bImfcRxWQZpy1pAgpEkfFhg3757Q9JRf"); cb.setOAuthAccessTokenSecret("1uPSfYPbaENtXFYWsryBIAHnUsmG3pT6lGH0NzxTCGW7O"); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); for (String s : names) { String[] temp; if (s.contains(",")) { temp = s.split(","); } else { temp = s.split(" "); } System.out.println( "--------------------------------------------------------------------------------------" + temp[0]); Query query = new Query("#" + temp[0]); query.lang("en"); int numberOfTweets = 500; long lastID = Long.MAX_VALUE; ArrayList<Status> tweets = new ArrayList<>(); while (tweets.size() < numberOfTweets) { if (numberOfTweets - tweets.size() > 100) { query.setCount(100); } else { query.setCount(numberOfTweets - tweets.size()); } try { QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); System.out.println("Gathered " + tweets.size() + " tweets"); for (Status t : tweets) { if (t.getId() < lastID) { lastID = t.getId(); } } } catch (TwitterException te) { System.out.println("Couldn't connect: " + te); } query.setMaxId(lastID - 1); } Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CrawledData", "root", ""); for (int i = 0; i < tweets.size(); i++) { Status t = (Status) tweets.get(i); //GeoLocation loc = t.getGeoLocation(); String user = t.getUser().getScreenName(); String msg = t.getText(); String time = t.getCreatedAt().toString(); //if (loc!=null) { // Double lat = t.getGeoLocation().getLatitude(); // Double lon = t.getGeoLocation().getLongitude(); // System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon); //} //else{ System.out.println(i + " USER: " + user + " wrote: " + msg + " at: " + time); //} try { Class.forName("com.mysql.jdbc.Driver"); PreparedStatement ps = con .prepareStatement("INSERT IGNORE INTO TwitterFeed VALUES (?,?,?,?,?)"); ps.setString(1, s); ps.setString(2, cr.get_ticker_from_company(s)); ps.setString(3, user); ps.setString(4, msg); ps.setString(5, time); int k = ps.executeUpdate(); if (k <= 0) { System.out.println("Entry Unsuccessful"); } else { System.out.println("Entry Successful"); } } catch (ClassNotFoundException | SQLException e) { System.out.println(e); } } con.close(); } }
From source file:datasite.DataSite.java
public static void main(String[] args) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true);//from w w w. j av a 2 s .c o m cb.setOAuthConsumerKey("ConsumerKey"); cb.setOAuthConsumerSecret("ConsumerSecret"); cb.setOAuthAccessToken("AccessToken"); cb.setOAuthAccessTokenSecret("AccessTokenSecret"); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener; listener = new StatusListener() { @Override public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); try (PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter("tweet_input\\tweets.txt", true)))) { //out.println(username); String content = status.getText(); out.println(content + "\n"); //System.out.append( content +"\n"); } catch (IOException ex) { Logger.getLogger(DataSite.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); String keywords[] = { "africa" }; fq.track(keywords); twitterStream.addListener(listener); twitterStream.filter(fq); //twitterStream.(); }
From source file:datasite.SortedUnique.java
public static void main(String[] args) { ConfigurationBuilder confb = new ConfigurationBuilder(); confb.setDebugEnabled(true);/*w ww . j ava 2 s . c om*/ confb.setOAuthConsumerKey("Consumer Key"); confb.setOAuthConsumerSecret("Consumer Secret"); confb.setOAuthAccessToken("Access Token"); confb.setOAuthAccessTokenSecret("Access Token Secret"); TwitterStream twitterStream = new TwitterStreamFactory(confb.build()).getInstance(); StatusListener listener; listener = new StatusListener() { @Override public void onException(Exception arg0) { // TODO Auto-generated method stub } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { // TODO Auto-generated method stub } @Override public void onScrubGeo(long arg0, long arg1) { // TODO Auto-generated method stub } @Override public void onStatus(Status status) { PrintStream out = null; try { User user = status.getUser(); // gets Username String username = status.getUser().getScreenName(); String content = status.getText(); Set<String> userWrds = new HashSet<String>(); // HashSet implements Set Scanner sc = new Scanner(content + user); while (sc.hasNext()) { String word = sc.next(); userWrds.add(word); } out = new PrintStream(new FileOutputStream("tweet_output\\unique.txt", true)); Iterator<String> iter = userWrds.iterator(); for (int i = 1; i <= 1 && iter.hasNext(); i++) //System.out.println(iter.next()); out.println(userWrds.size()); } catch (FileNotFoundException ex) { Logger.getLogger(SortedUnique.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } } @Override public void onTrackLimitationNotice(int arg0) { // TODO Auto-generated method stub } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery fq = new FilterQuery(); String keywords[] = { "africa" }; fq.track(keywords); twitterStream.addListener(listener); twitterStream.filter(fq); //twitterStream.(); }
From source file:de.binfalse.jatter.JatterTools.java
License:Open Source License
/** * Gets the twitter instance./*from ww w . j a va 2s. c o m*/ * * @param conf * the conf * @return the twitter instance */ public static Twitter getTwitterInstance(Config conf) { if (twitter == null) { ConfigurationBuilder confBuilder = new ConfigurationBuilder(); confBuilder.setOAuthConsumerKey(conf.getTwitterConsumerKey()); confBuilder.setOAuthConsumerSecret(conf.getTwitterConsumerSecret()); confBuilder.setOAuthAccessToken(conf.getTwitterAccesstoken()); confBuilder.setOAuthAccessTokenSecret(conf.getTwitterAccesstokenSecret()); twitter = new TwitterFactory(confBuilder.build()).getInstance(); } return twitter; }
From source file:de.dev.eth0.retweeter.AbstractTwitterClient.java
License:BEER-WARE LICENSE
/** * Builds a twitter object to access twitter, including all configs * * @return twitter//w w w .ja v a2 s . c om */ protected Twitter getTwitter() { if (twitter == null) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthAccessToken(config.getAccessToken()); cb.setOAuthAccessTokenSecret(config.getAccessSecret()); cb.setOAuthConsumerKey(config.getConsumerKey()); cb.setOAuthConsumerSecret(config.getConsumerSecret()); twitter = new TwitterFactory(cb.build()).getInstance(); } return twitter; }