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:org.rhq.plugins.twitter.TwitterEventPoller.java

License:Open Source License

/**
 * Add statuses to the list of events to return
 * @param statuses//from w w w .j a  v a 2  s .c  o m
 */
public void addStatuses(List<Status> statuses) {

    synchronized (events) {
        for (Status status : statuses) {
            Event ev = new Event(getEventType(), // Event Type
                    status.getUser().getName(), // SourceLocation
                    status.getCreatedAt().getTime(), // Timestamp
                    EventSeverity.INFO, // Severity -- just all the same for now
                    status.getText());
            events.add(ev);
        }
    }
}

From source file:org.richfaces.examples.tweetstream.dataserver.listeners.TweetStreamListener.java

License:Open Source License

private Tweet createTweet(Status status) {
    //create a new tweet from the status update
    Tweet tweet = new Tweet();
    tweet.setText(status.getText());//from   w ww .ja  va2 s .  c o m
    tweet.setId(status.getUser().getId());
    tweet.setProfileImageUrl(status.getUser().getProfileImageURL().toString());
    tweet.setScreenName(status.getUser().getScreenName());
    if (status.getRetweetedStatus() != null) {
        tweet.setRetweet(status.getRetweetedStatus().isRetweet());
    }

    //process hashtags in the tweet
    HashtagEntity[] hashtagEntities = status.getHashtagEntities();
    if (hashtagEntities != null) {
        ArrayList<String> curTags = new ArrayList<String>(hashtagEntities.length);

        for (HashtagEntity tw4jTag : hashtagEntities) {
            curTags.add(tw4jTag.getText());
        }

        tweet.setHashTags(curTags.toArray(new String[0]));
    } else {
        tweet.setHashTags(new String[0]);
    }
    return tweet;
}

From source file:org.seasr.meandre.apps.twitter.TwitterToTuple.java

public void onStatus(Status status) {
    String text = status.getText();

    //// w w w  . j  a  va 2  s.  c  o m
    // cull out as much as possible here
    //
    text = TwitterServices.convertToASCII(text);
    if (text == null) {
        // console.info("SKIP non-ascii " + status.getText());
        return;
    }

    float pct = TwitterServices.parsingPercentage(text);
    if (pct < 0.40) {
        // console.info("SKIP " + pct + " " + text);
        return;
    }

    User user = status.getUser();
    String location = TwitterServices.getLocation(status);

    /*
    if (location == TwitterServices.NO_LOCATION) {
       return;
    }
    */

    //console.info("Raw      " + status.getText());
    if (status.isRetweet()) {
        console.fine("YES RT " + status.getText());
    }

    String clean = clean(text);

    /*
    if (c.length() != text.length()) {
       console.info(text);
       console.info(c);
    }
    */

    outTuple.setValue(ID_IDX, ID++);
    outTuple.setValue(USER_IDX, user.getId());
    outTuple.setValue(FOLLOWERS_IDX, user.getFavouritesCount());
    outTuple.setValue(TWEET_IDX, text);
    outTuple.setValue(TEXT_IDX, clean);
    outTuple.setValue(LOCATION_IDX, location);

    // console.info("got data ");

    synchronized (buffer) {

        buffer.add(outTuple.convert());

        if (buffer.size() > WINDOW_SIZE) {

            // console.info("wake the waiter " + buffer.size());
            buffer.notifyAll();

        }

    }
    // console.info("leaving");

}

From source file:org.selman.tweetamo.PersistentStore.java

License:Apache License

private static Map<String, AttributeValue> newItem(Status status) {
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put(COL_ID, new AttributeValue().withN(Long.toString(status.getId())));
    item.put(COL_CREATEDAT, new AttributeValue().withN(Long.toString(status.getCreatedAt().getTime())));
    if (status.getGeoLocation() != null) {
        item.put(COL_LAT, new AttributeValue().withN(Double.toString(status.getGeoLocation().getLatitude())));
        item.put(COL_LONG, new AttributeValue().withN(Double.toString(status.getGeoLocation().getLongitude())));
    }//from w w w .ja  va 2s  .co m
    item.put(COL_SCREENNAME, new AttributeValue().withS(status.getUser().getScreenName()));
    item.put(COL_TEXT, new AttributeValue().withS(status.getText()));
    return item;
}

From source file:org.selman.tweetamo.TweetamoClient.java

License:Apache License

public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        System.out.println("Usage: [language] [search topic]");
    }/*ww  w .  j a  va2 s . com*/

    kinesisClient = new AmazonKinesisClient(new ClasspathPropertiesFileCredentialsProvider());
    waitForStreamToBecomeAvailable(STREAM_NAME);

    LOG.info("Publishing tweets to stream : " + STREAM_NAME);
    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            try {
                PutRecordRequest putRecordRequest = new PutRecordRequest();
                putRecordRequest.setStreamName(STREAM_NAME);
                putRecordRequest.setData(TweetSerializer.toBytes(status));
                putRecordRequest.setPartitionKey(status.getUser().getScreenName());
                PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest);
                LOG.info("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey()
                        + ", ShardID : " + putRecordResult.getShardId());

            } catch (Exception e) {
                LOG.error("Failed to putrecord", e);
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }
    };

    ClasspathTwitterCredentialsProvider provider = new ClasspathTwitterCredentialsProvider();
    TwitterCredentials credentials = provider.getTwitterCredentials();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(credentials.getConsumerKey())
            .setOAuthConsumerSecret(credentials.getConsumerSecret())
            .setOAuthAccessToken(credentials.getAccessToken())
            .setOAuthAccessTokenSecret(credentials.getAccessTokenSecret());
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    twitterStream.addListener(listener);
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.language(new String[] { args[0] });
    filterQuery.track(new String[] { args[1] });
    twitterStream.filter(filterQuery);
}

From source file:org.sintef.jarduino.examples.advanced.Twitter4Arduino.java

License:LGPL

@Override
protected void loop() {
    List<Status> statuses;/*ww w  .j  a  v  a  2s  . c o  m*/
    try {
        //Get status updates from your tweet feed
        statuses = twitter.getFriendsTimeline();
        //select the last tweet
        Status status = (Status) statuses.get(0);
        //check if it is a new tweet, or if you have it from before
        if (last == null || !status.getUser().getName().equals(last.getUser().getName())
                && !status.getText().equals(last.getText())) {
            //check that the tweet isn't written by yourself
            if (!status.getUser().getScreenName().equalsIgnoreCase(userName)) {
                System.out.println(status.getUser().getScreenName() + ":" + status.getText());
                last = status;
                //light up the Arduino
                digitalWrite(led, DigitalState.HIGH);
                timer.schedule(new Timeout(this), 10000);
            }
        }
        //wait ten seconds before checking again
        //Twitter have a limit on how many times you can check per day
        delay(10000);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
}

From source file:org.smarttechie.servlet.SimpleStream.java

public void getStream(TwitterStream twitterStream, String[] parametros, final Session session)//,PrintStream out)
{

    listener = new StatusListener() {

        @Override//from w ww . ja  v  a2  s  .  c  o  m
        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) {
            Twitter twitter = new TwitterFactory().getInstance();
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            System.out.println("");
            String profileLocation = user.getLocation();
            System.out.println(profileLocation);
            long tweetId = status.getId();
            System.out.println(tweetId);
            String content = status.getText();
            System.out.println(content + "\n");

            JSONObject obj = new JSONObject();
            obj.put("User", status.getUser().getScreenName());
            obj.put("ProfileLocation", user.getLocation().replaceAll("'", "''"));
            obj.put("Id", status.getId());
            obj.put("UserId", status.getUser().getId());
            //obj.put("User", status.getUser());
            obj.put("Message", status.getText().replaceAll("'", "''"));
            obj.put("CreatedAt", status.getCreatedAt().toString());
            obj.put("CurrentUserRetweetId", status.getCurrentUserRetweetId());
            //Get user retweeteed
            String otheruser;
            try {
                if (status.getCurrentUserRetweetId() != -1) {
                    User user2 = twitter.showUser(status.getCurrentUserRetweetId());
                    otheruser = user2.getScreenName();
                    System.out.println("Other user: " + otheruser);
                }
            } catch (Exception ex) {
                System.out.println("ERROR: " + ex.getMessage().toString());
            }
            obj.put("IsRetweet", status.isRetweet());
            obj.put("IsRetweeted", status.isRetweeted());
            obj.put("IsFavorited", status.isFavorited());

            obj.put("InReplyToUserId", status.getInReplyToUserId());
            //In reply to
            obj.put("InReplyToScreenName", status.getInReplyToScreenName());

            obj.put("RetweetCount", status.getRetweetCount());
            if (status.getGeoLocation() != null) {
                obj.put("GeoLocationLatitude", status.getGeoLocation().getLatitude());
                obj.put("GeoLocationLongitude", status.getGeoLocation().getLongitude());
            }

            JSONArray listHashtags = new JSONArray();
            String hashtags = "";
            for (HashtagEntity entity : status.getHashtagEntities()) {
                listHashtags.add(entity.getText());
                hashtags += entity.getText() + ",";
            }

            if (!hashtags.isEmpty())
                obj.put("HashtagEntities", hashtags.substring(0, hashtags.length() - 1));

            if (status.getPlace() != null) {
                obj.put("PlaceCountry", status.getPlace().getCountry());
                obj.put("PlaceFullName", status.getPlace().getFullName());
            }

            obj.put("Source", status.getSource());
            obj.put("IsPossiblySensitive", status.isPossiblySensitive());
            obj.put("IsTruncated", status.isTruncated());

            if (status.getScopes() != null) {
                JSONArray listScopes = new JSONArray();
                String scopes = "";
                for (String scope : status.getScopes().getPlaceIds()) {
                    listScopes.add(scope);
                    scopes += scope + ",";
                }

                if (!scopes.isEmpty())
                    obj.put("Scopes", scopes.substring(0, scopes.length() - 1));
            }

            obj.put("QuotedStatusId", status.getQuotedStatusId());

            JSONArray list = new JSONArray();
            String contributors = "";
            for (long id : status.getContributors()) {
                list.add(id);
                contributors += id + ",";
            }

            if (!contributors.isEmpty())
                obj.put("Contributors", contributors.substring(0, contributors.length() - 1));

            System.out.println("" + obj.toJSONString());

            insertNodeNeo4j(obj);

            //out.println(obj.toJSONString());
            String statement = "INSERT INTO TweetsClassification JSON '" + obj.toJSONString() + "';";
            executeQuery(session, statement);
        }

        @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();

    fq.track(parametros);

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

From source file:org.socialsketch.tool.rubbish.experiments.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application.//from   w  ww . ja  v  a  2s . c o m
 *
 * @param args
 */
public static void main(String[] args) throws TwitterException {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
    //twitterStream.
}

From source file:org.socialsketch.tool.rubbish.twitterstream.PrintFilterStream.java

License:Apache License

/**
 * Main entry of this application./*from ww  w. j a va  2  s .co m*/
 *
 * @param args follow(comma separated user ids) track(comma separated filter terms)
 * @throws twitter4j.TwitterException
 */
public static void main(String[] args) throws TwitterException {
    //        if (args.length < 1) {
    //            System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
    //            System.exit(-1);
    //        }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);

    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();

    //        for (String arg : args) {
    //            if (isNumericalArgument(arg)) {
    //                for (String id : arg.split(",")) {
    //                    follow.add(Long.parseLong(id));
    //                }
    //            } else {
    //                track.addAll(Arrays.asList(arg.split(",")));
    //            }
    //        }
    track.add("void setup draw");
    track.add("void size");

    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }

    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));
}

From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java

License:Open Source License

private void addTweetList(List<Status> tweetList) {
    // add all tweets and creates new persons, if they do not exist already

    //      // users to lookup
    //      Set<Long> lookupUserIds = new HashSet<Long>();
    //      //  w  w w .j  av  a 2s .  c om
    //      // extract all needed users from tweet list
    //      for (Tweet tweet : tweetList) {
    //         // User who wrote the tweet
    //         long userId = tweet.getFromUserId();
    //         
    //         // look if user already exists
    //         if(getExistingPersonForTwitterUserId(userId) == null)
    //         {
    //            // does not exist, so add it to the lookup set
    //            lookupUserIds.add(userId);
    //         }
    //      }
    //      
    //      // lookup the needed users
    //      if(!lookupUserIds.isEmpty())
    //      {
    //         int numberOfUsers = lookupUserIds.size();
    //         long[] userIdArray = new long[numberOfUsers];
    //         int i = 0;
    //         // create array of longs
    //         for(Long userId : lookupUserIds)
    //         {
    //            userIdArray[i] = userId;
    //            i++;
    //         }
    //         
    //         ResponseList<User> twitterUsers = null;
    //
    //         // lookup
    //         try {
    //             twitterUsers = twitterAPI.lookupUsers(userIdArray);
    //         } catch (TwitterException e) {
    //            log("Could not lookup users due to exception. (" + e.getMessage() + ")", LogService.LOG_ERROR);
    //         }
    //         
    //         if(twitterUsers != null)
    //         {
    //            // add them all
    //            for(User twitterUser : twitterUsers)
    //            {
    //               createPersonFromTwitterUser(twitterUser);
    //            }
    //         }
    //      }

    //      // now add all tweets, users should already be there
    //      for (Tweet tweet : tweetList) {
    //
    //         long userId = tweet.getFromUserId();
    //         Person author = getPersonForTwitterUserId(userId);
    //
    //         // create content
    //         createContentFromTweet(author, tweet);
    //      }

    // now add all tweets, users should already be there
    for (Status tweet : tweetList) {

        User user = tweet.getUser();

        Person author = createPersonFromTwitterUser(user);

        // create content
        createContentFromTweet(author, tweet);
    }
}