Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

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

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file: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 .jav  a  2s.  com*/
 */
@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 {
        logger.debug("Starting up Twitter filtering...");

        FilterQuery query = new FilterQuery().track(keywords);
        twitterStream.filter(query);
    }
    super.start();
}

From source file:com.controller.SearchController.java

License:Open Source License

public static String displayTweets(String query) {
    StringBuilder sb = new StringBuilder();
    sb.append(//  ww w.  j  av  a  2 s .co  m
            " <h3 class=\"text-center\"><i class=\"fa fa-twitter-square\"></i>&nbsp;Comments from Twitter</h3>");
    List<Status> tweet = TwitterSearch.configure(query);
    if (tweet.isEmpty()) {
        return "<span class=\"label label-info\">No Tweets results found.</span>";
    }

    if (tweet.size() > 5) {
        // Display a maximum of 5 tweets.
        tweet.subList(5, tweet.size()).clear();
    }

    for (Status status : tweet) {
        sb.append("<div class='thumbnail row'>");
        sb.append("<div class=\"text-center col-xs-2\">");
        sb.append("<img class=\"img-responsive\"' src=");
        sb.append(status.getUser().getBiggerProfileImageURL());
        sb.append(">");
        sb.append("</div>");
        sb.append("<div class=\"col-xs-10\">");
        sb.append(status.getCreatedAt());
        sb.append("<br />");
        sb.append("<strong>");
        sb.append(status.getUser().getScreenName());
        sb.append("&nbsp;</strong>said<br />");
        sb.append(status.getText());
        sb.append("</div>");
        sb.append("</div>");
    }

    return sb.toString();
}

From source file:com.daemon.database.Transactor.java

License:Open Source License

/**
 * Saves a given tweet in the DB if that tweet is not already saved. Only saves
 * the tweet no other information!//w  w w  .j a  v  a 2s  .  c  o  m
 * 
 * @param tweet The tweet to be saved.
 * @throws SQLException
 */
private void saveTweet(Status tweet, RegressionSentimentClassifier sentimentClassifier) throws SQLException {
    // for reweet, save the original tweet first
    if (tweet.getRetweetedStatus() != null) {
        saveAllTransactionSafe(tweet.getRetweetedStatus(), null, sentimentClassifier);
    }
    // then, save the current tweet

    // 1: Set Tweet ID
    prepStatementTweet.setLong(1, tweet.getId());

    // 2 / 3: Set GeoLocation
    if (tweet.getGeoLocation() != null) {
        prepStatementTweet.setFloat(2, (float) tweet.getGeoLocation().getLatitude());
        prepStatementTweet.setFloat(3, (float) tweet.getGeoLocation().getLongitude());
    } else {
        prepStatementTweet.setNull(2, java.sql.Types.NULL);
        prepStatementTweet.setNull(3, java.sql.Types.NULL);
    }

    // 4: Set User ID
    prepStatementTweet.setLong(4, tweet.getUser().getId());

    // 5: Set Reply-Tweet ID
    if (tweet.getInReplyToStatusId() == -1) {
        prepStatementTweet.setNull(5, java.sql.Types.NULL);
    } else {
        prepStatementTweet.setLong(5, tweet.getInReplyToStatusId());
    }

    // 6: Set Retweet-ID
    if (tweet.getRetweetedStatus() != null) {
        prepStatementTweet.setLong(6, tweet.getRetweetedStatus().getId());
    } else {
        prepStatementTweet.setNull(6, java.sql.Types.NULL);
    }

    // 7: Set Creation Date of Tweet
    java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(tweet.getCreatedAt().getTime());
    prepStatementTweet.setTimestamp(7, sqlTimestamp);

    // 8-11: Other attributes:
    prepStatementTweet.setString(8, tweet.getSource());
    prepStatementTweet.setString(9, tweet.getText());
    prepStatementTweet.setString(10, tweet.getIsoLanguageCode());
    prepStatementTweet.setInt(11, tweet.getRetweetCount());

    // 12: Sentiment
    Float sentiment = sentimentClassifier.determineSentiment(tweet.getText(), tweet.getIsoLanguageCode());
    if (sentiment == null) {
        prepStatementTweet.setNull(12, java.sql.Types.NULL);
    } else {
        prepStatementTweet.setFloat(12,
                sentimentClassifier.determineSentiment(tweet.getText(), tweet.getIsoLanguageCode()));
    }

    // execute statement
    prepStatementTweet.addBatch();
}

From source file:com.daemon.database.Transactor.java

License:Open Source License

/**
 * Saves the tweet and makes all necessary alterations in the DB - can be
 * called by saveTweet (in a recursion)!
 * /*from  w w w .  jav a 2s.co  m*/
 * @param tweet The tweet with related information for this tweet to be saved.
 * @param term The term the tweet is associated with. Nullable.
 * @throws SQLException
 */
public void saveAllTransactionSafe(Status tweet, SearchTerm term,
        RegressionSentimentClassifier sentimentClassifier) throws SQLException {
    saveUser(tweet.getUser());
    saveTweet(tweet, sentimentClassifier);
    saveUserMentions(tweet);

    // in the case of a retweet: does not have a Search Term.
    if (term != null) {
        saveTweetWithTerm(tweet, term, sentimentClassifier);
    }
    saveTweetsHashtags(tweet);
}

From source file:com.daemon.database.Transactor.java

License:Open Source License

/**
 * Saves multiple tweets and makes all necessary alterations in the DB.
 * //from  ww  w .  j  ava  2s.  c  o  m
 * @param tweet   The tweet with related information for this tweet to be saved.
 * @param term   The term the tweet is associated with.
 */
public void saveAllTweets(List<Status> tweets, SearchTerm term,
        RegressionSentimentClassifier sentimentClassifier) {
    Status currentTweet = null;
    try {

        for (Status tweet : tweets) {
            currentTweet = tweet;
            // Save the tweet information
            saveAllTransactionSafe(tweet, term, sentimentClassifier);
        }

        // Save all batches
        prepStatementUser.executeBatch();
        prepStatementTweet.executeBatch();
        prepStatementMentions.executeBatch();
        prepStatementTweetWithTerm.executeBatch();
        prepStatementHashtag.executeBatch();
        prepStatementTweetHasHashtag.executeBatch();

        connect.commit();
    } catch (Exception e) {
        _logger.log("Cannot save data: " + e.getMessage());
        if (connect != null) {
            try {
                _logger.log("Transaction is being rolled back for tweet-id:" + currentTweet.getId()
                        + " and term-id: " + term.getId());
                connect.rollback();
            } catch (SQLException excep) {
                _logger.log("Could not rollback the transaction:");
                _logger.logStackTrace(excep);
            } catch (Exception excep) {
                _logger.log("Could not rollback the transaction, because the search term has no id, yet.");
                _logger.logStackTrace(excep);
            }
        }
        _logger.log(getTweetErrorString(currentTweet));
        _logger.log(getUserErrorString(currentTweet.getUser()));
        _logger.log("Stack trace for the failed saving of data.");
        _logger.logStackTrace(e);
    }
}

From source file:com.daiv.android.twitter.adapters.ArrayListLoader.java

License:Apache License

@Override
public String getItemParams(Adapter adapter, int position) {
    try {//from   w  w  w  .j  av a2 s  .c  om
        Status status = (Status) adapter.getItem(position);
        String url;

        if (!status.isRetweet()) {
            url = status.getUser().getBiggerProfileImageURL();
        } else {
            url = status.getRetweetedStatus().getUser().getBiggerProfileImageURL();
        }
        return url;
    } catch (Exception e) {
        // no items...
        Log.v("getting_url", "no url found");
        return "";
    }
}

From source file:com.daiv.android.twitter.adapters.PicturesArrayAdapter.java

License:Apache License

public void bindView(final View view, Context mContext, final String url, final Status status) {
    final ViewHolder holder = (ViewHolder) view.getTag();

    Log.v("Test_picture", "text: " + status.getText());

    Status thisStatus;/*from  w w  w.ja  v a 2  s. c  o  m*/

    String retweeter;
    final long time = status.getCreatedAt().getTime();
    long originalTime = 0;

    if (status.isRetweet()) {
        retweeter = status.getUser().getScreenName();

        thisStatus = status.getRetweetedStatus();
        originalTime = thisStatus.getCreatedAt().getTime();
    } else {
        retweeter = "";

        thisStatus = status;
    }
    final String fRetweeter = retweeter;

    final long fOriginalTime = originalTime;

    User user = thisStatus.getUser();

    final long id = thisStatus.getId();
    final String profilePic = user.getBiggerProfileImageURL();
    String tweetTexts = thisStatus.getText();
    final String name = user.getName();
    final String screenname = user.getScreenName();

    String[] html = TweetLinkUtils.getLinksInStatus(thisStatus);
    final String tweetText = html[0];
    final String picUrl = html[1];
    final String otherUrl = html[2];
    final String hashtags = html[3];
    final String users = html[4];

    holder.url = url;

    holder.iv.loadImage(url, false, new NetworkedCacheableImageView.OnImageLoadedListener() {
        @Override
        public void onImageLoaded(CacheableBitmapDrawable result) {
            holder.iv.setBackgroundDrawable(null);
        }
    });

    holder.iv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String link;

            boolean displayPic = !picUrl.equals("");
            if (displayPic) {
                link = picUrl;
            } else {
                link = otherUrl.split("  ")[0];
            }

            Log.v("tweet_page", "clicked");
        }
    });

}

From source file:com.daiv.android.twitter.adapters.TimelineArrayAdapter.java

License:Apache License

public void bindView(final View view, Status status, int position) {
    final ViewHolder holder = (ViewHolder) view.getTag();

    if (holder.expandArea.getVisibility() == View.VISIBLE) {
        removeExpansionNoAnimation(holder);
    }//from www .j a  v a  2s  .  c om

    Status thisStatus;

    String retweeter;
    final long time = status.getCreatedAt().getTime();
    long originalTime = 0;

    if (status.isRetweet()) {
        retweeter = status.getUser().getScreenName();

        thisStatus = status.getRetweetedStatus();
        originalTime = thisStatus.getCreatedAt().getTime();
    } else {
        retweeter = "";

        thisStatus = status;
    }

    final long fOriginalTime = originalTime;

    User user = thisStatus.getUser();

    holder.tweetId = thisStatus.getId();
    final long id = holder.tweetId;
    final String profilePic = user.getOriginalProfileImageURL();
    String tweetTexts = thisStatus.getText();
    final String name = user.getName();
    final String screenname = user.getScreenName();

    String[] html = TweetLinkUtils.getLinksInStatus(thisStatus);

    final String tweetText = html[0];
    final String picUrl = html[1];
    holder.picUrl = picUrl;
    final String otherUrl = html[2];
    final String hashtags = html[3];
    final String users = html[4];

    final boolean inAConversation = thisStatus.getInReplyToStatusId() != -1;

    holder.gifUrl = TweetLinkUtils.getGIFUrl(status, otherUrl);

    if (holder.isAConversation != null) {
        if (inAConversation) {
            if (holder.isAConversation.getVisibility() != View.VISIBLE) {
                holder.isAConversation.setVisibility(View.VISIBLE);
            }
        } else {
            if (holder.isAConversation.getVisibility() != View.GONE) {
                holder.isAConversation.setVisibility(View.GONE);
            }
        }
    }

    if (!settings.reverseClickActions) {
        final String fRetweeter = retweeter;
        holder.background.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {

                String link;

                boolean hasGif = holder.gifUrl != null && !holder.gifUrl.isEmpty();
                boolean displayPic = !holder.picUrl.equals("") && !holder.picUrl.contains("youtube")
                        && !(hasGif);
                if (displayPic) {
                    link = holder.picUrl;
                } else {
                    link = otherUrl.split("  ")[0];
                }

                Log.v("tweet_page", "clicked");

                return true;
            }
        });

        holder.background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.preventNextClick) {
                    holder.preventNextClick = false;
                    return;
                }
                if (holder.expandArea.getVisibility() == View.GONE) {
                    addExpansion(holder, screenname, users, otherUrl.split("  "), holder.picUrl, id);
                } else {
                    removeExpansionWithAnimation(holder);
                    removeKeyboard(holder);
                }
            }
        });

    } else {
        final String fRetweeter = retweeter;
        holder.background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.preventNextClick) {
                    holder.preventNextClick = false;
                    return;
                }

                String link;

                boolean hasGif = holder.gifUrl != null && !holder.gifUrl.isEmpty();
                boolean displayPic = !holder.picUrl.equals("") && !holder.picUrl.contains("youtube")
                        && !(hasGif);
                if (displayPic) {
                    link = holder.picUrl;
                } else {
                    link = otherUrl.split("  ")[0];
                }

                Log.v("tweet_page", "clicked");
            }
        });

        holder.background.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (holder.expandArea.getVisibility() == View.GONE) {
                    addExpansion(holder, screenname, users, otherUrl.split("  "), holder.picUrl, id);
                } else {
                    removeExpansionWithAnimation(holder);
                    removeKeyboard(holder);
                }

                return true;
            }
        });
    }

    if (!screenname.equals(username)) {

    } else {
        // need to clear the click listener so it isn't left over from another profile
        holder.profilePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        holder.profilePic.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View view) {
                return true;
            }
        });
    }

    if (TestLayout == AppSettings.LAYOUT_FULL_SCREEN
            || (settings.nameAndHandleOnTweet && settings.addonTheme)) {
        if (holder.screenTV.getVisibility() == View.GONE) {
            holder.screenTV.setVisibility(View.VISIBLE);
        }
        holder.screenTV.setText("@" + screenname);
        holder.name.setText(name);
    } else {
        if (!settings.showBoth) {
            holder.name.setText(settings.displayScreenName ? "@" + screenname : name);
        } else {
            if (holder.screenTV.getVisibility() == View.GONE) {
                holder.screenTV.setVisibility(View.VISIBLE);
            }
            holder.name.setText(name);
            holder.screenTV.setText("@" + screenname);
        }
    }

    if (!settings.absoluteDate) {
        holder.time.setText(Utils.getTimeAgo(time, context));
    } else {
        Date date = new Date(time);
        holder.time
                .setText(timeFormatter.format(date).replace("24:", "00:") + ", " + dateFormatter.format(date));
    }

    holder.tweet.setText(tweetText);

    boolean picture = false;

    if (settings.inlinePics) {
        if (holder.picUrl.equals("")) {
            if (holder.image.getVisibility() != View.GONE) {
                holder.image.setVisibility(View.GONE);
            }

            if (holder.playButton.getVisibility() == View.VISIBLE) {
                holder.playButton.setVisibility(View.GONE);
            }
        } else {
            if (holder.picUrl.contains("youtube")
                    || (holder.gifUrl != null && !android.text.TextUtils.isEmpty(holder.gifUrl))) {

                if (holder.playButton.getVisibility() == View.GONE) {
                    holder.playButton.setVisibility(View.VISIBLE);
                }

                final String fRetweeter = retweeter;

                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String link;

                        boolean hasGif = holder.gifUrl != null && !holder.gifUrl.isEmpty();
                        boolean displayPic = !holder.picUrl.equals("") && !holder.picUrl.contains("youtube")
                                && !(hasGif);
                        if (displayPic) {
                            link = holder.picUrl;
                        } else {
                            link = otherUrl.split("  ")[0];
                        }
                    }
                });

                holder.image.setImageDrawable(transparent);

                picture = true;

            } else {
                holder.image.setImageDrawable(transparent);

                picture = true;

                if (holder.playButton.getVisibility() == View.VISIBLE) {
                    holder.playButton.setVisibility(View.GONE);
                }
            }

            if (holder.image.getVisibility() == View.GONE) {
                holder.image.setVisibility(View.VISIBLE);
            }
        }
    }

    if (type == NORMAL) {
        if (retweeter.length() > 0) {
            holder.retweeter.setText(context.getResources().getString(R.string.retweeter) + retweeter);
            holder.retweeterName = retweeter;
            holder.retweeter.setVisibility(View.VISIBLE);
        } else if (holder.retweeter.getVisibility() == View.VISIBLE) {
            holder.retweeter.setVisibility(View.GONE);
        }
    } else if (type == RETWEET) {

        int count = status.getRetweetCount();

        if (count > 1) {
            holder.retweeter.setText(
                    status.getRetweetCount() + " " + context.getResources().getString(R.string.retweets_lower));
            holder.retweeter.setVisibility(View.VISIBLE);
        } else if (count == 1) {
            holder.retweeter.setText(
                    status.getRetweetCount() + " " + context.getResources().getString(R.string.retweet_lower));
            holder.retweeter.setVisibility(View.VISIBLE);
        }
    }

    if (picture) {
        CacheableBitmapDrawable wrapper = mCache.getFromMemoryCache(holder.picUrl);
        if (wrapper != null) {
            holder.image.setImageDrawable(wrapper);
            picture = false;
        }
    }

    final boolean hasPicture = picture;
    mHandler[currHandler].removeCallbacksAndMessages(null);
    mHandler[currHandler].postDelayed(new Runnable() {
        @Override
        public void run() {
            if (holder.tweetId == id) {
                if (hasPicture) {
                    loadImage(context, holder, holder.picUrl, mCache, id);
                }

                if (settings.useEmoji
                        && (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || EmojiUtils.ios)) {
                    String text = holder.tweet.getText().toString();
                    if (EmojiUtils.emojiPattern.matcher(text).find()) {
                        final Spannable span = EmojiUtils.getSmiledText(context, Html.fromHtml(tweetText));
                        holder.tweet.setText(span);
                    }
                }

                holder.tweet.setSoundEffectsEnabled(false);
                holder.tweet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (!TouchableMovementMethod.touched) {
                            // we need to manually set the background for click feedback because the spannable
                            // absorbs the click on the background
                            if (!holder.preventNextClick) {
                                holder.background.getBackground()
                                        .setState(new int[] { android.R.attr.state_pressed });
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        holder.background.getBackground()
                                                .setState(new int[] { android.R.attr.state_empty });
                                    }
                                }, 25);
                            }

                            holder.background.performClick();
                        }
                    }
                });

                holder.tweet.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        if (!TouchableMovementMethod.touched) {
                            holder.background.performLongClick();
                            holder.preventNextClick = true;
                        }
                        return false;
                    }
                });

                if (holder.retweeter.getVisibility() == View.VISIBLE) {
                    holder.retweeter.setSoundEffectsEnabled(false);
                    holder.retweeter.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (!TouchableMovementMethod.touched) {
                                if (!holder.preventNextClick) {
                                    holder.background.getBackground()
                                            .setState(new int[] { android.R.attr.state_pressed });
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            holder.background.getBackground()
                                                    .setState(new int[] { android.R.attr.state_empty });
                                        }
                                    }, 25);
                                }

                                holder.background.performClick();
                            }
                        }
                    });

                    holder.retweeter.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View view) {
                            if (!TouchableMovementMethod.touched) {
                                holder.background.performLongClick();
                                holder.preventNextClick = true;
                            }
                            return false;
                        }
                    });
                }

                TextUtils.linkifyText(context, holder.tweet, holder.background, true, otherUrl, false);
                TextUtils.linkifyText(context, holder.retweeter, holder.background, true, "", false);
            }
        }
    }, 400);
    currHandler++;

    if (currHandler == 10) {
        currHandler = 0;
    }

    if (openFirst && position == 0) {
        holder.background.performClick();
    }
}

From source file:com.daiv.android.twitter.adapters.TimelineArrayAdapter.java

License:Apache License

public void addExpansion(final ViewHolder holder, String screenname, String users, final String[] otherLinks,
        final String webpage, final long id) {

    holder.retweet.setVisibility(View.VISIBLE);
    holder.retweetCount.setVisibility(View.VISIBLE);
    holder.favCount.setVisibility(View.VISIBLE);
    holder.favorite.setVisibility(View.VISIBLE);

    //holder.reply.setVisibility(View.GONE);
    try {/*from  ww w  . j  a  va 2 s.  c  o  m*/
        holder.replyButton.setVisibility(View.GONE);
    } catch (Exception e) {

    }

    holder.screenName = screenname;

    // used to find the other names on a tweet... could be optimized i guess, but only run when button is pressed
    final String text = holder.tweet.getText().toString();
    String extraNames = "";

    if (text.contains("@")) {
        for (String s : users.split("  ")) {
            if (!s.equals(settings.myScreenName) && !extraNames.contains(s) && !s.equals(screenname)) {
                extraNames += "@" + s + " ";
            }
        }
    }

    try {
        if (holder.retweeter.getVisibility() == View.VISIBLE && !extraNames.contains(holder.retweeterName)) {
            extraNames += "@" + holder.retweeterName + " ";
        }
    } catch (NullPointerException e) {

    }

    if (!screenname.equals(settings.myScreenName)) {
        holder.reply.setText("@" + screenname + " " + extraNames);
    } else {
        holder.reply.setText(extraNames);
    }

    holder.reply.setSelection(holder.reply.getText().length());

    if (holder.favCount.getText().toString().length() <= 2) {
        holder.favCount.setText(" -");
        holder.retweetCount.setText(" -");
    }

    //ExpansionAnimation expandAni = new ExpansionAnimation(holder.expandArea, 450);
    holder.expandArea.setVisibility(View.VISIBLE);//startAnimation(expandAni);

    getCounts(holder, id);

    holder.favorite.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (holder.isFavorited || !settings.crossAccActions) {
                new FavoriteStatus(holder, holder.tweetId, FavoriteStatus.TYPE_ACC_ONE).execute();
            } else if (settings.crossAccActions) {
                // dialog for favoriting
                String[] options = new String[3];

                options[0] = "@" + settings.myScreenName;
                options[1] = "@" + settings.secondScreenName;
                options[2] = context.getString(R.string.both_accounts);

                new AlertDialog.Builder(context).setItems(options, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int item) {
                        new FavoriteStatus(holder, holder.tweetId, item + 1).execute();
                    }
                }).create().show();
            }
        }
    });

    holder.retweet.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!settings.crossAccActions) {
                new RetweetStatus(holder, holder.tweetId, FavoriteStatus.TYPE_ACC_ONE).execute();
            } else {
                // dialog for favoriting
                String[] options = new String[3];

                options[0] = "@" + settings.myScreenName;
                options[1] = "@" + settings.secondScreenName;
                options[2] = context.getString(R.string.both_accounts);

                new AlertDialog.Builder(context).setItems(options, new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, final int item) {
                        new RetweetStatus(holder, holder.tweetId, item + 1).execute();
                    }
                }).create().show();
            }
        }
    });

    holder.retweet.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            new AlertDialog.Builder(context).setTitle(context.getResources().getString(R.string.remove_retweet))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            new RemoveRetweet(holder.tweetId).execute();
                        }
                    }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).create().show();
            return false;
        }

        class RemoveRetweet extends AsyncTask<String, Void, Boolean> {

            private long tweetId;

            public RemoveRetweet(long tweetId) {
                this.tweetId = tweetId;
            }

            protected void onPreExecute() {
                holder.retweet.clearColorFilter();

                Toast.makeText(context, context.getResources().getString(R.string.removing_retweet),
                        Toast.LENGTH_SHORT).show();
            }

            protected Boolean doInBackground(String... urls) {
                try {
                    Twitter twitter = Utils.getTwitter(context, settings);
                    ResponseList<twitter4j.Status> retweets = twitter.getRetweets(tweetId);
                    for (twitter4j.Status retweet : retweets) {
                        if (retweet.getUser().getId() == settings.myId)
                            twitter.destroyStatus(retweet.getId());
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }

            protected void onPostExecute(Boolean deleted) {
                try {
                    if (deleted) {
                        Toast.makeText(context, context.getResources().getString(R.string.success),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, context.getResources().getString(R.string.error),
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    // user has gone away from the window
                }
            }
        }
    });

    holder.reply.requestFocus();
    removeKeyboard(holder);
    holder.reply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent compose = new Intent(context, ComposeActivity.class);
            String string = holder.reply.getText().toString();
            try {
                compose.putExtra("user", string.substring(0, string.length() - 1));
            } catch (Exception e) {

            }
            compose.putExtra("id", holder.tweetId);
            compose.putExtra("reply_to_text", "@" + holder.screenName + ": " + text);
            context.startActivity(compose);

            removeExpansionWithAnimation(holder);
        }
    });

    if (holder.replyButton != null) {
        holder.replyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new ReplyToStatus(holder, holder.tweetId).execute();
            }
        });
    }

    final String name = screenname;

    try {
        holder.shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                String text = holder.tweet.getText().toString();

                text = TweetLinkUtils.removeColorHtml(text, settings);
                text = restoreLinks(text);

                switch (settings.quoteStyle) {
                case AppSettings.QUOTE_STYLE_TWITTER:
                    text = " " + "https://twitter.com/" + name + "/status/" + id;
                    break;
                case AppSettings.QUOTE_STYLE_Test:
                    text = "\"@" + name + ": " + text + "\" ";
                    break;
                case AppSettings.QUOTE_STYLE_RT:
                    text = " RT @" + name + ": " + text;
                    break;
                }
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.putExtra(Intent.EXTRA_TEXT, text);
                context.startActivity(
                        Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            }

            public String restoreLinks(String text) {
                String full = text;

                String[] split = text.split("\\s");
                String[] otherLink = new String[otherLinks.length];

                for (int i = 0; i < otherLinks.length; i++) {
                    otherLink[i] = "" + otherLinks[i];
                }

                for (String s : otherLink) {
                    Log.v("Test_links", ":" + s + ":");
                }

                boolean changed = false;
                int otherIndex = 0;

                if (otherLink.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];

                        //if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
                        if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
                            String f = s.replace("...", "").replace("http", "");

                            f = stripTrailingPeriods(f);

                            try {
                                if (otherIndex < otherLinks.length) {
                                    if (otherLink[otherIndex].substring(otherLink[otherIndex].length() - 1,
                                            otherLink[otherIndex].length()).equals("/")) {
                                        otherLink[otherIndex] = otherLink[otherIndex].substring(0,
                                                otherLink[otherIndex].length() - 1);
                                    }
                                    f = otherLink[otherIndex].replace("http://", "").replace("https://", "")
                                            .replace("www.", "");
                                    otherLink[otherIndex] = "";
                                    otherIndex++;

                                    changed = true;
                                }
                            } catch (Exception e) {

                            }

                            if (changed) {
                                split[i] = f;
                            } else {
                                split[i] = s;
                            }
                        } else {
                            split[i] = s;
                        }

                    }
                }

                if (!webpage.equals("")) {
                    for (int i = split.length - 1; i >= 0; i--) {
                        String s = split[i];
                        if (Patterns.WEB_URL.matcher(s).find()) {
                            String replace = otherLinks[otherLinks.length - 1];
                            if (replace.replace(" ", "").equals("")) {
                                replace = webpage;
                            }
                            split[i] = replace;
                            changed = true;
                            break;
                        }
                    }
                }

                if (changed) {
                    full = "";
                    for (String p : split) {
                        full += p + " ";
                    }

                    full = full.substring(0, full.length() - 1);
                }

                return full;
            }

            private String stripTrailingPeriods(String url) {
                try {
                    if (url.substring(url.length() - 1, url.length()).equals(".")) {
                        return stripTrailingPeriods(url.substring(0, url.length() - 1));
                    } else {
                        return url;
                    }
                } catch (Exception e) {
                    return url;
                }
            }
        });

        holder.quoteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, ComposeActivity.class);
                intent.setType("text/plain");
                String text = holder.tweet.getText().toString();

                text = TweetLinkUtils.removeColorHtml(text, settings);
                text = restoreLinks(text);

                switch (settings.quoteStyle) {
                case AppSettings.QUOTE_STYLE_TWITTER:
                    text = " " + "https://twitter.com/" + name + "/status/" + id;
                    break;
                case AppSettings.QUOTE_STYLE_Test:
                    text = "\"@" + name + ": " + text + "\" ";
                    break;
                case AppSettings.QUOTE_STYLE_RT:
                    text = " RT @" + name + ": " + text;
                    break;
                }
                intent.putExtra("user", text);
                intent.putExtra("id", id);

                context.startActivity(intent);
            }

            public String restoreLinks(String text) {
                String full = text;

                String[] split = text.split("\\s");
                String[] otherLink = new String[otherLinks.length];

                for (int i = 0; i < otherLinks.length; i++) {
                    otherLink[i] = "" + otherLinks[i];
                }

                boolean changed = false;

                if (otherLink.length > 0) {
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];

                        //if (Patterns.WEB_URL.matcher(s).find()) { // we know the link is cut off
                        if (s.contains("...")) { // we know the link is cut off
                            String f = s.replace("...", "").replace("http", "");

                            Log.v("Test_links", ":" + s + ":");

                            for (int x = 0; x < otherLink.length; x++) {
                                if (otherLink[x].toLowerCase().contains(f.toLowerCase())) {
                                    changed = true;
                                    // for some reason it wouldn't match the last "/" on a url and it was stopping it from opening
                                    try {
                                        if (otherLink[x]
                                                .substring(otherLink[x].length() - 1, otherLink[x].length())
                                                .equals("/")) {
                                            otherLink[x] = otherLink[x].substring(0, otherLink[x].length() - 1);
                                        }
                                        f = otherLink[x].replace("http://", "").replace("https://", "")
                                                .replace("www.", "");
                                        otherLink[x] = "";
                                    } catch (Exception e) {

                                    }
                                    break;
                                }
                            }

                            if (changed) {
                                split[i] = f;
                            } else {
                                split[i] = s;
                            }
                        } else {
                            split[i] = s;
                        }

                    }
                }

                if (!webpage.equals("")) {
                    for (int i = 0; i < split.length; i++) {
                        String s = split[i];
                        s = s.replace("...", "");

                        if (Patterns.WEB_URL.matcher(s).find()
                                && (s.startsWith("t.co/") || s.contains("twitter.com/"))) { // we know the link is cut off
                            String replace = otherLinks[otherLinks.length - 1];
                            if (replace.replace(" ", "").equals("")) {
                                replace = webpage;
                            }
                            split[i] = replace;
                            changed = true;
                        }
                    }
                }

                if (changed) {
                    full = "";
                    for (String p : split) {
                        full += p + " ";
                    }

                    full = full.substring(0, full.length() - 1);
                }

                return full;
            }
        });
    } catch (Exception e) {
        // theme made before these were implemented
    }
}

From source file:com.daiv.android.twitter.data.sq_lite.HomeContentProvider.java

License:Apache License

public static void insertTweet(Status status, int currentAccount, Context context) {
    ContentValues values = new ContentValues();
    String originalName = "";
    long id = status.getId();
    long time = status.getCreatedAt().getTime();

    if (status.isRetweet()) {
        originalName = status.getUser().getScreenName();
        status = status.getRetweetedStatus();
    }/*from  www. j  a  v  a  2s. c  o m*/

    String[] html = TweetLinkUtils.getLinksInStatus(status);
    String text = html[0];
    String media = html[1];
    String url = html[2];
    String hashtags = html[3];
    String users = html[4];

    String source;
    if (status.isRetweet()) {
        source = android.text.Html.fromHtml(status.getRetweetedStatus().getSource()).toString();
    } else {
        source = android.text.Html.fromHtml(status.getSource()).toString();
    }

    values.put(HomeSQLiteHelper.COLUMN_ACCOUNT, currentAccount);
    values.put(HomeSQLiteHelper.COLUMN_TEXT, text);
    values.put(HomeSQLiteHelper.COLUMN_TWEET_ID, id);
    values.put(HomeSQLiteHelper.COLUMN_NAME, status.getUser().getName());
    values.put(HomeSQLiteHelper.COLUMN_PRO_PIC, status.getUser().getOriginalProfileImageURL());
    values.put(HomeSQLiteHelper.COLUMN_SCREEN_NAME, status.getUser().getScreenName());
    values.put(HomeSQLiteHelper.COLUMN_TIME, time);
    values.put(HomeSQLiteHelper.COLUMN_RETWEETER, originalName);
    values.put(HomeSQLiteHelper.COLUMN_UNREAD, 1);
    values.put(HomeSQLiteHelper.COLUMN_PIC_URL, media);
    values.put(HomeSQLiteHelper.COLUMN_URL, url);
    values.put(HomeSQLiteHelper.COLUMN_USERS, users);
    values.put(HomeSQLiteHelper.COLUMN_HASHTAGS, hashtags);
    values.put(HomeSQLiteHelper.COLUMN_CLIENT_SOURCE, source);

    context.getContentResolver().insert(HomeContentProvider.CONTENT_URI, values);
}