List of usage examples for twitter4j.conf ConfigurationBuilder setDebugEnabled
public ConfigurationBuilder setDebugEnabled(boolean debugEnabled)
From source file:com.smart.home.service.TwitterService.java
License:Open Source License
/** * Constructor for twitter service// w ww . j a v a 2s . co 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.stronquens.amgtwitter.ControllerOAuth.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from www. j a v a 2 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./* www . jav a 2 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;// w w w . ja v a2 s . c o 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/*from w w w . j ava 2 s . c o 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"; } }
From source file:com.tweetmyhome.TweetMyHome.java
public TweetMyHome() throws TweetMyHomeException, IOException, TweetStringException { Log.setLogger(new MyCustomLogger()); p = new TweetMyHomeProperties(); if (!p.isFirstTimeCreated()) { if (p.getValueByKey(Key.debuggin).equalsIgnoreCase("true")) { Log.set(Log.LEVEL_DEBUG);// w w w.j a va 2 s . co m Log.set(Log.LEVEL_TRACE); } else { Log.set(Log.LEVEL_INFO); } } else { File file = new File(TweetMyHomeProperties.FILE_NAME); info(String.format("Properties file created at: %s", file.getAbsolutePath())); info(String.format("Please edit '%s' to correct aplication function", TweetMyHomeProperties.FILE_NAME)); info("Exiting aplication..."); System.exit(0); } tweetCount = new TweetMensajeCount(COUNT_FILE); tmh_device_xml = XMLFilesManager.getTweetMyHomeDevices(); if (tmh_device_xml == null) { throw new TweetMyHomeException( "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + "] file"); } tmh_dic_xml = XMLFilesManager.getTweetMyHomeDictionaryCommand(); if (tmh_dic_xml == null) { throw new TweetMyHomeException( "Fail to read [" + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "] file"); } tweetDictionary = new TweetStringDictionary(tmh_dic_xml); trace("XML Files already Readed [" + XMLFilesManager.TWEET_MY_HOME_DEVICES_XML_FILE + "," + XMLFilesManager.TWEET_MY_HOME_DICTIONARY_XML_FILE + "]"); if (!NetUtil.isConnectedToInternet() && INTERNET_REQUIRED_DEV) { throw new TweetMyHomeException("Not Connected to Internet"); } trace("Internet conecction detected"); trace("Trying to connect to DBMS..."); db = new TweetMyHomeDatabase(p); if (!db.connect()) { throw new TweetMyHomeException("Not Connected to DBMS"); } trace("Connected to DBMS"); db.addTweetMyHomeDevices(tmh_device_xml); if (RASPBERRY_ON_BOARD) { if (p.getValueByKey(Key.arduinoIOBridge).equalsIgnoreCase("true")) { throw new TweetMyHomeException("Arduino not supported..."); } else { iob = new RaspberryPiGPIO(tmh_device_xml); } if (iob != null) { iob.addIODeviceListener(this); iob.connect(); trace("GPIO Link established"); com = new Comunity(false, iob); sec = new Security(false, iob); //sect = new SecurityThreshhold(sec); trace("Security , Security threshold & Comunity initiated"); } } else { warn("Raspberry PI GPIO omited. APP prob. won't work well"); } sect = new SecurityThreshhold(sec); trace("Setting Twitter OAuth parameters..."); ConfigurationBuilder cb1 = new ConfigurationBuilder(); cb1.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug") .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp") .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp") .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg"); ConfigurationBuilder cb2 = new ConfigurationBuilder(); cb2.setDebugEnabled(false).setOAuthConsumerKey("RaTG5hw5OwhQQugghtLthG0ug") .setOAuthConsumerSecret("brJ0vcrdGnCHMTxDCmKoThPpJubD6e2xol5WjdO9bBa19nzkXp") .setOAuthAccessToken("3236804811-V6MOxfbox4jVylx6pDjkR9UrEpuPzZyOwkaVIWp") .setOAuthAccessTokenSecret("33HvizelxmGN700a7pLa6YBKv0l2uTMLoJK593MlXellg"); TwitterFactory tf = new TwitterFactory(cb1.build()); TwitterStreamFactory sf = new TwitterStreamFactory(cb2.build()); trace("Connecting to Twitter STREAM API..."); tws = sf.getInstance(); tws.addListener(this); tws.user(); trace("Connecting to Twitter REST API..."); tw = tf.getInstance(); debug("Contructor fi"); /*----------------NEEDED WORK TO DO-------------------*/ // integrityCheckSuperAdmin(); }
From source file:com.twitter.storm.hashtag2.TwitterSampleSpout.java
License:Apache License
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { queue = new LinkedBlockingQueue<Status>(1000); _collector = collector;/*w w w. ja va 2s .c om*/ StatusListener listener = new StatusListener() { public void onStatus(Status status) { queue.offer(status); } public void onDeletionNotice(StatusDeletionNotice sdn) { } public void onTrackLimitationNotice(int i) { } public void onScrubGeo(long l, long l1) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning arg0) { // TODO Auto-generated method stub } }; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret) .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret); _twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); _twitterStream.addListener(listener); if (keyWords.length == 0) { _twitterStream.sample(); } else { FilterQuery query = new FilterQuery().track(keyWords); _twitterStream.filter(query); } }
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"); }// w w w. ja v a 2 s .c o 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.wavemaker.runtime.ws.TwitterFeedService.java
License:Open Source License
private Twitter getTwitter() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(OAuthConsumerKey).setOAuthConsumerSecret(OAuthConsumerSecret) .setOAuthAccessToken(OAuthAccessToken).setOAuthAccessTokenSecret(OAuthAccessTokenSecret); return new TwitterFactory(cb.build()).getInstance(); }
From source file:com.wimbli.serverevents.Register.java
License:Open Source License
private static void execute() { try {//w w w. j a v a2s .c o m ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("QyuUqx8UFaRLMWORQinphg") .setOAuthConsumerSecret("EWORHYNo3JkJgvihiGwFL8tWNHExyhWFilR1Q"); twitter = new TwitterFactory(cb.build()).getInstance(); accessToken = null; try { // get request token. // this will throw IllegalStateException if access token is already available requestToken = twitter.getOAuthRequestToken(); msg("Open the following URL and grant access to ServerEvents:"); msg(requestToken.getAuthorizationURL()); outputToFile("Open the following URL and grant access to ServerEvents: \n" + requestToken.getAuthorizationURL()); msg("For convenience, this URL has also been output to a file: " + outFile); if (cmdLine) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken) { System.out.print( "Enter the PIN(if available) and hit enter after you have granted access. [PIN]:"); String pin = br.readLine(); tryPin(pin); } } } catch (IllegalStateException ie) { // access token is already available, or consumer key/secret is not set. if (!twitter.getAuthorization().isEnabled()) { msg("OAuth consumer key/secret is not set."); exit(-1); } } } catch (TwitterException te) { msg("Failed to get timeline: " + te.getMessage()); msg("Try revoking access to the ServerEvents application from your Twitter settings page."); exit(-1); } catch (IOException ioe) { msg("Failed to read the system input."); exit(-1); } if (cmdLine) exit(0); }