List of usage examples for twitter4j Query Query
public Query(String query)
From source file:cd.examentwitter.Metodos.java
/** * Metodo para buscar una determinada secuencia caracteres por todo Twitter */// w w w . j a v a2s . c o m public void search() { try { String search = JOptionPane.showInputDialog("Qu secuencia de caracteres desea buscar?"); QueryResult result = twitter.search(new Query(search)); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ": " + status.getText()); } } catch (TwitterException ex) { Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:ch.schrimpf.core.TwitterCrawler.java
License:Open Source License
/** * @param queryString describes keywords and filters * @return an initialized Query/*from w w w . j a v a 2s. co m*/ */ private Query initQuery(String queryString) { Query query = new Query(queryString); try { Properties prop = new Properties(); prop.load(new FileInputStream("easyTwitterCrawler.properties")); query.setCount(Integer.parseInt(prop.getProperty("queryLimit"))); query.setLocale(prop.getProperty("locale")); query.setLang(prop.getProperty("lang")); GeoLocation location = new GeoLocation(Double.parseDouble(prop.getProperty("latitude")), Double.parseDouble(prop.getProperty("longitude"))); double radius = Double.parseDouble(prop.getProperty("radius")); query.setGeoCode(location, radius, Query.KILOMETERS); } catch (IOException e) { // Properties could not be load query.setCount(DEFAULT_QUERY_LIMIT); query.setLocale(DEFAULT_LOCALE); query.setLang(DEFAULT_LANG); query.setGeoCode(DEFAULT_GEO_LOCATION, DEFAULT_RADIUS, Query.KILOMETERS); } return query; }
From source file:Classes.TwitterPull.java
public void retrieveTweets() throws TwitterException { Query query = new Query("\"" + this.queryString + "\""); query.setLang("en"); query.setCount(100);/* ww w . jav a 2 s.com*/ QueryResult result; int i = 0; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { String t = tweet.getText().replaceAll("\n", "").replaceAll("\r", ""); // appendTweetDocument(t); retrievedTweets.add(t); } i++; } while ((query = result.nextQuery()) != null && i < 50); }
From source file:co.uk.socialticker.ticker.TickerActivity.java
License:Open Source License
/** * Test code to try and retrieve some data from twitter in a search! * @throws TwitterException //from w ww .j a v a2s.c om * */ public JSONArray doSearch(View v) throws TwitterException { if (mApiClient != null || debugOn) { // The factory instance is re-useable and thread safe. //get the hashtag - check to make sure if returned value is set to something with a length JSONArray jsA = new JSONArray(); String qHash = p.getString(KEY_CAST_HASHTAG, ""); Log.d(TAG, "Hash to search: " + qHash); if (qHash.length() == 0) { Toast.makeText(this, "The hashtag looks like it is not setup. May want to fix that", Toast.LENGTH_LONG).show(); } else { 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); //Query query = new Query("#MOTD2014"); Query query = new Query(qHash); query.count(TWEET_COUNT); QueryResult result = twitter.search(query); for (twitter4j.Status status : result.getTweets()) { MediaEntity[] me = status.getMediaEntities(); String meUrl = ""; if (me.length > 0) { Log.d(TAG, "me[0] : " + me[0].getMediaURL()); //meUrl = me[0].getDisplayURL(); //sjort URl = useless. meUrl = me[0].getMediaURL(); } JSONObject jso = tweetJSON(status.getUser().getScreenName(), status.getUser().getName() // , status.getUser().getOriginalProfileImageURL() //Whatever the size was it was uploaded in // , status.getUser().getProfileImageURL() // 48x48 , status.getUser().getBiggerProfileImageURL() // 73x73 , status.getText(), status.getCreatedAt().toString(), status.getFavoriteCount(), status.getRetweetCount(), meUrl); jsA.put(jso); } } catch (TwitterException e) { // Error in updating status Log.d("Twitter Search Error", e.getMessage()); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } } ; return jsA; } else { Toast.makeText(this, "You do not seem to be connected to a cast device...", Toast.LENGTH_LONG).show(); return null; } }
From source file:Collector.TweetCollector.java
public static List<Status> getTweets(final String q) { Timer timer = new Timer(); TimerTask hourlyTask = new TimerTask() { @Override/*from ww w. j a v a 2 s . c om*/ public void run() { long amountOfTweets = 0; try { long maxID = -1; Query query = new Query(q); //printTimeLine(query); Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchLimit = rateLimitStatus.get("/search/tweets"); for (int batchNumber = 0; MAX_QUERIES < 10; batchNumber++) { System.out.printf("\n\n!!! batch %d\n\n", batchNumber); if (searchLimit.getRemaining() == 0) { // so as to not get blocked by twitter Thread.sleep(searchLimit.getSecondsUntilReset() + 3 * 1001); } query.setCount(TWEETS_PER_QUERY);// constant value of 100 query.setResultType(Query.ResultType.recent); query.setLang("en");// only english tweets if (maxID != -1) { query.setMaxId(maxID - 1);// so the first querys not set to previous max } QueryResult result = twitter.search(query); if (result.getTweets().size() == 0) { break; } for (Status s : result.getTweets()) { amountOfTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } storeTweet(s);// where stored in db System.out.printf("At%s : %s\n", // debugging purposes s.getCreatedAt().toString(), s.getText()); searchLimit = result.getRateLimitStatus(); //resets System.out.printf("\n\nA total of %d tweet retrieved\n", amountOfTweets); } } } catch (TwitterException te) { System.out.println("Error Code :" + te.getErrorCode()); System.out.println("Exception Code " + te.getExceptionCode()); System.out.println("Status Code " + te.getStatusCode()); if (te.getStatusCode() == 401) { System.out.println("Twitter Error :\nAuthentication " + "credentials (https://dev.twitter.com/auth) " + " are either missing of incorrect, " + "\nplease check consumer key /secret"); } } catch (InterruptedException ex) { } } }; // schedule the task to run starting now and then every hour... timer.schedule(hourlyTask, 0l, 1000 * 60 * 60); return statuses; }
From source file:Collector.TweetCollector.java
public static List<Status> printTimeLine(String account) { try {/*from w w w . j a v a2 s . com*/ Query query = new Query(account); QueryResult result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } return tweets; } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } return null; }
From source file:collector.TwitterCollector.java
public LinkedHashSet<Tweet> search(String queryExpression, int maxResults) { Query query = new Query(queryExpression); int numberOfTweets = maxResults;//512; long lastID = Long.MAX_VALUE; query = query.lang("pt"); List<Status> tweets = new ArrayList<>(); boolean finish = false; while ((tweets.size() < numberOfTweets) && !finish) { System.out.print("."); if (numberOfTweets - tweets.size() > 100) {//100) { query.setCount(100);//100); } else {/* ww w . jav a 2 s .co m*/ query.setCount(numberOfTweets - tweets.size()); } try { QueryResult result = twitter.search(query); List<Status> resultList = result.getTweets(); if (resultList == null || resultList.isEmpty()) { finish = true; System.out.println("no foram encontrados mais tweets"); } else { tweets.addAll(resultList); for (Status t : tweets) { if (t.getId() < lastID) { lastID = t.getId(); } } } } catch (TwitterException ex) { System.err.println(ex.getMessage()); } query.setMaxId(lastID - 1); } LinkedHashSet<Tweet> out = new LinkedHashSet<>(); for (Status status : tweets) { if (!status.getText().startsWith("RT")) { TwitterUser user; user = new TwitterUser().addID(status.getUser().getId()).addName(status.getUser().getName()) .addLocation(status.getUser().getLocation()).addDateSignin(status.getUser().getCreatedAt()) .addCountTweets(status.getUser().getStatusesCount()) .addCountFavorites(status.getUser().getFavouritesCount()) .addCountFriends(status.getUser().getFriendsCount()) .addCountFollowers(status.getUser().getFollowersCount()); Tweet tweet = new Tweet().addUser(user).addText(status.getText()).addID(status.getId()) .addDate(status.getCreatedAt()) .addLatitude(status.getGeoLocation() != null ? status.getGeoLocation().getLatitude() : Double.MAX_VALUE) .addLongitude(status.getGeoLocation() != null ? status.getGeoLocation().getLongitude() : Double.MAX_VALUE); out.add(tweet); } } return out; }
From source file:com.concursive.connect.web.modules.profile.jobs.TwitterQueryJob.java
License:Open Source License
public void execute(JobExecutionContext context) throws JobExecutionException { long startTime = System.currentTimeMillis(); LOG.debug("Starting job..."); SchedulerContext schedulerContext = null; Connection db = null;/*from w w w. j av a 2s . c om*/ try { schedulerContext = context.getScheduler().getContext(); // Determine if the twitter hash is enabled ApplicationPrefs prefs = (ApplicationPrefs) schedulerContext.get("ApplicationPrefs"); String twitterHash = prefs.get(ApplicationPrefs.TWITTER_HASH); if (!StringUtils.hasText(twitterHash)) { LOG.debug("Hash is not defined exiting from Twitter query job..."); return; } db = SchedulerUtils.getConnection(schedulerContext); // Determine the previous retrieved twitter id to use for query Process process = new Process(db, "TwitterQueryJob"); long sinceId = process.getLongValue(); LOG.debug("Last saved twitter id is : " + sinceId); // Create Query Object for searching twitter Query query = new Query("#" + twitterHash); query.setRpp(99); if (sinceId > 0) { // Set since_id in the query query.setSinceId(sinceId); } // Get the Twitter search results Twitter twitter = new Twitter(TWITTER_BASE_URL); QueryResult result = twitter.search(query); LOG.debug("Found and retrieved " + result.getTweets().size() + " tweet(s)."); // Iterate through the tweets and store in project history int count = 0; for (Tweet tweet : result.getTweets()) { count++; LOG.debug("Got tweet from " + tweet.getFromUser() + " as " + tweet.getText()); // See if this matches any profiles in the system // @note it's possible that more than one project can have the same twitter id ProjectList projectList = new ProjectList(); projectList.setTwitterId(tweet.getFromUser()); projectList.setApprovedOnly(true); projectList.buildList(db); // Clean up the tweet output String message = tweet.getText(); // Turn links into wiki links message = WikiUtils.addWikiLinks(message); // Remove the hash tag - beginning or middle message = StringUtils.replace(message, "#" + twitterHash + " ", ""); // Remove the hash tag - middle or end message = StringUtils.replace(message, " #" + twitterHash, ""); // Remove the hash tag - untokenized message = StringUtils.replace(message, "#" + twitterHash, ""); // Update the activity stream for the matching profiles for (Project project : projectList) { ProjectHistory projectHistory = new ProjectHistory(); projectHistory.setProjectId(project.getId()); projectHistory.setEnabled(true); // If there is a user profile, use the user's id, else use the businesses id? or use a different event if (project.getProfile()) { projectHistory.setEnteredBy(project.getOwner()); } else { projectHistory.setEnteredBy(project.getOwner()); } projectHistory.setLinkStartDate(new Timestamp(System.currentTimeMillis())); String desc = WikiLink.generateLink(project) + " [[http://twitter.com/" + tweet.getFromUser() + "/statuses/" + tweet.getId() + " tweeted]] " + message; projectHistory.setDescription(desc); projectHistory.setLinkItemId(project.getId()); projectHistory.setLinkObject(ProjectHistoryList.TWITTER_OBJECT); projectHistory.setEventType(ProjectHistoryList.TWITTER_EVENT); // Store the tweets in project history projectHistory.insert(db); } // Set the tweet id as since_Id if (sinceId < tweet.getId()) { sinceId = tweet.getId(); } } //update the recent sinceId and process timestamp process.setLongValue(sinceId); process.setProcessed(new Timestamp(new java.util.Date().getTime())); process.update(db); long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; LOG.debug("Finished: " + count + " took " + totalTime + " ms"); } catch (Exception e) { LOG.error("TwitterQueryJob Exception", e); throw new JobExecutionException(e.getMessage()); } finally { SchedulerUtils.freeConnection(schedulerContext, db); } }
From source file:com.daemon.Minion.java
License:Open Source License
/** * Sends a request specified as search term to Twitter and returns the * results Twitter returned./*from w w w . ja v a2s .c o m*/ * * @param term The search term object. * @return The answer of the sent request as QueryResult. * @throws TwitterException Thrown whenever there is a problem querying Twitter * (i. e the Rate Limit was reached). */ public QueryResult search(SearchTerm term) throws TwitterException { Query query = new Query(term.getTerm()); query.setCount(100); query.setResultType(Query.RECENT); if (term.getLastFetchedTweetId() == null) { // Start a new backwards search fron the current given start if (term.getOldStart() == null) query.setUntil(Localization.DATETIME_FORMATTER.print(term.getCurrentStart().plusDays(1))); } else // Continue the current search from the last fetched tweet id query.setMaxId(term.getLastFetchedTweetId()); return _twitter.search(query); }
From source file:com.daiv.android.twitter.ui.profile_viewer.fragments.sub_fragments.ProfileMentionsFragment.java
License:Apache License
public void doSearch() { spinner.setVisibility(View.VISIBLE); new Thread(new Runnable() { @Override// w w w. j a v a2s. c o m public void run() { try { Twitter twitter = Utils.getTwitter(context, settings); query = new Query("@" + screenName + " -RT"); query.sinceId(1); QueryResult result = twitter.search(query); tweets.clear(); for (twitter4j.Status status : result.getTweets()) { tweets.add(status); } if (result.hasNext()) { query = result.nextQuery(); hasMore = true; } else { hasMore = false; } ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { adapter = new TimelineArrayAdapter(context, tweets); listView.setAdapter(adapter); listView.setVisibility(View.VISIBLE); spinner.setVisibility(View.GONE); canRefresh = true; if (!hasMore) { View footer = inflater.inflate(R.layout.mentions_footer, null); listView.addFooterView(footer); listView.setFooterDividersEnabled(false); } } }); } catch (Exception e) { e.printStackTrace(); ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { spinner.setVisibility(View.GONE); canRefresh = false; if (!hasMore) { View footer = inflater.inflate(R.layout.mentions_footer, null); listView.addFooterView(footer); listView.setFooterDividersEnabled(false); } } }); } catch (OutOfMemoryError e) { e.printStackTrace(); ((Activity) context).runOnUiThread(new Runnable() { @Override public void run() { spinner.setVisibility(View.GONE); canRefresh = false; if (!hasMore) { View footer = inflater.inflate(R.layout.mentions_footer, null); listView.addFooterView(footer); listView.setFooterDividersEnabled(false); } } }); } } }).start(); }