Example usage for twitter4j Status getUserMentionEntities

List of usage examples for twitter4j Status getUserMentionEntities

Introduction

In this page you can find the example usage for twitter4j Status getUserMentionEntities.

Prototype

UserMentionEntity[] getUserMentionEntities();

Source Link

Document

Returns an array of user mentions in the tweet.

Usage

From source file:com.github.jcustenborder.kafka.connect.twitter.StatusConverter.java

License:Apache License

public static void convert(Status status, Struct struct) {
    struct.put("CreatedAt", status.getCreatedAt()).put("Id", status.getId()).put("Text", status.getText())
            .put("Source", status.getSource()).put("Truncated", status.isTruncated())
            .put("InReplyToStatusId", status.getInReplyToStatusId())
            .put("InReplyToUserId", status.getInReplyToUserId())
            .put("InReplyToScreenName", status.getInReplyToScreenName()).put("Favorited", status.isFavorited())
            .put("Retweeted", status.isRetweeted()).put("FavoriteCount", status.getFavoriteCount())
            .put("Retweet", status.isRetweet()).put("RetweetCount", status.getRetweetCount())
            .put("RetweetedByMe", status.isRetweetedByMe())
            .put("CurrentUserRetweetId", status.getCurrentUserRetweetId())
            .put("PossiblySensitive", status.isPossiblySensitive()).put("Lang", status.getLang());

    Struct userStruct;// w w w . jav  a2 s. c o m
    if (null != status.getUser()) {
        userStruct = new Struct(USER_SCHEMA);
        convert(status.getUser(), userStruct);
    } else {
        userStruct = null;
    }
    struct.put("User", userStruct);

    Struct placeStruct;
    if (null != status.getPlace()) {
        placeStruct = new Struct(PLACE_SCHEMA);
        convert(status.getPlace(), placeStruct);
    } else {
        placeStruct = null;
    }
    struct.put("Place", placeStruct);

    Struct geoLocationStruct;
    if (null != status.getGeoLocation()) {
        geoLocationStruct = new Struct(GEO_LOCATION_SCHEMA);
        convert(status.getGeoLocation(), geoLocationStruct);
    } else {
        geoLocationStruct = null;
    }
    struct.put("GeoLocation", geoLocationStruct);
    List<Long> contributers = new ArrayList<>();

    if (null != status.getContributors()) {
        for (Long l : status.getContributors()) {
            contributers.add(l);
        }
    }
    struct.put("Contributors", contributers);

    List<String> withheldInCountries = new ArrayList<>();
    if (null != status.getWithheldInCountries()) {
        for (String s : status.getWithheldInCountries()) {
            withheldInCountries.add(s);
        }
    }
    struct.put("WithheldInCountries", withheldInCountries);

    struct.put("HashtagEntities", convert(status.getHashtagEntities()));
    struct.put("UserMentionEntities", convert(status.getUserMentionEntities()));
    struct.put("MediaEntities", convert(status.getMediaEntities()));
    struct.put("SymbolEntities", convert(status.getSymbolEntities()));
    struct.put("URLEntities", convert(status.getURLEntities()));
}

From source file:com.klinker.android.twitter.utils.TweetLinkUtils.java

License:Apache License

public static String[] getLinksInStatus(Status status) {
    UserMentionEntity[] users = status.getUserMentionEntities();
    String mUsers = "";

    for (UserMentionEntity name : users) {
        String n = name.getScreenName();
        if (n.length() > 1) {
            mUsers += n + "  ";
        }//from w w w  .  j a v  a 2  s  .c  om
    }

    HashtagEntity[] hashtags = status.getHashtagEntities();
    String mHashtags = "";

    for (HashtagEntity hashtagEntity : hashtags) {
        String text = hashtagEntity.getText();
        if (text.length() > 1) {
            mHashtags += text + "  ";
        }
    }

    URLEntity[] urls = status.getURLEntities();
    String expandedUrls = "";
    String compressedUrls = "";

    for (URLEntity entity : urls) {
        String url = entity.getExpandedURL();
        if (url.length() > 1) {
            expandedUrls += url + "  ";
            compressedUrls += entity.getURL() + "  ";
        }
    }

    MediaEntity[] medias = status.getMediaEntities();
    String mediaExp = "";
    String mediaComp = "";
    String mediaDisplay = "";

    for (MediaEntity e : medias) {
        String url = e.getURL();
        if (url.length() > 1) {
            mediaComp += url + "  ";
            mediaExp += e.getExpandedURL() + "  ";
            mediaDisplay += e.getDisplayURL() + "  ";
        }
    }

    String[] sExpandedUrls;
    String[] sCompressedUrls;
    String[] sMediaExp;
    String[] sMediaComp;
    String[] sMediaDisplay;

    try {
        sCompressedUrls = compressedUrls.split("  ");
    } catch (Exception e) {
        sCompressedUrls = new String[0];
    }

    try {
        sExpandedUrls = expandedUrls.split("  ");
    } catch (Exception e) {
        sExpandedUrls = new String[0];
    }

    try {
        sMediaComp = mediaComp.split("  ");
    } catch (Exception e) {
        sMediaComp = new String[0];
    }

    try {
        sMediaExp = mediaExp.split("  ");
    } catch (Exception e) {
        sMediaExp = new String[0];
    }

    try {
        sMediaDisplay = mediaDisplay.split("  ");
    } catch (Exception e) {
        sMediaDisplay = new String[0];
    }

    String tweetTexts = status.getText();

    String imageUrl = "";
    String otherUrl = "";

    for (int i = 0; i < sCompressedUrls.length; i++) {
        String comp = sCompressedUrls[i];
        String exp = sExpandedUrls[i];

        if (comp.length() > 1 && exp.length() > 1) {
            String str = exp.toLowerCase();

            try {
                tweetTexts = tweetTexts.replace(comp,
                        exp.replace("http://", "").replace("https://", "").replace("www.", "").substring(0, 30)
                                + "...");
            } catch (Exception e) {
                tweetTexts = tweetTexts.replace(comp,
                        exp.replace("http://", "").replace("https://", "").replace("www.", ""));
            }
            if (str.contains("instag") && !str.contains("blog.insta")) {
                imageUrl = exp + "media/?size=m";
                otherUrl += exp + "  ";
            } else if (exp.toLowerCase().contains("youtub")
                    && !(str.contains("channel") || str.contains("user"))) {
                // first get the youtube video code
                int start = exp.indexOf("v=") + 2;
                int end = exp.length();
                if (exp.substring(start).contains("&")) {
                    end = exp.indexOf("&");
                } else if (exp.substring(start).contains("?")) {
                    end = exp.indexOf("?");
                }
                try {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, end) + "/hqdefault.jpg";
                } catch (Exception e) {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, exp.length() - 1)
                            + "/hqdefault.jpg";
                }
                otherUrl += exp + "  ";
            } else if (str.contains("youtu.be")) {
                // first get the youtube video code
                int start = exp.indexOf(".be/") + 4;
                int end = exp.length();
                if (exp.substring(start).contains("&")) {
                    end = exp.indexOf("&");
                } else if (exp.substring(start).contains("?")) {
                    end = exp.indexOf("?");
                }
                try {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, end) + "/hqdefault.jpg";
                } catch (Exception e) {
                    imageUrl = "http://img.youtube.com/vi/" + exp.substring(start, exp.length() - 1)
                            + "/mqefault.jpg";
                }
                otherUrl += exp + "  ";
            } else if (str.contains("twitpic")) {
                int start = exp.indexOf(".com/") + 5;
                imageUrl = "http://twitpic.com/show/full/" + exp.substring(start).replace("/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("i.imgur") && !str.contains("/a/")) {
                int start = exp.indexOf(".com/") + 5;
                imageUrl = "http://i.imgur.com/" + exp.replace("http://i.imgur.com/", "").replace(".jpg", "")
                        + "m.jpg";
                imageUrl = imageUrl.replace("gallery/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("imgur") && !str.contains("/a/")) {
                int start = exp.indexOf(".com/") + 6;
                imageUrl = "http://i.imgur.com/" + exp.replace("http://imgur.com/", "").replace(".jpg", "")
                        + "m.jpg";
                imageUrl = imageUrl.replace("gallery/", "").replace("a/", "");
                otherUrl += exp + "  ";
            } else if (str.contains("pbs.twimg.com")) {
                imageUrl = exp;
                otherUrl += exp + "  ";
            } else if (str.contains("ow.ly/i")) {
                imageUrl = "http://static.ow.ly/photos/original/"
                        + exp.substring(exp.lastIndexOf("/")).replaceAll("/", "") + ".jpg";
                otherUrl += exp + "  ";
            } else if (str.contains("p.twipple.jp")) {
                imageUrl = "http://p.twipple.jp/show/large/" + exp.replace("p.twipple.jp/", "")
                        .replace("http://", "").replace("https://", "").replace("www.", "");
                otherUrl += exp + "  ";
            } else if (str.contains(".jpg") || str.contains(".png")) {
                imageUrl = exp;
                otherUrl += exp + "  ";
            } else {
                otherUrl += exp + "  ";
            }
        }
    }

    for (int i = 0; i < sMediaComp.length; i++) {
        String comp = sMediaComp[i];
        String exp = sMediaExp[i];

        if (comp.length() > 1 && exp.length() > 1) {
            try {
                tweetTexts = tweetTexts.replace(comp, sMediaDisplay[i].replace("http://", "")
                        .replace("https://", "").replace("www.", "").substring(0, 22) + "...");
            } catch (Exception e) {
                tweetTexts = tweetTexts.replace(comp,
                        sMediaDisplay[i].replace("http://", "").replace("https://", "").replace("www.", ""));
            }
            imageUrl = status.getMediaEntities()[0].getMediaURL();

            for (MediaEntity m : status.getExtendedMediaEntities()) {
                if (m.getType().equals("photo")) {
                    if (!imageUrl.contains(m.getMediaURL())) {
                        imageUrl += " " + m.getMediaURL();
                    }
                }
            }

            otherUrl += sMediaDisplay[i];
        }
    }

    return new String[] { tweetTexts, imageUrl, otherUrl, mHashtags, mUsers };
}

From source file:com.krossovochkin.kwitter.fragments.SendTweetFragment.java

License:Apache License

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    final EditText tweetEditText = (EditText) getView().findViewById(R.id.tweet_edit_text);
    final FloatingActionButton sendTweetButton = (FloatingActionButton) getView()
            .findViewById(R.id.send_tweet_button);
    final TextView symbolCounterTextView = (TextView) getView().findViewById(R.id.char_counter_text_view);

    tweetEditText.addTextChangedListener(new TextWatcher() {
        @Override//from  w w w .  j  av a2s  .  c o m
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (tweetEditText.getText() != null) {
                int charsLeft = getResources().getInteger(R.integer.max_tweet_char_length)
                        - tweetEditText.getText().length();
                symbolCounterTextView.setText(String.valueOf(charsLeft));

                if (charsLeft < 0) {
                    sendTweetButton.setEnabled(false);
                } else {
                    sendTweetButton.setEnabled(true);
                }
            }
        }
    });

    if (isReply()) {
        Status status = (Status) getArguments().getSerializable(Constants.STATUS_KEY);
        StringBuilder mentions = new StringBuilder();

        mentions.append("@");
        mentions.append(status.getUser().getScreenName());
        mentions.append(" ");

        for (UserMentionEntity mentionEntity : status.getUserMentionEntities()) {
            mentions.append("@");
            mentions.append(mentionEntity.getScreenName());
            mentions.append(" ");
        }
        tweetEditText.setText(mentions.toString());
    }

    sendTweetButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (twitterActionListener != null) {
                if (tweetEditText.getText() != null) {

                    if (isReply()) {
                        Status status = (Status) getArguments().getSerializable(Constants.STATUS_KEY);
                        twitterActionListener.sendReplyRequest(status, tweetEditText.getText().toString());
                    } else {
                        twitterActionListener.sendTweetRequest(tweetEditText.getText().toString());
                    }

                    getFragmentManager().popBackStack();
                } else {
                    Log.e(TAG, "tweetEditText has no text");
                }
            } else {
                Log.e(TAG, "twitterActionListener from SendTweetFragment is null, did the fragment"
                        + "is attached to activity?");
            }
        }
    });

    KeyboardHelper.showSoftKeyboard(getActivity(), tweetEditText);
}

From source file:com.michaelfitzmaurice.clocktwerk.TweetResponder.java

License:Apache License

private String replyBody(String myScreenName, Status mention, String messageBody) {

    String replyMessage = "@" + mention.getUser().getScreenName() + " ";
    for (UserMentionEntity userMentionEntity : mention.getUserMentionEntities()) {
        String mentionScreenName = userMentionEntity.getScreenName();
        if (mentionScreenName.equalsIgnoreCase(myScreenName) == false) {
            replyMessage += "@" + mentionScreenName + " ";
        }/*from  w  ww.  j  a  v a  2 s .c  o  m*/
    }
    replyMessage += messageBody;

    return replyMessage;
}

From source file:com.mothsoft.alexis.engine.retrieval.TwitterRetrievalTaskImpl.java

License:Apache License

private List<TweetMention> readMentions(Status status) {
    final List<TweetMention> mentions = new ArrayList<TweetMention>();

    if (status.getUserMentionEntities() != null) {
        for (final UserMentionEntity entity : status.getUserMentionEntities()) {

            final Long userId = entity.getId();
            final String name = entity.getName();
            final String screenName = entity.getScreenName();

            final TweetMention mention = new TweetMention((short) entity.getStart(), (short) entity.getEnd(),
                    userId, name, screenName);
            mentions.add(mention);/*from www.j  av  a  2 s  .  c  o m*/
        }
    }

    return mentions;
}

From source file:com.narvis.frontend.twitter.input.Input.java

License:Open Source License

private boolean shouldAnswerTweet(Status status) throws TwitterException {
    // Checking for favorite is useless here
    return (status.getUser().getId() != this.stream.getId()) && !status.isRetweet()
            && isMentionnedIn(status.getUserMentionEntities());
}

From source file:com.projectlaver.util.TwitterListingResponseHandler.java

License:Open Source License

public void processStatus(Status status) {

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("+processStatus() with status id: " + status.getId());
    }/*www.j  ava 2  s .co m*/

    String twitterId = this.longToString(status.getId());
    User profile = status.getUser();

    // Convert twitterIds to Strings here because these fields are treated as varchars by the database
    String providerUserId = this.longToString(profile.getId());
    String inReplyToStatusId = this.longToString(status.getInReplyToStatusId());
    String tweetText = status.getText();
    Boolean isRetweet = (status.getRetweetedStatus() != null);

    // these two fields are required; without an @mention and a #hashtag we do not need to persist this tweet
    String mentionedProviderUserId = this.getMentionedProviderUserId(status.getUserMentionEntities());
    String hashtag = this.getMentionedHashtag(status.getHashtagEntities());

    if (StringUtils.isNoneBlank(mentionedProviderUserId, hashtag)) {

        ReplyMessageDTO dto = new ReplyMessageDTO(SocialProviders.TWITTER, providerUserId, twitterId,
                inReplyToStatusId, null, isRetweet, tweetText, hashtag, INITIAL_STATUS, status.getCreatedAt());

        // Use a try catch here to trap excptions
        try {
            super.processUserMessage(mentionedProviderUserId, dto, false);

            // Retry on deadlock
        } catch (DeadlockLoserDataAccessException e) {

            this.logger.error("Lost deadlock trying to insert tweet. Falling back on retry logic.");
            this.retryProcessAfterDeadlock(mentionedProviderUserId, dto);

            // Log on uncaught exception
        } catch (Exception e) {
            this.logger.error(String.format(
                    "Valid message with id: %s read by stream, but processing failed with an exception.",
                    twitterId), e);
            this.logger.error("UNINSERTED TWEET: " + ToStringBuilder.reflectionToString(dto));
        }
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("-processStatus() with status id: " + status.getId());
    }
}

From source file:com.raythos.sentilexo.twitter.utils.StatusArraysHelper.java

public static Map<String, Long> getUserMentionMap(Status status) {
    @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
    Map<String, Long> result = new HashMap<>();
    for (UserMentionEntity um : status.getUserMentionEntities()) {
        result.put(um.getScreenName(), um.getId());
    }/*from  ww  w. j a  v  a2 s  .c  om*/
    return result;
}

From source file:com.rhymestore.twitter.stream.GetMentionsListener.java

License:Open Source License

@Override
public void onStatus(final Status status) {
    UserMentionEntity[] mentions = status.getUserMentionEntities();
    if (mentions != null) {
        for (UserMentionEntity mention : mentions) {
            try {
                // Check if there is any mention to us
                if (isCurrentUser(twitter, mention.getScreenName())) {
                    // Only reply if it is a valid mention
                    if (isValidMention(status) && !isCurrentUser(twitter, status.getUser().getScreenName())) {
                        LOGGER.debug("Processing tweet {} from {}", status.getId(),
                                status.getUser().getScreenName());

                        ReplyCommand reply = new ReplyCommand(twitter, wordParser, rhymeStore, status);
                        reply.execute();
                    } else {
                        LOGGER.debug("Ignoring mention: {}", status.getText());
                    }//  w ww.j  a  v  a  2s . com

                    // Do not process the same tweet more than once
                    break;
                }
            } catch (TwitterException ex) {
                LOGGER.error("Could not process status: {}", status.getText());
            }
        }
    }
}

From source file:com.rowland.hashtrace.utility.Utility.java

License:Apache License

public static Tweet createTweet(Status status) {
    User user = status.getUser();//from  w  w w  .j  av  a 2 s .  c om

    long tweet_id = status.getId();

    String tweet_text = status.getText();

    Date tweet_text_date = status.getCreatedAt();

    int tweet_retweet_count = status.getRetweetCount();

    int tweet_favourite_count = status.getFavoriteCount();

    int tweet_mentions_count = status.getUserMentionEntities().length;

    String user_name = user.getScreenName();

    String user_image_url = user.getBiggerProfileImageURL();

    String user_cover_url = user.getProfileBackgroundImageURL();

    String user_location = user.getLocation();

    String user_description = user.getDescription();

    Tweet tweet = new Tweet(tweet_id, tweet_text, tweet_text_date, tweet_retweet_count, tweet_favourite_count,
            tweet_mentions_count, user_name, user_image_url, user_location, user_description, user_cover_url);

    return tweet;
}