List of usage examples for twitter4j Status getUser
User getUser();
From source file:org.mariotaku.twidere.util.ContentValuesCreator.java
License:Open Source License
@NonNull public static ContentValues createStatus(final Status orig, final long accountId) { if (orig == null) throw new NullPointerException(); final ContentValues values = new ContentValues(); values.put(Statuses.ACCOUNT_ID, accountId); values.put(Statuses.STATUS_ID, orig.getId()); values.put(Statuses.STATUS_TIMESTAMP, orig.getCreatedAt().getTime()); final Status status; if (orig.isRetweet()) { final Status retweetedStatus = orig.getRetweetedStatus(); final User retweetUser = orig.getUser(); final long retweetedById = retweetUser.getId(); values.put(Statuses.RETWEET_ID, retweetedStatus.getId()); values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime()); values.put(Statuses.RETWEETED_BY_USER_ID, retweetedById); values.put(Statuses.RETWEETED_BY_USER_NAME, retweetUser.getName()); values.put(Statuses.RETWEETED_BY_USER_SCREEN_NAME, retweetUser.getScreenName()); values.put(Statuses.RETWEETED_BY_USER_PROFILE_IMAGE, (retweetUser.getProfileImageUrlHttps())); values.put(Statuses.IS_RETWEET, true); if (retweetedById == accountId) { values.put(Statuses.MY_RETWEET_ID, orig.getId()); } else {/*from w ww .java 2 s.c o m*/ values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet()); } status = retweetedStatus; } else if (orig.isQuote()) { final Status quotedStatus = orig.getQuotedStatus(); final User quoteUser = orig.getUser(); final long quotedById = quoteUser.getId(); values.put(Statuses.QUOTE_ID, quotedStatus.getId()); final String textHtml = TwitterContentUtils.formatStatusText(orig); values.put(Statuses.QUOTE_TEXT_HTML, textHtml); values.put(Statuses.QUOTE_TEXT_PLAIN, orig.getText()); values.put(Statuses.QUOTE_TEXT_UNESCAPED, toPlainText(textHtml)); values.put(Statuses.QUOTE_TIMESTAMP, orig.getCreatedAt().getTime()); values.put(Statuses.QUOTE_SOURCE, orig.getSource()); final ParcelableMedia[] quoteMedia = ParcelableMedia.fromStatus(orig); if (quoteMedia != null && quoteMedia.length > 0) { try { values.put(Statuses.QUOTE_MEDIA_JSON, LoganSquare.serialize(Arrays.asList(quoteMedia), ParcelableMedia.class)); } catch (IOException ignored) { } } values.put(Statuses.QUOTED_BY_USER_ID, quotedById); values.put(Statuses.QUOTED_BY_USER_NAME, quoteUser.getName()); values.put(Statuses.QUOTED_BY_USER_SCREEN_NAME, quoteUser.getScreenName()); values.put(Statuses.QUOTED_BY_USER_PROFILE_IMAGE, quoteUser.getProfileImageUrlHttps()); values.put(Statuses.QUOTED_BY_USER_IS_VERIFIED, quoteUser.isVerified()); values.put(Statuses.QUOTED_BY_USER_IS_PROTECTED, quoteUser.isProtected()); values.put(Statuses.IS_QUOTE, true); status = quotedStatus; } else { values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet()); status = orig; } if (orig.isRetweet()) { values.put(Statuses.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); values.put(Statuses.IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); values.put(Statuses.IN_REPLY_TO_USER_NAME, TwitterContentUtils.getInReplyToName(status)); values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, status.getInReplyToScreenName()); } else { values.put(Statuses.IN_REPLY_TO_STATUS_ID, orig.getInReplyToStatusId()); values.put(Statuses.IN_REPLY_TO_USER_ID, orig.getInReplyToUserId()); values.put(Statuses.IN_REPLY_TO_USER_NAME, TwitterContentUtils.getInReplyToName(orig)); values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, orig.getInReplyToScreenName()); } final User user = status.getUser(); final long userId = user.getId(); final String profileImageUrl = (user.getProfileImageUrlHttps()); final String name = user.getName(), screenName = user.getScreenName(); values.put(Statuses.USER_ID, userId); values.put(Statuses.USER_NAME, name); values.put(Statuses.USER_SCREEN_NAME, screenName); values.put(Statuses.IS_PROTECTED, user.isProtected()); values.put(Statuses.IS_VERIFIED, user.isVerified()); values.put(Statuses.USER_PROFILE_IMAGE_URL, profileImageUrl); values.put(CachedUsers.IS_FOLLOWING, user.isFollowing()); final String textHtml = TwitterContentUtils.formatStatusText(status); values.put(Statuses.TEXT_HTML, textHtml); values.put(Statuses.TEXT_PLAIN, status.getText()); values.put(Statuses.TEXT_UNESCAPED, toPlainText(textHtml)); values.put(Statuses.RETWEET_COUNT, status.getRetweetCount()); values.put(Statuses.REPLY_COUNT, status.getReplyCount()); values.put(Statuses.FAVORITE_COUNT, status.getFavoriteCount()); values.put(Statuses.DESCENDENT_REPLY_COUNT, status.getDescendentReplyCount()); values.put(Statuses.SOURCE, status.getSource()); values.put(Statuses.IS_POSSIBLY_SENSITIVE, status.isPossiblySensitive()); final GeoLocation location = status.getGeoLocation(); if (location != null) { values.put(Statuses.LOCATION, ParcelableLocation.toString(location.getLatitude(), location.getLongitude())); } final Place place = status.getPlace(); if (place != null) { values.put(Statuses.PLACE_FULL_NAME, place.getFullName()); } values.put(Statuses.IS_FAVORITE, status.isFavorited()); final ParcelableMedia[] media = ParcelableMedia.fromStatus(status); if (media != null && media.length > 0) { try { values.put(Statuses.MEDIA_JSON, LoganSquare.serialize(Arrays.asList(media), ParcelableMedia.class)); } catch (IOException ignored) { } } final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status); if (mentions != null && mentions.length > 0) { try { values.put(Statuses.MENTIONS_JSON, LoganSquare.serialize(Arrays.asList(mentions), ParcelableUserMention.class)); } catch (IOException ignored) { } } final ParcelableCardEntity card = ParcelableCardEntity.fromCardEntity(status.getCard(), accountId); if (card != null) { try { values.put(Statuses.CARD, LoganSquare.serialize(card)); values.put(Statuses.CARD_NAME, card.name); } catch (IOException ignored) { } } return values; }
From source file:org.minesales.infres6.narvisAPITwiterConsole.communications.twitter.input.TwitterInput.java
private String[] tweetParser(Status status) { String[] returnValue = new String[2]; returnValue[0] = getCleanTweet(status.getText()); returnValue[1] = status.getUser().getScreenName() + getOtherResponseName(status.getText()); return returnValue; }
From source file:org.mule.twitter.TwitterConnector.java
License:Open Source License
/** * Retrieves the following user updates notifications:<br/> * - New Statuses <br/>/*from www . java2s . c om*/ * - Block/Unblock events <br/> * - Follow events <br/> * - User profile updates <br/> * - Retweets <br/> * - List creation/deletion <br/> * - List member addition/remotion <br/> * - List subscription/unsubscription <br/> * - List updates <br/> * - Profile updates <br/> * <p/> * Such notifications are represented as org.mule.twitter.UserEvent objects * <p/> * Only one Twitter stream can be consumed using the same credentials. As a consequence, * only one twitter stream can be consumed per connector instance. * <p/> * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:userStream} * * @param keywords the keywords to track for new statuses * @param callback_ the {@link SourceCallback} used to dispatch messages when a response is received */ @Source public void userStream(@Placement(group = "Keywords to Track") List<String> keywords, final SourceCallback callback_) { initStream(); final SoftCallback callback = new SoftCallback(callback_); stream.addListener(new UserStreamAdapter() { @Override public void onException(Exception ex) { logger.warn("An exception occured while processing user stream", ex); } @Override public void onStatus(Status status) { try { callback.process(UserEvent.fromPayload(EventType.NEW_STATUS, status.getUser(), status)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onBlock(User source, User blockedUser) { try { callback.process(UserEvent.fromTarget(EventType.BLOCK, source, blockedUser)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onFollow(User source, User followedUser) { try { callback.process(UserEvent.fromTarget(EventType.FOLLOW, source, followedUser)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUnblock(User source, User unblockedUser) { try { callback.process(UserEvent.fromTarget(EventType.UNBLOCK, source, unblockedUser)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListCreation(User listOwner, UserList list) { try { callback.process(UserEvent.fromPayload(EventType.LIST_CREATION, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListDeletion(User listOwner, UserList list) { try { callback.process(UserEvent.fromPayload(EventType.LIST_DELETION, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) { try { callback.process(UserEvent.from(EventType.LIST_MEMBER_ADDITION, addedMember, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) { try { callback.process( UserEvent.from(EventType.LIST_MEMBER_DELETION, deletedMember, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListSubscription(User subscriber, User listOwner, UserList list) { try { callback.process(UserEvent.from(EventType.LIST_SUBSCRIPTION, subscriber, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) { try { callback.process(UserEvent.from(EventType.LIST_UNSUBSCRIPTION, subscriber, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserListUpdate(User listOwner, UserList list) { try { callback.process(UserEvent.fromPayload(EventType.LIST_UPDATE, listOwner, list)); } catch (Exception e) { logger.error(e.getMessage(), e); } } @Override public void onUserProfileUpdate(User updatedUser) { try { callback.process(UserEvent.fromPayload(EventType.PROFILE_UPDATE, updatedUser, null)); } catch (Exception e) { logger.error(e.getMessage(), e); } } }); stream.user(toStringArray(keywords)); }
From source file:org.n52.twitter.model.TwitterMessage.java
License:Open Source License
public static TwitterMessage create(Status tweet) { if (isGeolocated(tweet)) { TwitterMessage result = new TwitterMessage(); result.id = Long.toString(tweet.getId()); result.procedure = new Procedure(tweet.getUser().getScreenName(), String.format(USER_URL, tweet.getUser().getScreenName())); result.location = new TwitterLocation(tweet.getGeoLocation(), tweet.getPlace()); result.createdTime = new DateTime(tweet.getCreatedAt(), DateTimeZone.UTC); result.link = String.format(TWEET_URL, tweet.getUser().getScreenName(), Long.toString(tweet.getId())); result.message = tweet.getText(); return result; }// ww w . j av a 2 s .c o m return null; }
From source file:org.nsoft.openbus.model.Mensagem.java
License:Open Source License
public static Mensagem creteFromTwitterStatus(Status s) { try {//from www .ja va 2s .co m Mensagem mensagem = new Mensagem(); String text = s.getText(); for (HashtagEntity h : s.getHashtagEntities()) { String subText = "<a href=\"twitter_search://do_search?search=" + h.getText() + "\">#" + h.getText() + "</a>"; text = text.replace("#" + h.getText(), subText); } for (UserMentionEntity u : s.getUserMentionEntities()) { String subText = "<a href=\"twitter_search_user://find_user?username=" + u.getScreenName() + "\">@" + u.getScreenName() + "</a>"; text = text.replace("@" + u.getScreenName(), subText); } mensagem.setAction(OpenTwitterStatusAction.getInstance()); mensagem.addtions = createAddtions(s); mensagem.addtions.put("htmlText", text); mensagem.idMensagem = Long.toString(s.getId()); mensagem.nome_usuario = s.getUser().getName(); mensagem.mensagem = s.getText(); mensagem.imagePath = new URL(s.getUser().getOriginalProfileImageURL()); mensagem.data = s.getCreatedAt(); mensagem.idUser = s.getUser().getId(); mensagem.tipo = TIPO_STATUS; return mensagem; } catch (JSONException e) { return null; } catch (MalformedURLException e) { return null; } }
From source file:org.nsoft.openbus.utils.ImageUtils.java
License:Open Source License
public static void loadImages(ResponseList<Status> list) { for (Status status : list) { URL imageURL = status.getUser().getProfileImageUrlHttps(); Bitmap imgBit = ImageUtils.imageCache.get(imageURL); if (imgBit == null) { // imgBit = ImageUtils.loadProfileImages(imageURL); ImageUtils.imageCache.put(imageURL, imgBit); }/* www . j a va 2 s. c o m*/ } }
From source file:org.nsoft.openbus.utils.TwitterUtils.java
License:Open Source License
public static ResponseUpdate updateTweets(Context ctx, ResponseList<twitter4j.Status> list, int type) { // ImageUtils.loadImages(list); Mensagem lastMessage = null;/* w w w .ja v a 2s.c o m*/ Vector<Mensagem> mensagens = new Vector<Mensagem>(); for (twitter4j.Status status : list) { Mensagem m = Mensagem.creteFromTwitterStatus(status); Facade facade = Facade.getInstance(ctx); User u = User.createFromTwitterUser(status.getUser()); facade.insert(u); m.setTipo(type); if (!facade.exsistsStatus(m.getIdMensagem(), m.getTipo())) { facade.insert(m); } mensagens.add(m); lastMessage = m; } ResponseUpdate response = new ResponseUpdate(); response.lastMessage = lastMessage; response.mensagens = mensagens; return response; }
From source file:org.onepercent.utils.twitterstream.agent.src.main.java.com.cloudera.flume.source.TwitterSource.java
License:Apache License
/** * Start processing events. This uses the Twitter Streaming API to sample * Twitter, and process tweets.//from w w w .j a va 2 s .c om */ @Override public void start() { // The channel is the piece of Flume that sits between the Source and Sink, // and is used to process events. final ChannelProcessor channel = getChannelProcessor(); final Map<String, String> headers = new HashMap<String, String>(); // The StatusListener is a twitter4j API, which can be added to a Twitter // stream, and will execute methods every time a message comes in through // the stream. StatusListener listener = new StatusListener() { // The onStatus method is executed every time a new tweet comes in. public void onStatus(Status status) { // The EventBuilder is used to build an event using the headers and // the raw JSON of a tweet logger.debug(status.getUser().getScreenName() + ": " + status.getText()); headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime())); Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers); channel.processEvent(event); } // This listener will ignore everything except for new tweets public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning warning) { } }; logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}", new String[] { consumerKey, accessToken }); // Set up the stream's listener (defined above), twitterStream.addListener(listener); // Set up a filter to pull out industry-relevant tweets if (keywords.length == 0) { logger.debug("Starting up Twitter sampling..."); twitterStream.sample(); } else if (keywords.length > 0) { if (languages.length == 0) { logger.debug("Starting up Twitter Keyword filtering..."); FilterQuery query = new FilterQuery().track(keywords); twitterStream.filter(query); } else { logger.debug("Starting up Twitter Keyword and Language filtering..."); FilterQuery query = new FilterQuery(); query.track(keywords); query.language(languages); twitterStream.filter(query); } } super.start(); }
From source file:org.opensocial.TwitterProxy.java
License:Apache License
/** * Called on HTTP GET//from w w w. j av a 2 s . co m * Returns last 20 tweets from the user using "screen_name". * If screenName is null or an empty string, we return the last 20 tweets from the public * timeline * @param screenName * @return JSON Response a ActivityStream Activity collection for the set tweets */ @GET @Produces(MediaType.APPLICATION_JSON) public Object getTweets(@QueryParam("screen_name") String screenName) { JSONArray resultArray = new JSONArray(); ResponseList<Status> list = null; try { if (screenName == null || screenName.equals("")) { list = twitter.getHomeTimeline(); } else { list = twitter.getUserTimeline(screenName); } System.out.println("Rate limit: " + list.getRateLimitStatus().getRemainingHits()); Iterator<Status> iter = list.iterator(); while (iter.hasNext()) { Status status = iter.next(); ActivityBuilder activityBuilder = Activity.makeActivity().id(Long.toString(status.getId())) .verb(Verb.POST).published(new DateTime(status.getCreatedAt().getTime())) .source(ASObject.makeObject(ASObject.SOURCE).displayName(status.getSource())) .author(PersonObject.makePerson(status.getUser().getScreenName()) .id(Long.toString(status.getUser().getId())) .image(MediaLink .makeMediaLink(status.getUser().getProfileImageURL().toExternalForm())) .get()); boolean eeAdded = false; eeAdded = EmbeddedExperiences.addHashtagEE(uriInfo, status, activityBuilder); if (!eeAdded) { eeAdded = EmbeddedExperiences.addUrlMatchedEE(uriInfo, status, activityBuilder); } if (!eeAdded) { eeAdded = EmbeddedExperiences.addUrlStyleEE(status, activityBuilder); } activityBuilder.content(status.getText()); Activity activity = activityBuilder.get(); StringWriter swriter = new StringWriter(); activity.writeTo(swriter); JSONObject jobj = new JSONObject(swriter.toString()); resultArray.put(jobj); } return resultArray; } catch (Exception e) { e.printStackTrace(); return Response.serverError().entity(e).build(); } }
From source file:org.primefaces.examples.view.TwitterSearchView.java
License:Apache License
public void start() { if (!active) { PushContext context = PushContextFactory.getDefault().getPushContext(); context.schedule("/twitter", new Callable<String>() { private String results; public String call() throws Exception { List<Status> tweets = twitterService.asyncSearch("I"); if (tweets != null) { JSONObject jSONObject = new JSONObject(); JSONArray jSONArray = new JSONArray(); for (Status t : tweets) { JSONObject j = new JSONObject(); j.put("from_user", t.getUser().getScreenName()); j.put("text", t.getText()); j.put("image", t.getUser().getMiniProfileImageURL()); jSONArray.put(j); }/*from www . j a v a2s . c o m*/ jSONObject.put("results", jSONArray); results = "{\"data\":" + jSONObject.toString() + "}"; } return results; } }, 10, TimeUnit.SECONDS); active = true; } }