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.ahuralab.mozaic.db.Message.java

License:Open Source License

public static Message create(Status status) {

    User user = status.getUser();

    return new Message(status.getText(), status.getCreatedAt(), status.getRetweetCount(), user.getId(),
            user.getName(), user.getScreenName(), user.getLocation(), user.getDescription(),
            user.getProfileImageURL(), status.getId(), 0, 0, user.getFollowersCount(), user.getStatusesCount());
}

From source file:com.alainesp.fan.sanderson.SummaryFragment.java

License:Open Source License

protected int doWork() {
    int state = DownloadParseSaveTask.STATE_SUCCESS;

    try {/*from  w ww .  j  a v  a 2 s  . c  o  m*/
        List<twitter4j.Status> tweets;

        // Twitter client configuration
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TwitterAPISecrets.CONSUMER_KEY)
                .setOAuthConsumerSecret(TwitterAPISecrets.CONSUMER_SECRET);
        // TODO: Use guest authentication instead of application
        builder.setApplicationOnlyAuthEnabled(true).setDebugEnabled(false).setGZIPEnabled(true);

        Twitter twitter = new TwitterFactory(builder.build()).getInstance();
        twitter.getOAuth2Token();

        // Get the tweets
        long lastTweetID = DB.Tweet.getLastTweetID();
        if (lastTweetID <= 0)
            tweets = twitter.getUserTimeline("BrandSanderson");
        else
            tweets = twitter.getUserTimeline("BrandSanderson", new Paging(lastTweetID));

        if (tweets != null) {
            long brandonID = 28187205;
            Hashtable<Long, DB.Tweet> findTweet = new Hashtable<>(tweets.size() * 16, 0.25f);
            List<DB.Tweet> dbTweets = new ArrayList<>(tweets.size());
            for (twitter4j.Status tweet : tweets) {
                // Create the tweet
                if (tweet.isRetweet())
                    tweet = tweet.getRetweetedStatus();

                long tweetID = tweet.getId();
                // TODO: Include the tweets in the DB
                if (findTweet.get(tweetID) == null)// This eliminate tweets already in the replies tree
                {
                    DB.Tweet dbTweet = new DB.Tweet(tweetID, getTweetText(tweet), tweet.getCreatedAt(), false,
                            tweet.getUser().getName(), tweet.getUser().getBiggerProfileImageURLHttps());
                    InternetHelper.getRemoteFile(tweet.getUser().getBiggerProfileImageURLHttps());
                    dbTweets.add(dbTweet);
                    findTweet.put(tweetID, dbTweet);

                    // Traverse the tree of the replies tweets
                    twitter4j.Status treeTweet = tweet;
                    while (treeTweet != null && treeTweet.getInReplyToStatusId() >= 0) {
                        try {
                            long id = treeTweet.getInReplyToStatusId();
                            long userID = treeTweet.getUser().getId();
                            treeTweet = null;
                            if (findTweet.get(id) == null || brandonID == userID)
                                treeTweet = twitter.showStatus(id);
                            else// Remove duplicates. Not sure why they appear, but the difference of the text is a dot at the end.
                                dbTweets.remove(dbTweets.size() - 1);
                        } catch (Exception ignore) {
                        }

                        if (treeTweet != null) {
                            findTweet.put(treeTweet.getId(), dbTweet);
                            StringBuilder replyBuilder = new StringBuilder();

                            replyBuilder.append("<blockquote>");

                            // Profile image
                            replyBuilder.append("<img src=\"");
                            InternetHelper.getRemoteFile(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append("\"/>&nbsp;<b>");

                            // Username - date
                            replyBuilder.append(treeTweet.getUser().getName());
                            replyBuilder.append("</b> @");
                            replyBuilder.append(treeTweet.getUser().getScreenName());
                            replyBuilder.append(" - ");
                            replyBuilder
                                    .append(TwitterFragment.showDateFormat.format(treeTweet.getCreatedAt()));

                            // Tweet text
                            replyBuilder.append("<br/>");
                            replyBuilder.append(getTweetText(treeTweet));

                            // Remaining
                            replyBuilder.append(dbTweet.htmlReply);
                            replyBuilder.append("</blockquote>");

                            dbTweet.htmlReply = replyBuilder.toString();
                        }
                    }
                }
            }
            DB.Tweet.updateTwitter(dbTweets);
        }
    } catch (Exception e) {
        Logger.reportError(e.toString());
        state = DownloadParseSaveTask.STATE_ERROR_PARSING;
    }

    return state;
}

From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java

License:Open Source License

@Command(name = "twitter", desc = "displays the last tweet of a twitter user", aliases = { "twit" })
@Usage(".twitter <user>")
public CommandResult twitter(CommandSource source, CommandContext context) {
    if (source.getSource() == CommandSource.Source.USER
            && (context.getPrefix() == null || !context.getPrefix().equals("."))) {
        return null;
    }/*from   ww  w . j a  v a 2 s  .  c o m*/
    if (context.getArgs() == null || context.getArgs().length < 1) {
        return get(ReturnType.NOTICE, "Correct usage is .twitter <user>", source, context);
    }

    try {
        List<Status> statusList = twitter.getUserTimeline(context.getArgs()[0]);
        if (statusList == null || statusList.size() < 1) {
            return get(ReturnType.MESSAGE, "User has no tweets!", source, context);
        }
        Status status = statusList.get(0);
        status.getUser();
        StringBuilder builder = new StringBuilder();
        builder.append(status.getUser().getScreenName()).append(Colors.BLUE).append(": ").append(Colors.NORMAL)
                .append(status.getText()).append(" (");

        Period period = new Period(new DateTime(status.getCreatedAt()), new DateTime());
        if (period.getWeeks() > 2 || period.getMonths() > 1 || period.getYears() > 1) {
            builder.append(longTimeFormatter.print(period));
        } else {
            builder.append(timeFormatter.print(period));
        }
        builder.append(" ago)");
        return get(ReturnType.MESSAGE, builder.toString().replace(lineBreak, " "), source, context);
    } catch (TwitterException e) {
        if (e.getStatusCode() == 404) {
            return get(ReturnType.MESSAGE, "User not found!", source, context);
        } else if (e.getStatusCode() == 401) {
            return get(ReturnType.MESSAGE, "Access denied by Twitter!", source, context);
        } else {
            e.printStackTrace();
            return get(ReturnType.MESSAGE, "There was an internal error!", source, context);
        }
    }
}

From source file:com.androtwitt.ExampleAppWidgetProvider.java

License:Apache License

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

    Log.d(TAG, "updateAppWidget appWidgetId=" + appWidgetId);
    ArrayList lines = new ArrayList();

    Twitter unauthenticatedTwitter = new TwitterFactory().getInstance();
    System.out.println("Showing public timeline.");
    try {/*from   w  ww .  j a v a 2 s. c  o m*/
        List<Status> statuses = unauthenticatedTwitter.getPublicTimeline();

        // Other methods require authentication
        String username = ExampleAppWidgetConfigure.loadTitlePref(context, appWidgetId, "username");
        String password = ExampleAppWidgetConfigure.loadTitlePref(context, appWidgetId, "password");

        Twitter twitter = new TwitterFactory().getInstance(username, password);
        statuses = twitter.getFriendsTimeline();
        for (Status status : statuses) {
            lines.add(status.getUser().getScreenName() + ":" + status.getText());
        }
    } catch (TwitterException te) {
        Log.d("AT_Error", "Failed to get timeline: " + te.getMessage());
    }

    // Construct the RemoteViews object.  It takes the package name (in our case, it's our
    // package, but it needs this because on the other side it's the widget host inflating
    // the layout from our package).
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);
    ArrayList<Integer> widgetTexts = new ArrayList();
    widgetTexts.add(R.id.appwidget_text0);
    widgetTexts.add(R.id.appwidget_text1);
    widgetTexts.add(R.id.appwidget_text2);
    widgetTexts.add(R.id.appwidget_text3);
    widgetTexts.add(R.id.appwidget_text4);
    widgetTexts.add(R.id.appwidget_text5);
    widgetTexts.add(R.id.appwidget_text6);
    widgetTexts.add(R.id.appwidget_text7);
    widgetTexts.add(R.id.appwidget_text8);
    widgetTexts.add(R.id.appwidget_text9);

    Iterator i = widgetTexts.iterator();
    Iterator j = lines.iterator();
    while (i.hasNext()) {
        Integer value = (Integer) i.next();
        if (j.hasNext()) {
            views.setTextViewText(value, (String) j.next());
        }
    }

    // Tell the widget manager
    appWidgetManager.updateAppWidget(appWidgetId, views);
}

From source file:com.appspot.bitlyminous.handler.twitter.AddUrlToDeliciousHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {/*from   w  w  w  .  ja va  2s . c  om*/
        User user = context.getUser();
        if (user == null) {
            user = getUserByScreenName(tweet.getUser().getScreenName());
            context.setUser(user);
        }
        if (user.getDeliciousToken() != null && user.getDeliciousSecret() != null) {
            DeliciousGateway gateway = GATEWAY_FACTORY.createDeliciousGateway(
                    ApplicationConstants.DELICIOUS_CONSUMER_KEY, ApplicationConstants.DELICIOUS_CONSUMER_SECRET,
                    user.getDeliciousToken().getValue(), user.getDeliciousSecret().getValue());
            gateway.getOAuthAuthentication().setOauthSessionHandle(user.getDeliciousSessionHandle().getValue());
            List<Url> urls = context.getUrls();
            for (Url entity : urls) {
                try {
                    gateway.addUrl(entity);
                } catch (GatewayException e) {
                    if (e.getErrorCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                        gateway.refreshToken(user.getDeliciousSessionHandle().getValue());
                        user.setDeliciousToken(new Text(gateway.getOAuthAuthentication().getAccessToken()));
                        user.setDeliciousSecret(
                                new Text(gateway.getOAuthAuthentication().getAccessTokenSecret()));
                        user.setDeliciousSessionHandle(
                                new Text(gateway.getOAuthAuthentication().getOauthSessionHandle()));
                        gateway.addUrl(entity);
                    } else {
                        throw e;
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while adding url to delicious.", e);
    }
    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.AddUrlToGoogleCSEHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {// ww w.ja  v a 2s .  c  o m
        User user = context.getUser();
        if (user == null) {
            user = getUserByScreenName(tweet.getUser().getScreenName());
            context.setUser(user);
        }
        if (user.getSearchEngineId() != null) {
            List<Url> urls = context.getUrls();
            for (Url entity : urls) {
                // TODO-Later: Add to custom search engine.
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while adding url to delicious.", e);
    }
    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.NearByHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    GeoLocation geoLocation = tweet.getGeoLocation();
    String text = getMentionText(tweet);
    if (geoLocation == null) {
        StatusUpdate reply = new StatusUpdate(
                ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.noLocation",
                        new String[] { "@" + tweet.getUser().getScreenName() }));
        reply.setInReplyToStatusId(tweet.getId());
        return reply;
    } else {/*  w  w  w  .  ja v a  2s .  co m*/
        try {
            GeoQuery query = new GeoQuery(geoLocation);
            List<Tip> nearbyTips = getFoursquareGateway()
                    .getNearbyTips(new com.appspot.bitlyminous.entity.GeoLocation(geoLocation.getLatitude(),
                            geoLocation.getLongitude()), 1);
            String status = buildTipsStatus(nearbyTips);

            if (nearbyTips.isEmpty()) {
                List<Venue> nearbyVenues = new ArrayList<Venue>();
                if (text != null) {
                    nearbyVenues = getFoursquareGateway().getNearbyVenues(
                            new com.appspot.bitlyminous.entity.GeoLocation(geoLocation.getLatitude(),
                                    geoLocation.getLongitude()),
                            text, 1);
                }
                status = status + buildVenuesStatus(nearbyVenues);
                if (nearbyVenues.isEmpty()) {
                    List<Place> nearbyPlaces = getTwitterClient().getNearbyPlaces(query);
                    status = status + buildPlacesStatus(nearbyPlaces);
                }

            }
            status = "@" + tweet.getUser().getScreenName() + " " + status;
            StatusUpdate reply = new StatusUpdate(status);
            reply.setInReplyToStatusId(tweet.getId());
            return reply;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error while getting nearby places", e);
        }
        return null;
    }
}

From source file:com.appspot.bitlyminous.handler.twitter.RetweetRelatedTweetsHandler.java

License:Apache License

/**
 * Builds the status./*from   w w w .  j  a  v  a 2s.c  om*/
 * 
 * @param tweet the tweet
 * @param relatedTweets the related tweets
 * 
 * @return the string
 */
private String buildStatus(Status tweet, List<WebResult> relatedTweets) {
    for (WebResult webResult : relatedTweets) {
        String user = getUserFromResult(webResult.getUnescapedUrl());
        if (user != null) {
            return "@" + tweet.getUser().getScreenName() + " RT @" + user
                    + trimText(webResult.getContent(), 100);
        }
    }

    return "";
}

From source file:com.appspot.bitlyminous.handler.twitter.SaveUserHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {//  w w w . j a v a2s . c  o  m
        User user = getUserByScreenName(tweet.getUser().getScreenName());
        if (user == null) {
            user = new User();
            user.setScreenName(tweet.getUser().getScreenName());
            user.setLevel(User.Level.DIRECT_USER);
        }
        context.setUser(user);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while persisting urls.", e);
    }

    return null;
}

From source file:com.appspot.bitlyminous.handler.twitter.ScanLinkHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    try {//w  ww . jav  a 2  s. c  om
        List<String> shortUrls = extractBitlyUrls(tweet.getText());
        if (!shortUrls.isEmpty()) {
            Set<Url> longUrls = getBitlyClient()
                    .call(Bitly.expand(shortUrls.toArray(new String[shortUrls.size()])));
            GoogleSafeBrowsingGateway gateway = getGoogleSafeBrowsingGateway();
            for (Url url : longUrls) {
                if (!isEmpty(url.getLongUrl())) {
                    if (gateway.isBlacklisted(url.getLongUrl())) {
                        StatusUpdate reply = new StatusUpdate(ApplicationResources.getLocalizedString(
                                "com.appspot.bitlyminous.message.badurl",
                                new String[] { "@" + tweet.getUser().getScreenName(),
                                        trimText(tweet.getText(), 20),
                                        ApplicationConstants.GOOGLE_SAFE_BROWSING_REF_URL }));
                        reply.setInReplyToStatusId(tweet.getId());
                        return reply;
                    }
                    if (gateway.isMalwarelisted(url.getLongUrl())) {
                        StatusUpdate reply = new StatusUpdate(ApplicationResources.getLocalizedString(
                                "com.appspot.bitlyminous.message.badurl",
                                new String[] { "@" + tweet.getUser().getScreenName(),
                                        trimText(tweet.getText(), 20),
                                        ApplicationConstants.GOOGLE_SAFE_BROWSING_REF_URL }));
                        reply.setInReplyToStatusId(tweet.getId());
                        return reply;
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error while scanning urls.", e);
    }
    return null;
}