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:DataCollections.TweetHelper.java

public Tweet_dbo convertStatusToTweet_dbo(Status s) {
    Tweet_dbo tweet = new Tweet_dbo();
    tweet.values[Tweet_dbo.map.get("tweet_id")].setValue(String.valueOf(s.getId()));
    tweet.values[Tweet_dbo.map.get("user_id")].setValue(String.valueOf(s.getUser().getId()));
    tweet.values[Tweet_dbo.map.get("user_screenname")]
            .setValue(removeEscapeCharacters(s.getUser().getScreenName()));
    if (s.getGeoLocation() != null) {
        tweet.values[Tweet_dbo.map.get("lon")].setValue(String.valueOf(s.getGeoLocation().getLongitude()));
        tweet.values[Tweet_dbo.map.get("lat")].setValue(String.valueOf(s.getGeoLocation().getLatitude()));
    }//from  w w  w  .  j av  a  2 s.c o  m
    //tweet.values[Tweet_dbo.map.get("f_search")].setValue("true");
    tweet.values[Tweet_dbo.map.get("text")].setValue(removeEscapeCharacters(s.getText()));
    tweet.values[Tweet_dbo.map.get("hashtags")].setValue(stringifyHashtags(s.getHashtagEntities()));
    tweet.values[Tweet_dbo.map.get("mentions")].setValue(stringiyMentions(s.getUserMentionEntities()));
    tweet.values[Tweet_dbo.map.get("favouritecount")].setValue(String.valueOf(s.getFavoriteCount()));
    tweet.values[Tweet_dbo.map.get("retweetcount")].setValue(String.valueOf(s.getRetweetCount()));
    return tweet;
}

From source file:DataCollections.Users_EdgesCollectionFromTweets.java

public void extract_InsertUsers_EdgesFromTweet(Status s) {
    User_dbo tweetuser = userhelper.convertUserToUser_dbo(s.getUser());

    UserMentionEntity[] mentions = s.getUserMentionEntities();
    Long[] mentionedusers = new Long[mentions.length];
    User_dbo[] mentionedusersdbos = new User_dbo[mentions.length];

    int count = 0;
    for (UserMentionEntity u : mentions) {
        mentionedusers[count] = u.getId();
        mentionedusersdbos[count] = userhelper.convertMentionedUserToUser_dbo(u);
        count++;//  w w  w  . j  av  a 2s  . co m
    }
    User_dbo[] existinguser = UsersTable
            .select(" user_id = " + tweetuser.values[User_dbo.map.get("user_id")].lnumber + "", 0, 2);
    tweetuser.values[User_dbo.map.get("udetails_processed")].bool = true;
    if (existinguser.length == 0) {
        UsersTable.insert(tweetuser);
    } else {
        if (existinguser.length == 1) {
            if (existinguser[0].values[User_dbo.map.get("udetails_processed")].bool == false) {
                UsersTable.delete(existinguser[0].values[User_dbo.map.get("user_id")].lnumber);
                tweetuser.values[User_dbo.map.get("fri_fol_processed")].setValue(
                        String.valueOf(existinguser[0].values[User_dbo.map.get("fri_fol_processed")].bool));
                LogPrinter.printLog("User Deleted");
                UsersTable.insert(tweetuser);
            }
        }

    }
    long uid1 = tweetuser.values[User_dbo.map.get("user_id")].lnumber;
    long uid2;
    for (User_dbo mentioneduser : mentionedusersdbos) {

        existinguser = UsersTable
                .select(" user_id = " + mentioneduser.values[User_dbo.map.get("user_id")].lnumber + "", 0, 2);

        if (existinguser.length == 0) {
            UsersTable.insert(mentioneduser);
        }
        relationhelper.insertEdge(tweetuser, mentioneduser);
    }
}

From source file:datasite.DataSite.java

public static void main(String[] args) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/*  ww w. j  av a2  s.  co m*/
    cb.setOAuthConsumerKey("ConsumerKey");
    cb.setOAuthConsumerSecret("ConsumerSecret");
    cb.setOAuthAccessToken("AccessToken");
    cb.setOAuthAccessTokenSecret("AccessTokenSecret");

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

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();

            try (PrintWriter out = new PrintWriter(
                    new BufferedWriter(new FileWriter("tweet_input\\tweets.txt", true))))

            {
                //out.println(username);

                String content = status.getText();
                out.println(content + "\n");
                //System.out.append( content +"\n");

            } catch (IOException ex) {
                Logger.getLogger(DataSite.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

From source file:datasite.SortedUnique.java

public static void main(String[] args) {
    ConfigurationBuilder confb = new ConfigurationBuilder();
    confb.setDebugEnabled(true);/*from   w  w w  . ja v a  2 s. c om*/
    confb.setOAuthConsumerKey("Consumer Key");
    confb.setOAuthConsumerSecret("Consumer Secret");
    confb.setOAuthAccessToken("Access Token");
    confb.setOAuthAccessTokenSecret("Access Token Secret");

    TwitterStream twitterStream = new TwitterStreamFactory(confb.build()).getInstance();

    StatusListener listener;
    listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatus(Status status) {

            PrintStream out = null;
            try {
                User user = status.getUser();
                // gets Username

                String username = status.getUser().getScreenName();
                String content = status.getText();
                Set<String> userWrds = new HashSet<String>(); // HashSet implements Set
                Scanner sc = new Scanner(content + user);
                while (sc.hasNext()) {
                    String word = sc.next();
                    userWrds.add(word);

                }
                out = new PrintStream(new FileOutputStream("tweet_output\\unique.txt", true));
                Iterator<String> iter = userWrds.iterator();
                for (int i = 1; i <= 1 && iter.hasNext(); i++)
                    //System.out.println(iter.next());
                    out.println(userWrds.size());
            } catch (FileNotFoundException ex) {
                Logger.getLogger(SortedUnique.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "africa" };

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
    //twitterStream.();
}

From source file:de.binfalse.jatter.processors.TwitterStatusProcessor.java

License:Open Source License

/**
 * Translate twitter status./* ww  w .  j a  v  a2s.com*/
 *
 * @param status
 *          the status
 * @return the string
 */
public static String translateTwitterStatus(Status status) {
    String msg = "";
    if (status.getUser() != null && status.getUser().getScreenName() != null)
        msg += "*" + status.getUser().getScreenName() + "*: ";
    if (!status.isRetweet())
        msg += JatterTools.processTwitterMessag(status.getText());
    msg += " [" + App.printDateFormat.format(status.getCreatedAt());
    if (status.getGeoLocation() != null)
        msg += " - " + status.getGeoLocation().getLatitude() + "," + status.getGeoLocation().getLongitude();
    msg += " - " + status.getId();
    msg += "]";

    if (status.isRetweet())
        msg += "\n *RT* > " + translateTwitterStatus(status.getRetweetedStatus());

    if (status.getQuotedStatus() != null)
        msg += "\n *QT* > " + translateTwitterStatus(status.getQuotedStatus());

    return msg;
}

From source file:de.jetsli.twitter.TwitterSearch.java

License:Apache License

long search(String term, Collection<Status> result, Map<String, User> userMap, int tweets,
        long lastMaxCreateTime) throws TwitterException {
    long maxId = 0L;
    long maxMillis = 0L;
    // TODO it looks like only one page is possible with 4.0.0
    int maxPages = 1;
    int hitsPerPage = tweets;

    boolean breakPaging = false;
    for (int page = 0; page < maxPages; page++) {
        Query query = new Query(term);
        // RECENT or POPULAR
        query.setResultType(Query.MIXED);

        // avoid that more recent results disturb our paging!
        if (page > 0)
            query.setMaxId(maxId);//from w w  w  .ja  va  2 s. c  o m

        query.setCount(hitsPerPage);
        QueryResult res = twitter.search(query);

        // is res.getTweets() sorted?
        for (Status twe : res.getTweets()) {
            // determine maxId in the first page
            if (page == 0 && maxId < twe.getId())
                maxId = twe.getId();

            if (maxMillis < twe.getCreatedAt().getTime())
                maxMillis = twe.getCreatedAt().getTime();

            if (twe.getCreatedAt().getTime() + 1000 < lastMaxCreateTime)
                breakPaging = true;
            else {
                String userName = twe.getUser().getScreenName().toLowerCase();
                User user = userMap.get(userName);
                if (user == null)
                    userMap.put(userName, twe.getUser());

                result.add(twe);
            }
        }

        // minMillis could force us to leave earlier than defined by maxPages
        // or if resulting tweets are less then request (but -10 because of twitter strangeness)
        if (breakPaging || res.getTweets().size() < hitsPerPage - 10)
            break;
    }

    return maxMillis;
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public static Twitter4JTweet toTweet(Status st) {
    return toTweet(st, st.getUser());
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

/**
 * This method only returns up to 800 statuses, including retweets.
 *///from w  w  w.j av  a  2s  .co  m
public long getHomeTimeline(Collection<JTweet> result, int tweets, long lastId) throws TwitterException {
    if (lastId <= 0)
        lastId = 1;

    Map<String, JUser> userMap = new LinkedHashMap<String, JUser>();
    int hitsPerPage = 100;
    long maxId = lastId;
    long sinceId = lastId;
    int maxPages = tweets / hitsPerPage + 1;

    END_PAGINATION: for (int page = 0; page < maxPages; page++) {
        Paging paging = new Paging(page + 1, tweets, sinceId);
        // avoid that more recent results disturb our paging!
        if (page > 0)
            paging.setMaxId(maxId);

        Collection<Status> tmp = twitter.getHomeTimeline(paging);
        rateLimit--;
        for (Status st : tmp) {
            // determine maxId in the first page
            if (page == 0 && maxId < st.getId())
                maxId = st.getId();

            if (st.getId() < sinceId)
                break END_PAGINATION;

            Tweet tw = toTweet(st);
            String userName = tw.getFromUser().toLowerCase();
            JUser user = userMap.get(userName);
            if (user == null) {
                user = new JUser(st.getUser()).init(tw);
                userMap.put(userName, user);
            }

            result.add(new JTweet(tw, user));
        }

        // sinceId could force us to leave earlier than defined by maxPages
        if (tmp.size() < hitsPerPage)
            break;
    }

    return maxId;
}

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public TwitterStream streamingTwitter(Collection<String> track, final Queue<JTweet> queue)
        throws TwitterException {
    String[] trackArray = track.toArray(new String[track.size()]);
    TwitterStream stream = new TwitterStreamFactory().getInstance(twitter.getAuthorization());
    stream.addListener(new StatusListener() {

        @Override//from ww w  .  j ava  2  s. c  o m
        public void onStatus(Status status) {
            // ugly twitter ...
            if (Helper.isEmpty(status.getUser().getScreenName()))
                return;

            if (!queue.offer(new JTweet(toTweet(status), new JUser(status.getUser()))))
                logger.error("Cannot add tweet as input queue for streaming is full:" + queue.size());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            logger.error("We do not support onDeletionNotice at the moment! Tweet id: "
                    + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            logger.warn("onTrackLimitationNotice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onException(Exception ex) {
            logger.error("onException", ex);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        }
    });
    stream.filter(new FilterQuery(0, new long[0], trackArray));
    return stream;
}

From source file:de.vanita5.twittnuker.model.ParcelableStatus.java

License:Open Source License

public ParcelableStatus(final Status orig, final long account_id, final boolean is_gap) {
    this.is_gap = is_gap;
    this.account_id = account_id;
    id = orig.getId();/*  ww  w  .ja  v a 2  s. co m*/
    timestamp = getTime(orig.getCreatedAt());
    is_retweet = orig.isRetweet();
    final Status retweeted = orig.getRetweetedStatus();
    final User retweet_user = retweeted != null ? orig.getUser() : null;
    retweet_id = retweeted != null ? retweeted.getId() : -1;
    //NOTE getTime(orig.getCreatedAt())
    retweet_timestamp = retweeted != null ? getTime(retweeted.getCreatedAt()) : -1;
    retweeted_by_id = retweet_user != null ? retweet_user.getId() : -1;
    retweeted_by_name = retweet_user != null ? retweet_user.getName() : null;
    retweeted_by_screen_name = retweet_user != null ? retweet_user.getScreenName() : null;
    retweeted_by_profile_image = retweet_user != null
            ? ParseUtils.parseString(retweet_user.getProfileImageUrlHttps())
            : null;
    final Status status = retweeted != null ? retweeted : orig;
    final User user = status.getUser();
    user_id = user.getId();
    user_name = user.getName();
    user_screen_name = user.getScreenName();
    user_profile_image_url = ParseUtils.parseString(user.getProfileImageUrlHttps());
    user_is_protected = user.isProtected();
    user_is_verified = user.isVerified();
    user_is_following = user.isFollowing();
    text_html = formatStatusText(status);
    media = ParcelableMedia.fromEntities(status);
    text_plain = status.getText();
    retweet_count = status.getRetweetCount();
    favorite_count = status.getFavoriteCount();
    reply_count = status.getReplyCount();
    descendent_reply_count = status.getDescendentReplyCount();
    in_reply_to_name = getInReplyToName(status);
    in_reply_to_screen_name = status.getInReplyToScreenName();
    in_reply_to_status_id = status.getInReplyToStatusId();
    in_reply_to_user_id = status.getInReplyToUserId();
    source = status.getSource();
    location = new ParcelableLocation(status.getGeoLocation());
    is_favorite = status.isFavorited();
    text_unescaped = toPlainText(text_html);
    my_retweet_id = retweeted_by_id == account_id ? id : -1;
    is_possibly_sensitive = status.isPossiblySensitive();
    mentions = ParcelableUserMention.fromUserMentionEntities(status.getUserMentionEntities());
    first_media = media != null && media.length > 0 ? media[0].url : null;
}