List of usage examples for twitter4j Status getId
long getId();
From source file:de.fhb.twitalyse.spout.TwitterStreamSpout.java
License:Open Source License
@Override public void onStatus(Status status) { String json = DataObjectFactory.getRawJSON(status); id = InprocMessaging.acquireNewPort(); InprocMessaging.sendMessage(id, new Values(status.getId(), json)); }
From source file:de.jetsli.twitter.TwitterSearch.java
License:Apache License
long search(String term, Collection<Status> result, Map<String, User> userMap, int tweets, long lastMaxCreateTime) throws TwitterException { long maxId = 0L; long maxMillis = 0L; // TODO it looks like only one page is possible with 4.0.0 int maxPages = 1; int hitsPerPage = tweets; boolean breakPaging = false; for (int page = 0; page < maxPages; page++) { Query query = new Query(term); // RECENT or POPULAR query.setResultType(Query.MIXED); // avoid that more recent results disturb our paging! if (page > 0) query.setMaxId(maxId);//from w w w. j av a 2s. c om query.setCount(hitsPerPage); QueryResult res = twitter.search(query); // is res.getTweets() sorted? for (Status twe : res.getTweets()) { // determine maxId in the first page if (page == 0 && maxId < twe.getId()) maxId = twe.getId(); if (maxMillis < twe.getCreatedAt().getTime()) maxMillis = twe.getCreatedAt().getTime(); if (twe.getCreatedAt().getTime() + 1000 < lastMaxCreateTime) breakPaging = true; else { String userName = twe.getUser().getScreenName().toLowerCase(); User user = userMap.get(userName); if (user == null) userMap.put(userName, twe.getUser()); result.add(twe); } } // minMillis could force us to leave earlier than defined by maxPages // or if resulting tweets are less then request (but -10 because of twitter strangeness) if (breakPaging || res.getTweets().size() < hitsPerPage - 10) break; } return maxMillis; }
From source file:de.jetwick.tw.NewClass.java
License:Apache License
/** * A thread using the streaming API./* w ww. jav a 2 s . com*/ * Maximum tweets/sec == 50 !! we'll lose even infrequent tweets for a lot keywords! */ public Thread streaming(final String token, final String tokenSecret) { return new Thread() { StatusListener listener = new StatusListener() { int counter = 0; public void onStatus(Status status) { if (++counter % 20 == 0) log("async counter=" + counter); asyncMap.put(status.getId(), status.getText()); } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { log("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { log("Got track limitation notice:" + numberOfLimitedStatuses); } public void onScrubGeo(int userId, long upToStatusId) { log("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } public void onException(Exception ex) { ex.printStackTrace(); } }; public void run() { TwitterStream twitterStream = new TwitterStreamFactory() .getInstance(new AccessToken(token, tokenSecret)); twitterStream.addListener(listener); twitterStream.filter(new FilterQuery(0, null, new String[] { queryTerms }, null)); } }; }
From source file:de.jetwick.tw.TwitterSearch.java
License:Apache License
public static Twitter4JTweet toTweet(Status st, User user) { if (user == null) throw new IllegalArgumentException("User mustn't be null!"); if (st == null) throw new IllegalArgumentException("Status mustn't be null!"); Twitter4JTweet tw = new Twitter4JTweet(st.getId(), st.getText(), user.getScreenName()); tw.setCreatedAt(st.getCreatedAt());/* ww w . java 2 s. co m*/ tw.setFromUser(user.getScreenName()); if (user.getProfileImageURL() != null) tw.setProfileImageUrl(user.getProfileImageURL().toString()); tw.setSource(st.getSource()); tw.setToUser(st.getInReplyToUserId(), st.getInReplyToScreenName()); tw.setInReplyToStatusId(st.getInReplyToStatusId()); if (st.getGeoLocation() != null) { tw.setGeoLocation(st.getGeoLocation()); tw.setLocation(st.getGeoLocation().getLatitude() + ", " + st.getGeoLocation().getLongitude()); } else if (st.getPlace() != null) tw.setLocation(st.getPlace().getCountryCode()); else if (user.getLocation() != null) tw.setLocation(toStandardLocation(user.getLocation())); return tw; }
From source file:de.jetwick.tw.TwitterSearch.java
License:Apache License
/** * This method only returns up to 800 statuses, including retweets. *//* w w w .j a va2s . c o m*/ public long getHomeTimeline(Collection<JTweet> result, int tweets, long lastId) throws TwitterException { if (lastId <= 0) lastId = 1; Map<String, JUser> userMap = new LinkedHashMap<String, JUser>(); int hitsPerPage = 100; long maxId = lastId; long sinceId = lastId; int maxPages = tweets / hitsPerPage + 1; END_PAGINATION: for (int page = 0; page < maxPages; page++) { Paging paging = new Paging(page + 1, tweets, sinceId); // avoid that more recent results disturb our paging! if (page > 0) paging.setMaxId(maxId); Collection<Status> tmp = twitter.getHomeTimeline(paging); rateLimit--; for (Status st : tmp) { // determine maxId in the first page if (page == 0 && maxId < st.getId()) maxId = st.getId(); if (st.getId() < sinceId) break END_PAGINATION; Tweet tw = toTweet(st); String userName = tw.getFromUser().toLowerCase(); JUser user = userMap.get(userName); if (user == null) { user = new JUser(st.getUser()).init(tw); userMap.put(userName, user); } result.add(new JTweet(tw, user)); } // sinceId could force us to leave earlier than defined by maxPages if (tmp.size() < hitsPerPage) break; } return maxId; }
From source file:de.vanita5.twittnuker.loader.support.StatusRepliesLoader.java
License:Open Source License
@Override public List<Status> getStatuses(final Twitter twitter, final Paging paging) throws TwitterException { final Context context = getContext(); if (shouldForceUsingPrivateAPIs(context) || isOfficialTwitterInstance(context, twitter)) { final List<Status> statuses = twitter.showConversation(mInReplyToStatusId, paging); final List<Status> result = new ArrayList<Status>(); for (final Status status : statuses) { if (status.getId() > mInReplyToStatusId) { result.add(status);// www . jav a2 s .co m } } return result; } else { final List<Status> statuses = super.getStatuses(twitter, paging); final List<Status> result = new ArrayList<Status>(); for (final Status status : statuses) { if (status.getInReplyToStatusId() == mInReplyToStatusId) { result.add(status); } } return result; } }
From source file:de.vanita5.twittnuker.loader.support.Twitter4JStatusesLoader.java
License:Open Source License
@SuppressWarnings("unchecked") @Override// w w w.ja va 2 s.c o m public final List<ParcelableStatus> loadInBackground() { final File serializationFile = getSerializationFile(); final List<ParcelableStatus> data = getData(); if (isFirstLoad() && getTabPosition() >= 0 && serializationFile != null) { final List<ParcelableStatus> cached = getCachedData(serializationFile); if (cached != null) { data.addAll(cached); Collections.sort(data); return new CopyOnWriteArrayList<>(data); } } final List<Status> statuses; final boolean truncated; final Context context = getContext(); final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE); final int loadItemLimit = prefs.getInt(KEY_LOAD_ITEM_LIMIT, DEFAULT_LOAD_ITEM_LIMIT); try { final Paging paging = new Paging(); paging.setCount(loadItemLimit); if (mMaxId > 0) { paging.setMaxId(mMaxId); } if (mSinceId > 0) { paging.setSinceId(mSinceId - 1); } statuses = new ArrayList<>(); truncated = truncateStatuses(getStatuses(getTwitter(), paging), statuses, mSinceId); } catch (final TwitterException e) { // mHandler.post(new ShowErrorRunnable(e)); e.printStackTrace(); return new CopyOnWriteArrayList<>(data); } final long minStatusId = statuses.isEmpty() ? -1 : Collections.min(statuses).getId(); final boolean insertGap = minStatusId > 0 && statuses.size() > 1 && !data.isEmpty() && !truncated; mHandler.post(CacheUsersStatusesTask.getRunnable(context, new StatusListResponse(mAccountId, statuses))); for (final Status status : statuses) { final long id = status.getId(); final boolean deleted = deleteStatus(data, id); data.add(new ParcelableStatus(status, mAccountId, minStatusId == id && insertGap && !deleted)); } Collections.sort(data); final ParcelableStatus[] array = data.toArray(new ParcelableStatus[data.size()]); for (int i = 0, size = array.length; i < size; i++) { final ParcelableStatus status = array[i]; if (shouldFilterStatus(mDatabase, status) && !status.is_gap && i != size - 1) { deleteStatus(data, status.id); } } saveCachedData(serializationFile, data); return new CopyOnWriteArrayList<>(data); }
From source file:de.vanita5.twittnuker.model.ParcelableStatus.java
License:Open Source License
public ParcelableStatus(final Status orig, final long account_id, final boolean is_gap) { this.is_gap = is_gap; this.account_id = account_id; id = orig.getId(); timestamp = getTime(orig.getCreatedAt()); is_retweet = orig.isRetweet();/*w ww . j a v a2 s .c om*/ final Status retweeted = orig.getRetweetedStatus(); final User retweet_user = retweeted != null ? orig.getUser() : null; retweet_id = retweeted != null ? retweeted.getId() : -1; //NOTE getTime(orig.getCreatedAt()) retweet_timestamp = retweeted != null ? getTime(retweeted.getCreatedAt()) : -1; retweeted_by_id = retweet_user != null ? retweet_user.getId() : -1; retweeted_by_name = retweet_user != null ? retweet_user.getName() : null; retweeted_by_screen_name = retweet_user != null ? retweet_user.getScreenName() : null; retweeted_by_profile_image = retweet_user != null ? ParseUtils.parseString(retweet_user.getProfileImageUrlHttps()) : null; final Status status = retweeted != null ? retweeted : orig; final User user = status.getUser(); user_id = user.getId(); user_name = user.getName(); user_screen_name = user.getScreenName(); user_profile_image_url = ParseUtils.parseString(user.getProfileImageUrlHttps()); user_is_protected = user.isProtected(); user_is_verified = user.isVerified(); user_is_following = user.isFollowing(); text_html = formatStatusText(status); media = ParcelableMedia.fromEntities(status); text_plain = status.getText(); retweet_count = status.getRetweetCount(); favorite_count = status.getFavoriteCount(); reply_count = status.getReplyCount(); descendent_reply_count = status.getDescendentReplyCount(); in_reply_to_name = getInReplyToName(status); in_reply_to_screen_name = status.getInReplyToScreenName(); in_reply_to_status_id = status.getInReplyToStatusId(); in_reply_to_user_id = status.getInReplyToUserId(); source = status.getSource(); location = new ParcelableLocation(status.getGeoLocation()); is_favorite = status.isFavorited(); text_unescaped = toPlainText(text_html); my_retweet_id = retweeted_by_id == account_id ? id : -1; is_possibly_sensitive = status.isPossiblySensitive(); mentions = ParcelableUserMention.fromUserMentionEntities(status.getUserMentionEntities()); first_media = media != null && media.length > 0 ? media[0].url : null; }
From source file:de.vanita5.twittnuker.service.BackgroundOperationService.java
License:Open Source License
private List<SingleResponse<ParcelableStatus>> updateStatus(final Builder builder, final ParcelableStatusUpdate statusUpdate) { final ArrayList<ContentValues> hashtag_values = new ArrayList<ContentValues>(); final Collection<String> hashtags = extractor.extractHashtags(statusUpdate.text); for (final String hashtag : hashtags) { final ContentValues values = new ContentValues(); values.put(CachedHashtags.NAME, hashtag); hashtag_values.add(values);/*w ww. ja v a2s. c o m*/ } boolean notReplyToOther = false; mResolver.bulkInsert(CachedHashtags.CONTENT_URI, hashtag_values.toArray(new ContentValues[hashtag_values.size()])); final List<SingleResponse<ParcelableStatus>> results = new ArrayList<SingleResponse<ParcelableStatus>>(); if (statusUpdate.accounts.length == 0) return Collections.emptyList(); try { final boolean hasMedia = statusUpdate.medias != null && statusUpdate.medias.length > 0; final String imagePath = hasMedia ? getImagePathFromUri(this, Uri.parse(statusUpdate.medias[0].uri)) : null; final File imageFile = imagePath != null ? new File(imagePath) : null; String uploadResultUrl = null; if (mUseUploader && imageFile != null && imageFile.exists()) { uploadResultUrl = uploadMedia(imageFile, statusUpdate.accounts, statusUpdate.text); } final String unshortenedContent = mUseUploader && uploadResultUrl != null ? getImageUploadStatus(new String[] { uploadResultUrl.toString() }, statusUpdate.text) : statusUpdate.text; final boolean shouldShorten = mValidator.getTweetLength(unshortenedContent) > mValidator .getMaxTweetLength(); Map<Long, ShortenedStatusModel> shortenedStatuses = null; if (shouldShorten && mUseShortener) { if (mShortener.equals(SERVICE_SHORTENER_HOTOTIN)) { shortenedStatuses = postHototIn(statusUpdate); if (shortenedStatuses == null) throw new ShortenException(this); } else if (mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) { shortenedStatuses = postTwitlonger(statusUpdate); if (shortenedStatuses == null) throw new ShortenException(this); } else { throw new IllegalArgumentException("BackgroundOperationService.java#updateStatus()"); } } if (shouldShorten) { if (!mUseShortener) throw new StatusTooLongException(this); else if (unshortenedContent == null) throw new ShortenException(this); } if (!mUseUploader && statusUpdate.medias != null) { for (final ParcelableMediaUpdate media : statusUpdate.medias) { final String path = getImagePathFromUri(this, Uri.parse(media.uri)); final File file = path != null ? new File(path) : null; if (file != null && file.exists()) { Utils.downscaleImageIfNeeded(file, 95); } } } for (final Account account : statusUpdate.accounts) { String shortenedContent = ""; ShortenedStatusModel shortenedStatusModel = null; final Twitter twitter = getTwitterInstance(this, account.account_id, true, true); if (shouldShorten && mUseShortener && shortenedStatuses != null) { shortenedStatusModel = shortenedStatuses.get(account.account_id); shortenedContent = shortenedStatusModel.getText(); } final StatusUpdate status = new StatusUpdate( shouldShorten && mUseShortener ? shortenedContent : unshortenedContent); status.setInReplyToStatusId(statusUpdate.in_reply_to_status_id); if (statusUpdate.location != null) { status.setLocation(ParcelableLocation.toGeoLocation(statusUpdate.location)); } if (!mUseUploader && hasMedia) { final BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; final long[] mediaIds = new long[statusUpdate.medias.length]; try { for (int i = 0, j = mediaIds.length; i < j; i++) { final ParcelableMediaUpdate media = statusUpdate.medias[i]; final String path = getImagePathFromUri(this, Uri.parse(media.uri)); if (path == null) throw new FileNotFoundException(); BitmapFactory.decodeFile(path, o); final File file = new File(path); final ContentLengthInputStream is = new ContentLengthInputStream(file); is.setReadListener(new StatusMediaUploadListener(this, mNotificationManager, builder, statusUpdate)); final MediaUploadResponse uploadResp = twitter.uploadMedia(file.getName(), is, o.outMimeType); mediaIds[i] = uploadResp.getId(); } } catch (final FileNotFoundException e) { } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); continue; } status.mediaIds(mediaIds); } status.setPossiblySensitive(statusUpdate.is_possibly_sensitive); if (twitter == null) { results.add(new SingleResponse<ParcelableStatus>(null, new NullPointerException())); continue; } try { final Status twitter_result = twitter.updateStatus(status); //Update Twitlonger statuses if (shouldShorten && mUseShortener && mShortener.equals(SERVICE_SHORTENER_TWITLONGER)) { TweetShortenerUtils.updateTwitlonger(shortenedStatusModel, twitter_result.getId(), twitter); } if (!notReplyToOther) { final long inReplyToUserId = twitter_result.getInReplyToUserId(); if (inReplyToUserId <= 0) { notReplyToOther = true; } } final ParcelableStatus result = new ParcelableStatus(twitter_result, account.account_id, false); results.add(new SingleResponse<ParcelableStatus>(result, null)); } catch (final TwitterException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); } } } catch (final UpdateStatusException e) { final SingleResponse<ParcelableStatus> response = SingleResponse.getInstance(e); results.add(response); } return results; }
From source file:de.vanita5.twittnuker.task.CacheUsersStatusesTask.java
License:Open Source License
@Override protected Void doInBackground(final Void... args) { if (all_statuses == null || all_statuses.length == 0) return null; final Extractor extractor = new Extractor(); final Set<ContentValues> cachedUsersValues = new HashSet<ContentValues>(); final Set<ContentValues> cached_statuses_values = new HashSet<ContentValues>(); final Set<ContentValues> hashtag_values = new HashSet<ContentValues>(); final Set<Long> userIds = new HashSet<Long>(); final Set<Long> status_ids = new HashSet<Long>(); final Set<String> hashtags = new HashSet<String>(); final Set<User> users = new HashSet<User>(); for (final TwitterListResponse<twitter4j.Status> values : all_statuses) { if (values == null || values.list == null) { continue; }//from w ww .j a v a2 s . c o m final List<twitter4j.Status> list = values.list; for (final twitter4j.Status status : list) { if (status == null || status.getId() <= 0) { continue; } status_ids.add(status.getId()); cached_statuses_values.add(makeStatusContentValues(status, values.account_id)); hashtags.addAll(extractor.extractHashtags(status.getText())); final User user = status.getUser(); if (user != null && user.getId() > 0) { users.add(user); final ContentValues filtered_users_values = new ContentValues(); filtered_users_values.put(Filters.Users.NAME, user.getName()); filtered_users_values.put(Filters.Users.SCREEN_NAME, user.getScreenName()); final String filtered_users_where = Where.equals(Filters.Users.USER_ID, user.getId()).getSQL(); resolver.update(Filters.Users.CONTENT_URI, filtered_users_values, filtered_users_where, null); } } } bulkDelete(resolver, CachedStatuses.CONTENT_URI, CachedStatuses.STATUS_ID, status_ids, null, false); bulkInsert(resolver, CachedStatuses.CONTENT_URI, cached_statuses_values); for (final String hashtag : hashtags) { final ContentValues hashtag_value = new ContentValues(); hashtag_value.put(CachedHashtags.NAME, hashtag); hashtag_values.add(hashtag_value); } bulkDelete(resolver, CachedHashtags.CONTENT_URI, CachedHashtags.NAME, hashtags, null, true); bulkInsert(resolver, CachedHashtags.CONTENT_URI, hashtag_values); for (final User user : users) { userIds.add(user.getId()); cachedUsersValues.add(makeCachedUserContentValues(user)); } bulkDelete(resolver, CachedUsers.CONTENT_URI, CachedUsers.USER_ID, userIds, null, false); bulkInsert(resolver, CachedUsers.CONTENT_URI, cachedUsersValues); return null; }