List of usage examples for twitter4j.conf ConfigurationBuilder build
public Configuration build()
From source file:com.smart.home.service.TwitterService.java
License:Open Source License
/** * Constructor for twitter service/*from w w w . j a va 2 s. c o m*/ * * @param apiKey twitter API key * @param apiSecret twitter API secret key * @param token twitter access token * @param tokenSecret twitter access token secret */ public TwitterService(String apiKey, String apiSecret, String token, String tokenSecret) { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(apiKey).setOAuthConsumerSecret(apiSecret) .setOAuthAccessToken(token).setOAuthAccessTokenSecret(tokenSecret); TwitterFactory factory = new TwitterFactory(cb.build()); twitter = factory.getInstance(); twitter.directMessages(); }
From source file:com.social.solution.fragment.MyFragment.java
License:Apache License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tweet_list, container, false); lastTimeStamp = System.currentTimeMillis(); mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout); mSwipeLayout.setProgressViewOffset(false, 150, 200); mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override// w w w . j a va2 s. c om public void onRefresh() { long currentTimeStamp = System.currentTimeMillis(); if ((currentTimeStamp - lastTimeStamp) / 1000 > 10) { System.out.println("load recent pranjal"); LoadRecentTweets(); } } }); Activity parentActivity = getActivity(); Fabric.with(getActivity(), new TweetUi()); Bundle bd = getArguments(); if (bd != null) { filterTweets = bd.getBoolean("filter"); position = bd.getInt("position"); } else { filterTweets = false; position = 0; } //Toast.makeText(this, "Filter : "+filterTweets+" Position : "+position, Toast.LENGTH_SHORT).show(); System.out.println("Filter : " + filterTweets + " Position : " + position); linlaHeaderProgress = (LinearLayout) view.findViewById(R.id.linlaHeaderProgress); listView = (ObservableListView) view.findViewById(R.id.mylist); final EnumSet<RequestParameters.NativeAdAsset> desiredAssets = EnumSet.of( RequestParameters.NativeAdAsset.TITLE, RequestParameters.NativeAdAsset.TEXT, RequestParameters.NativeAdAsset.ICON_IMAGE, RequestParameters.NativeAdAsset.MAIN_IMAGE, RequestParameters.NativeAdAsset.CALL_TO_ACTION_TEXT); mRequestParameters = new RequestParameters.Builder() //.location(location) .keywords("food").desiredAssets(desiredAssets).build(); setmydata(listView, inflater.inflate(R.layout.padding, listView, false)); listView.setAdapter(tweetadapter); linlaHeaderProgress.setBackgroundColor(-1); linlaHeaderProgress.setVisibility(View.VISIBLE); if (parentActivity instanceof ObservableScrollViewCallbacks) { // Scroll to the specified position after layout Bundle args = getArguments(); if (args != null && args.containsKey(ARG_INITIAL_POSITION)) { final int initialPosition = args.getInt(ARG_INITIAL_POSITION, 0); ScrollUtils.addOnGlobalLayoutListener(listView, new Runnable() { @Override public void run() { // scrollTo() doesn't work, should use setSelection() listView.setSelection(initialPosition); } }); } // TouchInterceptionViewGroup should be a parent view other than ViewPager. // This is a workaround for the issue #117: // https://github.com/ksoichiro/Android-ObservableScrollView/issues/117 listView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.root)); listView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity); } ConfigurationBuilder config = new ConfigurationBuilder().setOAuthConsumerKey(custkey) .setOAuthConsumerSecret(custsecret).setOAuthAccessToken(accesstoken) .setOAuthAccessTokenSecret(accesssecret); twitter1 = new TwitterFactory(config.build()).getInstance(); tweetlist = new ArrayList<Tweet>(); loadingTweets = new ArrayList<Tweet>(); lastDisplayTweetId = Long.MAX_VALUE; firstDisplayTweetId = Long.MIN_VALUE; return view; }
From source file:com.socialnetwork.abhishekchandale.snloginlib.twitter.TwitterSocialNetwork.java
License:Open Source License
private void initTwitterClient() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(mConsumerKey); builder.setOAuthConsumerSecret(mConsumerSecret); String accessToken = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_TOKEN, null); String accessTokenSecret = mSharedPreferences.getString(SAVE_STATE_KEY_OAUTH_SECRET, null); TwitterFactory factory = new TwitterFactory(builder.build()); if (TextUtils.isEmpty(accessToken) && TextUtils.isEmpty(accessTokenSecret)) { mTwitter = factory.getInstance(); } else {//from w ww . j av a 2 s.c om mTwitter = factory.getInstance(new twitter4j.auth.AccessToken(accessToken, accessTokenSecret)); } }
From source file:com.soomla.profile.social.twitter.SoomlaTwitter.java
License:Apache License
/** * {@inheritDoc}/*from www . ja va 2 s .com*/ */ @Override public void configure(Map<String, String> providerParams) { autoLogin = false; if (providerParams != null) { twitterConsumerKey = providerParams.get("consumerKey"); twitterConsumerSecret = providerParams.get("consumerSecret"); // extract autoLogin String autoLoginStr = providerParams.get("autoLogin"); autoLogin = autoLoginStr != null && Boolean.parseBoolean(autoLoginStr); } SoomlaUtils.LogDebug(TAG, String.format("ConsumerKey:%s ConsumerSecret:%s", twitterConsumerKey, twitterConsumerSecret)); if (TextUtils.isEmpty(twitterConsumerKey) || TextUtils.isEmpty(twitterConsumerSecret)) { SoomlaUtils.LogError(TAG, "You must provide the Consumer Key and Secret in the SoomlaProfile initialization parameters"); isInitialized = false; } else { isInitialized = true; } oauthCallbackURL = "oauth://soomla_twitter" + twitterConsumerKey; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(twitterConsumerKey); configurationBuilder.setOAuthConsumerSecret(twitterConsumerSecret); Configuration configuration = configurationBuilder.build(); twitter = new AsyncTwitterFactory(configuration).getInstance(); if (!actionsListenerAdded) { SoomlaUtils.LogWarning(TAG, "added action listener"); twitter.addListener(actionsListener); actionsListenerAdded = true; } }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
/** * Function to login twitter// w w w . java 2 s.com * */ private void loginToTwitter() { // Check if already logged in if (!isTwitterLoggedInAlready()) { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY); builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET); Configuration configuration = builder.build(); TwitterFactory factory = new TwitterFactory(configuration); twitter = factory.getInstance(); try { requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL); this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL()))); } catch (TwitterException e) { e.printStackTrace(); } } else { // user already logged into twitter Toast.makeText(TraqComplaintTaxi.this, "Already Logged into twitter", Toast.LENGTH_SHORT).show(); /* Get Access Token after login*/ /*try { 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(); // 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()); }*/ } }
From source file:com.speed.traquer.app.TraqComplaintTaxi.java
private void checkTwitterID() { /* Get Access Token after login*/ try {//from w w w.j a v a2s. c om 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.stronquens.amgtwitter.ControllerOAuth.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www .j a va2 s.c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TwitterException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Parametros del request HttpSession sesion = request.getSession(); String verifier = request.getParameter("verifier"); String op = request.getParameter("op"); // Definimos variables RequestToken requestToken = null; AccessToken accessToken = null; Twitter OAuthTwitter = null; String url = null; // Devolemos la url generada if ((verifier == null || verifier == "") && "url".equalsIgnoreCase(op)) { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf") .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW"); OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance(); sesion.setAttribute("twitter", OAuthTwitter); try { requestToken = OAuthTwitter.getOAuthRequestToken(); sesion.setAttribute("requestToken", requestToken); url = requestToken.getAuthenticationURL(); out.println("{\"url\":\"" + url + "\"}"); } catch (TwitterException ex) { } } // Devolvemos el acces token generado if (verifier != null && verifier.length() > 0) { OAuthTwitter = (Twitter) sesion.getAttribute("twitter"); requestToken = (RequestToken) sesion.getAttribute("requestToken"); accessToken = OAuthTwitter.getOAuthAccessToken(requestToken, verifier); sesion.setAttribute("accesToken", accessToken); sesion.removeAttribute("twitter"); sesion.removeAttribute("requestToken"); out.println("{\"token\":\"" + accessToken.getToken() + "\",\"secret\":\"" + accessToken.getTokenSecret() + "\"}"); } } }
From source file:com.stronquens.amgtwitter.ControllerTwitter.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . jav a2 s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Obtenemos parametros de la peticion String op = request.getParameter("op"); String accesToken = request.getParameter("token"); String accesTokenSecret = request.getParameter("secret"); // Inicializamos variables String jsonResult = ""; Twitter twitter = null; ConfigurationBuilder configBuilder = new ConfigurationBuilder(); Gson gson = new GsonBuilder().setDateFormat("dd/MM/yyyy HH:mm:ss").create(); // Se crea la instancia de twitter segun los parametros de ususario if (!"".equalsIgnoreCase(accesToken) && !"".equalsIgnoreCase(accesTokenSecret)) { try { configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf") .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW") .setOAuthAccessToken(accesToken).setOAuthAccessTokenSecret(accesTokenSecret); twitter = new TwitterFactory(configBuilder.build()).getInstance(); } catch (Exception e) { System.out.println(e); } } else { try { configBuilder.setDebugEnabled(true).setOAuthConsumerKey("nyFJnGU5NfN7MLuGufXhAcPTf") .setOAuthConsumerSecret("QOofP3lOC7ytKutfoexCyh3zDVIFNHoMuuuKI98S78XmeGvqgW"); twitter = new TwitterFactory(configBuilder.build()).getInstance(); } catch (Exception e) { System.out.println(e); } } // Se realizan las diferentes operaciones switch (op) { case "timeline": try { Paging pagina = new Paging(); pagina.setCount(25); ResponseList listado = twitter.getHomeTimeline(pagina); jsonResult = gson.toJson(listado); } catch (TwitterException ex) { System.out.println(ex); } break; case "usersettings": try { jsonResult = gson.toJson(twitter.showUser(twitter.getId())); } catch (TwitterException ex) { System.out.println(ex); } break; case "pruebas": try { jsonResult = gson.toJson(twitter.showUser(twitter.getId())); } catch (TwitterException ex) { System.out.println(ex); } break; default: jsonResult = "{\"eror\":\"la operacion no existe\"}"; } // Se devuelven los valores out.println(jsonResult); } }
From source file:com.telefonica.iot.cygnus.sources.TwitterSource.java
License:Open Source License
@Override public void configure(Context context) { consumerKey = context.getString("consumerKey"); consumerSecret = context.getString("consumerSecret"); accessToken = context.getString("accessToken"); accessTokenSecret = context.getString("accessTokenSecret"); LOGGER.info("Consumer Key: '" + consumerKey + "'"); LOGGER.info("Consumer Secret: '" + consumerSecret + "'"); LOGGER.info("Access Token: '" + accessToken + "'"); LOGGER.info("Access Token Secret: '" + accessTokenSecret + "'"); String southWestLatitude;//from ww w . j a va2 s . co m String southWestLongitude; String northEastLatitude; String northEastLongitude; String keywords; //Top-left coordinate southWestLatitude = context.getString("south_west_latitude"); southWestLongitude = context.getString("south_west_longitude"); LOGGER.info("South-West coordinate: '" + southWestLatitude + " " + southWestLongitude + "'"); //Bottom-right coordinate northEastLatitude = context.getString("north_east_latitude"); northEastLongitude = context.getString("north_east_longitude"); LOGGER.info("North-East coordinate: '" + northEastLatitude + " " + northEastLongitude + "'"); keywords = context.getString("keywords"); LOGGER.info("Keywords: '" + keywords + "'"); if (southWestLatitude != null && southWestLongitude != null && northEastLatitude != null && northEastLongitude != null) { double latitude1 = Double.parseDouble(southWestLatitude); double longitude1 = Double.parseDouble(southWestLongitude); double latitude2 = Double.parseDouble(northEastLatitude); double longitude2 = Double.parseDouble(northEastLongitude); boundingBox = new double[][] { new double[] { longitude1, latitude1 }, // south-west new double[] { longitude2, latitude2 } // north-east }; LOGGER.info("Coordinates: '" + boundingBox[0][0] + " " + boundingBox[0][1] + " " + boundingBox[1][0] + " " + boundingBox[1][1] + "'"); haveFilters = true; haveCoordinateFilter = true; } if (keywords != null) { if (keywords.trim().length() != 0) { splitKeywords = keywords.split(","); for (int i = 0; i < splitKeywords.length; i++) { splitKeywords[i] = splitKeywords[i].trim(); } LOGGER.info("keywords: {}", Arrays.toString(splitKeywords)); haveFilters = true; haveKeywordFilter = true; } } maxBatchSize = context.getInteger("maxBatchSize", maxBatchSize); maxBatchDurationMillis = context.getInteger("maxBatchDurationMillis", maxBatchDurationMillis); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true); cb.setOAuthConsumerKey(consumerKey); cb.setOAuthConsumerSecret(consumerSecret); cb.setOAuthAccessToken(accessToken); cb.setOAuthAccessTokenSecret(accessTokenSecret); cb.setJSONStoreEnabled(true); twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); }
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// www.j av a 2 s . 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"; } }