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.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 . j  a v a 2 s .c  om*/
    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.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets the most recent messages where your username is mentioned.
 *///  w  w  w  .j  ava2 s .co m
@SimpleFunction(description = "Requests the " + MAX_MENTIONS_RETURNED + " most "
        + "recent mentions of the logged-in user.  When the mentions have been "
        + "retrieved, the system will raise the <code>MentionsReceived</code> "
        + "event and set the <code>Mentions</code> property to the list of " + "mentions."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void RequestMentions() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestMentions",
                ErrorMessages.ERROR_TWITTER_REQUEST_MENTIONS_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> replies = Collections.emptyList();

        public void run() {
            try {
                replies = twitter.getMentionsTimeline();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestMentions",
                        ErrorMessages.ERROR_TWITTER_REQUEST_MENTIONS_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        mentions.clear();
                        for (Status status : replies) {
                            mentions.add(status.getUser().getScreenName() + " " + status.getText());
                        }
                        MentionsReceived(mentions);
                    }
                });
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Gets the most recent 20 messages in the user's timeline.
 *///from w  ww .  ja v  a 2 s.com
@SimpleFunction
public void RequestFriendTimeline() {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "RequestFriendTimeline",
                ErrorMessages.ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED, "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> messages = Collections.emptyList();

        public void run() {
            try {
                messages = twitter.getHomeTimeline();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "RequestFriendTimeline",
                        ErrorMessages.ERROR_TWITTER_REQUEST_FRIEND_TIMELINE_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        timeline.clear();
                        for (Status message : messages) {
                            List<String> status = new ArrayList<String>();
                            status.add(message.getUser().getScreenName());
                            status.add(message.getText());
                            timeline.add(status);
                        }
                        FriendTimelineReceived(timeline);
                    }
                });
            }
        }
    });
}

From source file:com.google.appinventor.components.runtime.Twitter.java

License:Open Source License

/**
 * Search for tweets or labels//from  www  . j  ava 2s  .com
 */
@SimpleFunction(description = "This searches Twitter for the given String query."
        + "<p><u>Requirements</u>: This should only be called after the "
        + "<code>IsAuthorized</code> event has been raised, indicating that the "
        + "user has successfully logged in to Twitter.</p>")
public void SearchTwitter(final String query) {
    if (twitter == null || userName.length() == 0) {
        form.dispatchErrorOccurredEvent(this, "SearchTwitter", ErrorMessages.ERROR_TWITTER_SEARCH_FAILED,
                "Need to login?");
        return;
    }
    AsynchUtil.runAsynchronously(new Runnable() {
        List<Status> tweets = Collections.emptyList();

        public void run() {
            try {
                tweets = twitter.search(new Query(query)).getTweets();
            } catch (TwitterException e) {
                form.dispatchErrorOccurredEvent(Twitter.this, "SearchTwitter",
                        ErrorMessages.ERROR_TWITTER_SEARCH_FAILED, e.getMessage());
            } finally {
                handler.post(new Runnable() {
                    public void run() {
                        searchResults.clear();
                        for (Status tweet : tweets) {
                            searchResults.add(tweet.getUser().getName() + " " + tweet.getText());
                        }
                        SearchSuccessful(searchResults);
                    }
                });
            }
        }
    });
}

From source file:com.happy_coding.viralo.twitter.SmartPoster.java

License:Apache License

/**
 * Returns mentions for user.//from   w w w .  j av a 2s  .c  o m
 *
 * @return
 */
public List<ContactTweet> getMentions() {

    Twitter twitter = new TwitterFactory().getInstance();

    try {

        ResponseList<Status> mentions = twitter.getMentions();
        List<ContactTweet> contactTweets = new ArrayList<ContactTweet>();

        for (Status status : mentions) {

            Contact contact = new Contact();
            contact.setUid(status.getUser().getId());
            contact.setName(status.getUser().getScreenName());

            ContactTweet contactTweet = new ContactTweet(contact, status.getText());
            contactTweet.setTweetID(status.getId());
            contactTweets.add(contactTweet);
        }
        return contactTweets;

    } catch (TwitterException e) {
        logger.error("can't load mentions", e);
        return null;
    }
}

From source file:com.hortonworks.amuise.cdrstorm.kafka.producers.CDRTestDataProducer.java

private void start() {

    /**//from  w  ww .j  av  a2 s  .c  om
     * Kafka Twitter Producer properties *
     */
    Properties twitterconprops = new Properties();
    twitterconprops.put("metadata.broker.list", globalconfigs.getProperty("twitter4j.brokerlist"));
    twitterconprops.put("serializer.class", globalconfigs.getProperty("twitter4j.serializer"));
    twitterconprops.put("request.required.acks", globalconfigs.getProperty("twitter4j.requiredacks"));
    ProducerConfig twitterproducerconfig = new ProducerConfig(twitterconprops);
    final Producer<String, String> twitterproducer = new Producer<String, String>(twitterproducerconfig);

    /**
     * Kafka CDR Producer properties *
     */
    Properties cdrconprops = new Properties();
    cdrconprops.put("metadata.broker.list", globalconfigs.getProperty("cdr.brokerlist"));
    cdrconprops.put("serializer.class", globalconfigs.getProperty("cdr.serializer"));
    cdrconprops.put("request.required.acks", globalconfigs.getProperty("cdr.requiredacks"));
    ProducerConfig cdrproducerconfig = new ProducerConfig(cdrconprops);
    final Producer<String, String> cdrproducer = new Producer<String, String>(cdrproducerconfig);

    /**
     * Twitter4j properties *
     */
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(globalconfigs.getProperty("twitter4j.consumerkey"));
    cb.setOAuthConsumerSecret(globalconfigs.getProperty("twitter4j.consumersecretkey"));
    cb.setOAuthAccessToken(globalconfigs.getProperty("twitter4j.accesstokenkey"));
    cb.setOAuthAccessTokenSecret(globalconfigs.getProperty("twitter4j.accesstokensecretkey"));
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    /**
     * Twitter listener *
     */
    StatusListener listener = new StatusListener() {
        // The onStatus method is executed every time a new tweet comes
        // in.
        public void onStatus(Status status) {

            StringBuilder sb = new StringBuilder();
            sb.append(status.getUser().getScreenName());
            sb.append("|");
            sb.append(status.getCreatedAt());
            sb.append("|");
            sb.append(status.getRetweetCount());
            sb.append("|");
            sb.append(status.getSource());
            sb.append("|");
            sb.append(status.getText());

            //call CDR create message
            String cdrmessage = createCDRMessage(status.getText());

            //Debug output
            System.out.println("_________________________________________________________");
            System.out.println(sb.toString());
            System.out.println("cdr message: " + cdrmessage);
            System.out.println("_________________________________________________________");

            //call producer for tweet
            KeyedMessage<String, String> twitterdata = new KeyedMessage<String, String>(
                    globalconfigs.getProperty("twitter4j.kafkatopic"), sb.toString());
            twitterproducer.send(twitterdata);

            //call producer for cdr
            KeyedMessage<String, String> cdrmessagedata = new KeyedMessage<String, String>(
                    globalconfigs.getProperty("cdr.kafkatopic"), cdrmessage);
            cdrproducer.send(cdrmessagedata);

        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onScrubGeo(long userId, long upToStatusId) {
        }

        public void onException(Exception ex) {
            System.out.println("General Exception: shutting down Twitter sample stream...");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
            twitterStream.shutdown();
        }

        public void onStallWarning(StallWarning warning) {
        }
    };

    twitterStream.addListener(listener);

    // Filter stream with targeted words
    String filterstring = globalconfigs.getProperty("twitter4j.filterwords");
    FilterQuery filterq = new FilterQuery();
    filterq.track(filterstring.split(","));
    twitterStream.filter(filterq);

    //twitterStream.sample();
}

From source file:com.ibm.TwitterAsyncService.java

License:Open Source License

@Override
public void run() {
    String bookTitle = ac.getRequest().getParameter("title");
    String bookAuthor = ac.getRequest().getParameter("author");
    boolean translate = Boolean.parseBoolean(ac.getRequest().getParameter("enable"));

    logger.debug("Requested book title {} and author {}", bookTitle, bookAuthor);

    Query query = new Query(bookTitle + " " + bookAuthor);
    query.setResultType(Query.RECENT);

    Twitter twitter = TwitterFactory.getSingleton();

    try {//from  www  .  jav  a  2 s.  c o m
        PrintWriter writer = ac.getResponse().getWriter();
        Locale locale = ac.getRequest().getLocale();
        WatsonTranslate watson = new WatsonTranslate(locale);

        // Just get the first page of results to avoid exceeding the Twitter rate limit
        QueryResult result = twitter.search(query);

        Alchemy alchemy = new Alchemy();

        List<Status> tweets = result.getTweets();

        logger.debug("Current tweets {}", tweets.toString());

        for (Status tweetMessage : tweets) {
            JSONObject json = new JSONObject();
            JSONObject tweet = new JSONObject();
            // We need to put the tweet and link into an inner object
            // so that we can use a special formatter in bootstrap table

            json.put("screenName", tweetMessage.getUser().getScreenName());

            if (translate) {
                String message = watson.translate(tweetMessage.getText());
                tweet.put("message", message);
                json.put("sentiment", alchemy.getSentiment(message));
            } else {
                tweet.put("message", tweetMessage.getText());
                json.put("sentiment", alchemy.getSentiment(tweetMessage.getText()));
            }

            String url = "https://twitter.com/" + tweetMessage.getUser().getScreenName() + "/status/"
                    + tweetMessage.getId();

            tweet.put("link", url);

            json.put("tweet", tweet);

            writer.write(("data: " + json.toString() + "\n\n"));
            writer.flush();
        }

        writer.write(("event: finished\n"));
        writer.write(("data: \n\n"));
        writer.flush();
        writer.close();
    } catch (TwitterException e) {
        logger.error("Twitter Error {}", e.getMessage());
    } catch (IOException e) {
        logger.error("could not write SSE {}", e.getMessage());
    } catch (NullPointerException e) {
        logger.error("Exception Twitter Async Service {}", e.getMessage());
    } finally {
        ac.complete();
    }
}

From source file:com.ikungolf.java.javatwitter.GetHomeTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetHomeTimeline
 *
 * @param args String[]/*from ww w .  java 2 s.co  m*/
 */
public static void main(String[] args) {
    try {
        // gets Twitter instance with default credentials
        Twitter twitter = new TwitterFactory().getInstance();
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.ikungolf.java.javatwitter.GetMentions.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetMentions
 *
 * @param args String[]//  w  w w  .j av  a  2  s.c  o m
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getMentionsTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s mentions.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.ikungolf.java.javatwitter.GetUserTimeline.java

/**
 * Usage: java twitter4j.examples.timeline.GetUserTimeline
 *
 * @param args String[]//from  w  w w  .  j  a  v a 2 s  . co m
 */
public static void main(String[] args) {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {
        List<Status> statuses;
        String user;
        //            if (args.length == 1) {
        //                user = args[0];
        user = "WebUpd8";
        statuses = twitter.getUserTimeline(user);
        //            } else {
        //                user = twitter.verifyCredentials().getScreenName();
        //                statuses = twitter.getUserTimeline();
        //            }
        System.out.println("Showing @" + user + "'s user timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}