List of usage examples for twitter4j Twitter search
QueryResult search(Query query) throws TwitterException;
From source file:com.mycompany.dovetune.SearchTwitter.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w . j a v a2 s .c om*/ * * @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 { // HttpSession session = request.getSession(false); // if(session != null){ Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); if (twitter != null) { String soundcloudUrl = request.getParameter("soundcloudUrl"); String songName = request.getParameter("songName"); out.println(twitter.toString()); int i = songName.indexOf("- "); String song = songName.substring(i + 2); try { Query query = new Query("(#" + song + ") OR ( " + songName + ") OR (#DoveTune)"); QueryResult result = twitter.search(query); List<Status> tweets = result.getTweets(); // String list = "<ulid='tweetList'>"; String list = ""; for (Status tweet : tweets) { list += "<li><img class='profileImg' src='" + tweet.getUser().getProfileImageURL() + "' title='Profile Image' alt='Profile Image'><strong>" + tweet.getUser().getName() + " @" + tweet.getUser().getScreenName() + "</strong> - " + tweet.getText() + "</li>"; } list = list.replace("#" + song, "<strong class='hashtags'>#" + song + "</strong>"); list = list.replace("#DoveTune", "<strong class='hashtags'>#DoveTune</strong>"); list = list.replace("#SoundCloud", "<strong class='hashtags'>#SoundCloud</strong>"); String songL = song; songL = songL.toLowerCase(); list = list.replace("#" + songL, "<strong class='hashtags'>#" + songL + "</strong>"); if (list.equals("")) { list = "<li>There are no tweets to display. Tweet your own!</li>"; } request.setAttribute("soundcloudUrl", soundcloudUrl); request.setAttribute("songName", songName); request.setAttribute("song", songName); request.setAttribute("list", list); } catch (TwitterException te) { te.printStackTrace(); out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } } else { String list = "<ul><li>In order to view tweets, please sign in to <a href=\"SignIn\" title=\"Sign in to Twitter\"><strong class=\"notSignedIn\">Twitter</strong></a></li></ul>"; request.setAttribute("list", list); } request.getRequestDispatcher("details.jsp").forward(request, response); }
From source file:com.mycompany.twittersearch.SearchTwitter.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . ja v 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, TwitterException { Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); out.println(twitter.toString()); String searchItem = request.getParameter("term"); try { Query query = new Query(searchItem); QueryResult result = twitter.search(query); List<Status> tweets = result.getTweets(); String list = ""; for (Status tweet : tweets) { list += "@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + "<br>"; } request.setAttribute("list", list); } catch (TwitterException te) { te.printStackTrace(); out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } request.getRequestDispatcher("showTweets.jsp").forward(request, response); }
From source file:com.ontotext.s4.TwitterVisualization.downloadTweets.SearchTweets.java
License:Open Source License
/** * This method executes search query on Twitter. The results are saved into the preconfigured result folder. * @param queryString/* w w w . j a va2s. co m*/ * the search query string. For more information refer to https://dev.twitter.com/docs/using-search * @throws TwitterException * any problem related to authentication, communication, search, etc. */ public void search(String queryString) throws TwitterException { // configures twitter API keys Twitter twitter = ConfigurateTwitterAccount(); // preparint the query Query query = new Query(queryString); // search in both popular and recent tweets query.resultType(Query.MIXED); // restrict result to English language query.lang("en"); // result of the query QueryResult result; do { logger.debug(query); // executing the query result = twitter.search(query); // collect all tweets available List<Status> tweets = result.getTweets(); // save each tweet into a file for (Status tweet : tweets) { saveTweetIntoFile(tweet); } } // handle the paging of the results while ((query = result.nextQuery()) != null); }
From source file:com.schnee.tweetgeister.visualization.TweetgeisterBalloonLayout.java
License:Open Source License
/** * // w w w.j av a 2 s.c o m */ private void createTree() { try { Twitter twitter = new TwitterFactory().getInstance(); List<Tweet> allTweets = new ArrayList<Tweet>(); String qString = "bp"; Query query = new Query(qString); query.setRpp(100); query.setLang("en"); int hits = 100; int page = 1; while (allTweets.size() < 1400 && page < 16 && hits == 100) { query.setPage(page); // System.out.println(query.toString()); QueryResult result = twitter.search(query); List<Tweet> tweets = result.getTweets(); allTweets.addAll(tweets); hits = tweets.size(); System.out.println("page: " + page + " hits: " + hits + " all tweets:" + allTweets.size()); page++; } System.out.println("hits: " + allTweets.size()); Set<CharSequence> inputSet = new HashSet<CharSequence>(); for (Tweet tweet : allTweets) { inputSet.add(tweet.getText()); } Clusterer cl = new Clusterer(inputSet, TokenizedCharSequence.TOKENIZER_FACTORY); com.schnee.tweetgeister.data.Tree<CharSequence> mindmap = cl.buildTree(); fillTree(mindmap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
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. jav a 2s . 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.tweet.analysis.SearchTweets.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param args search query/*from w ww . j a va 2s . c om*/ */ public static void main(String[] args) { if (args.length < 1) { //System.out.println("java twitter4j.examples.search.SearchTweets [query]"); //System.exit(-1); } Twitter twitter = new TwitterFactory().getInstance(); //twitter.getFollowersList("Kuldeep.loveiit"); try { Query query = new Query("Modi"); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }
From source file:com.twit.AppCrawler.java
public static void main(String[] args) throws TwitterException { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance(); CidadeController cidadeController = new CidadeController(new Cidade()); List<Cidade> cidades = cidadeController.findEntities(); String searchStr = "\"#viagem\" "; for (Cidade cidade : cidades) { //searchStr += "\"" + cidade.getNome() + "\" "; }//from www . ja v a2 s . c o m // Create a Query object. Query query = new Query(searchStr); // Send API request to execute a search with the given query. QueryResult result = twitter.search(query); // Display search results. for (Status status : result.getTweets()) { System.out.println("\n@" + status.getUser().getName() + ": " + status.getText()); } }
From source file:controllers.modules.CorpusModule.java
License:Open Source License
public static Result update(UUID corpus) { OpinionCorpus corpusObj = null;//from w w w . j av a 2 s. co m if (corpus != null) { corpusObj = fetchResource(corpus, OpinionCorpus.class); } OpinionCorpusFactory corpusFactory = null; MultipartFormData formData = request().body().asMultipartFormData(); if (formData != null) { // if we have a multi-part form with a file. if (formData.getFiles() != null) { // get either the file named "file" or the first one. FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"), Iterables.getFirst(formData.getFiles(), null)); if (filePart != null) { corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile()) .setFormat(FilenameUtils.getExtension(filePart.getFilename())); } } } else { // otherwise try as a json body. JsonNode json = request().body().asJson(); if (json != null) { OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class); if (optionsVM != null) { corpusFactory = optionsVM.toFactory(); } else { throw new IllegalArgumentException(); } if (optionsVM.grabbers != null) { if (optionsVM.grabbers.twitter != null) { if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) { TwitterFactory tFactory = new TwitterFactory(); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer( Play.application().configuration().getString("twitter4j.oauth.consumerKey"), Play.application().configuration().getString("twitter4j.oauth.consumerSecret")); twitter.setOAuthAccessToken(new AccessToken( Play.application().configuration().getString("twitter4j.oauth.accessToken"), Play.application().configuration() .getString("twitter4j.oauth.accessTokenSecret"))); Query query = new Query(optionsVM.grabbers.twitter.query); query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10)); query.resultType(Query.RECENT); if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) { query.lang(corpusFactory.getLanguage()); } else if (corpusObj != null) { query.lang(corpusObj.getLanguage()); } QueryResult qr; try { qr = twitter.search(query); } catch (TwitterException e) { throw new IllegalArgumentException(); } StringBuilder tweets = new StringBuilder(); for (twitter4j.Status status : qr.getTweets()) { // quote for csv, normalize space, and remove higher unicode characters. String text = StringEscapeUtils.escapeCsv(StringUtils .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", ""))); tweets.append(text + System.lineSeparator()); } corpusFactory.setContent(tweets.toString()); corpusFactory.setFormat("txt"); } } } } else { // if not json, then just create empty. corpusFactory = new OpinionCorpusFactory(); } } if (corpusFactory == null) { throw new IllegalArgumentException(); } if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) { corpusFactory.setTitle("Untitled corpus"); } corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em()); DocumentCorpusModel corpusVM = null; corpusObj = corpusFactory.create(); if (!em().contains(corpusObj)) { em().persist(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return created(corpusVM.asJson()); } for (PersistentObject obj : corpusObj.getDocuments()) { if (em().contains(obj)) { em().merge(obj); } else { em().persist(obj); } } em().merge(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return ok(corpusVM.asJson()); }
From source file:cp.Demo.java
private void MoviesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_MoviesListValueChanged // Obtain the movie object Movie mov;//from www. j av a 2s. co m try { mov = (Movie) MoviesList.getSelectedValue(); System.out.println(mov.getApiQuery()); } catch (Exception ex) { PosterLabel.setIcon(null); PosterLabel.setText("Movie not found"); return; } // Display the movie poster try { // Load the movie poster URL url = new URL(mov.getPosterLink()); ImageIcon img = new ImageIcon(url); // Rescale the movie poster int w = img.getIconWidth(); int h = img.getIconHeight(); int labelH = MovieTabs.getHeight() - 36; img.setImage(img.getImage().getScaledInstance(labelH * w / h, labelH, Image.SCALE_SMOOTH)); // Put the movie poster into the label, and change the text PosterLabel.setIcon(img); PosterLabel.setText(""); } catch (Exception ex) { // If for some reason the poster isn't available, indicate this PosterLabel.setIcon(null); PosterLabel.setText("Poster could not be displayed"); } // Display tweets about the movie try { // clear out the tweets TweetsArea.setText(""); // The factory instance is re-useable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query(mov.getTitle()); QueryResult result = twitter.search(query); String tweet; for (Status status : result.getTweets()) { tweet = String.format("[%s] @%s tweeted %s\n", status.getCreatedAt(), status.getUser().getScreenName(), status.getText()); TweetsArea.append(tweet); } } catch (TwitterException ex) { TweetsArea.setText(ex.toString()); } // Display reviews of the movie try { ReviewsArea.setText(""); for (Review rev : (new ReviewRequest(mov.getMovie())).getReviews()) { String review = String.format("[%s] (by %s, %s)\n%s\n%s\n\n", rev.getDateOfReview(), rev.getCritic(), rev.getPublication(), rev.getQuote(), rev.getReviewLinkUrl()); ReviewsArea.append(review); } } catch (IOException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex); } catch (ReviewRequest.ReviewRequestException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:crawler.TwitterFeed.java
/** * *//*w ww.j a v a 2 s. c o m*/ 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(); } }