Example usage for twitter4j User getScreenName

List of usage examples for twitter4j User getScreenName

Introduction

In this page you can find the example usage for twitter4j User getScreenName.

Prototype

String getScreenName();

Source Link

Document

Returns the screen name of the user

Usage

From source file:net.nokok.twitduke.core.twitter.TwitterNotificationListener.java

License:Open Source License

@Override
public void onUnblock(User source, User unblockedUser) {
    new NotificationFrame("", source.getScreenName() + "?"
            + unblockedUser.getScreenName() + "?????");
}

From source file:net.nokok.twitduke.core.twitter.TwitterNotificationListener.java

License:Open Source License

@Override
public void onUnfavorite(User source, User target, Status unfavoritedStatus) {
    new NotificationFrame(source.getScreenName() + "??????", unfavoritedStatus.getText());
}

From source file:net.wasdev.gameon.auth.twitter.TwitterCallback.java

License:Apache License

/**
 * Method that performs introspection on an AUTH string, and returns data as
 * a String->String hashmap.//from  w  w w . j av  a  2  s.c  o m
 * 
 * @param auth
 *            the authstring to query, as built by an auth impl.
 * @return the data from the introspect, in a map.
 * @throws IOException
 *             if anything goes wrong.
 */
public Map<String, String> introspectAuth(String token, String tokensecret) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret).setOAuthAccessToken(token)
            .setOAuthAccessTokenSecret(tokensecret);

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

    try {
        // ask twitter to verify the token & tokensecret from the auth
        // string
        // if invalid, it'll throw a TwitterException
        twitter.verifyCredentials();

        // if it's valid, lets grab a little more info about the user.
        long id = twitter.getId();
        ResponseList<User> users = twitter.lookupUsers(id);
        User u = users.get(0);
        String name = u.getName();
        String screenname = u.getScreenName();

        results.put("valid", "true");
        results.put("id", "twitter:" + id);
        results.put("name", name);
        results.put("screenname", screenname);

    } catch (TwitterException e) {
        results.put("valid", "false");
    }

    return results;
}

From source file:nz.net.speakman.android.dreamintweets.twitterstream.TwitterStreamAdapter.java

License:Apache License

private Spanned getTweetUsername(Status tweet) {
    User user = tweet.getUser();
    return Html.fromHtml(getClickableUrl(getUserUrl(user), "@" + user.getScreenName()));
}

From source file:nz.net.speakman.android.dreamintweets.twitterstream.TwitterStreamAdapter.java

License:Apache License

private String getUserUrl(User user) {
    return String.format(URL_FORMAT_USER_LINK, user.getScreenName());
}

From source file:ontoSentiment.Amigos.java

@Override
public void run() {
    ConfigurationBuilder cb = new ConfigurationBuilder();

    //the following is set without accesstoken- desktop client
    cb.setDebugEnabled(true).setOAuthConsumerKey("FBd5n7dyl8mCz73qyfZ0p4XHb")
            .setOAuthConsumerSecret("vu5Xt5TzBSL9naOZylIYlx5MdcRlhH2LvkpW6KIkxSf9AqwuGt")
            .setOAuthAccessToken("3232400175-lAchtC6ChWMTnJKe3BaWbst8SucIaTjn5gm4Rp2")
            .setOAuthAccessTokenSecret("DnkquBWAS6igYpM8Z4r54hH7ztcfMX6u8OzMXBLwM9Xkh");

    try {/*  w  w w . j  a  v  a  2  s  . co  m*/
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        //User u = twitter.showUser("karlaffabiola");            
        User u = twitter.showUser("raythemaster");
        IDs ids;
        System.out.println("Listing followers's ids.");

        System.out.println("ID: " + u.getId());
        System.out.println("Nome: " + u.getScreenName());

        long cursor = -1;
        PagableResponseList<User> pagableFollowings;
        List<User> listFriends = new ArrayList<>();
        List<User> listFriends2 = new ArrayList<>();

        pagableFollowings = twitter.getFriendsList(u.getId(), cursor, 200);
        System.out.println("Qunatidade followers: " + pagableFollowings.size());
        for (User user : pagableFollowings) {
            System.out.println("Id: " + user.getId() + " Nome: " + user.getScreenName());
            listFriends.add(user); // ArrayList<User>
        }

        for (User user : listFriends) {
            System.out.println("Id1: " + user.getId() + " Nome1: " + user.getScreenName());
            pagableFollowings = twitter.getFriendsList(user.getId(), cursor, 200);
            System.out.println("Qunatidade followers: " + pagableFollowings.size());
            for (User user2 : pagableFollowings) {
                System.out.println("Id2: " + user2.getId() + " Nome2: " + user2.getScreenName());
                listFriends2.add(user2); // ArrayList<User>
            }
        }
        System.out.println("Lista 1:" + listFriends.size());
        System.out.println("Lista 2:" + listFriends2.size());
        System.exit(0);
    } catch (TwitterException te) {
        // te.printStackTrace();
        System.out.println("Failed to get timeline: " + new Date());
        try {
            Thread.sleep(3 * 60 * 1000);
            run();
        } catch (InterruptedException ex) {
            Logger.getLogger(Amigos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.apache.asterix.external.parser.TweetParser.java

License:Apache License

@Override
public void parse(IRawRecord<? extends Status> record, DataOutput out) throws HyracksDataException {
    Status tweet = record.get();//  www  . j  a  v  a2s  .  c  o  m
    User user = tweet.getUser();
    // Tweet user data
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.SCREEN_NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.LANGUAGE)])
            .setValue(JObjectUtil.getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FRIENDS_COUNT)])
            .setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.STATUS_COUNT)])
            .setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FOLLOWERS_COUNT)])
            .setValue(user.getFollowersCount());

    // Tweet data
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.ID)])
            .setValue(String.valueOf(tweet.getId()));

    int userPos = tweetFieldNameMap.get(Tweet.USER);
    for (int i = 0; i < mutableUserFields.length; i++) {
        ((AMutableRecord) mutableTweetFields[userPos]).setValueAtPos(i, mutableUserFields[i]);
    }
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)])
                .setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)])
                .setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)]).setValue(0);
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.CREATED_AT)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.MESSAGE)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getText()));

    for (int i = 0; i < mutableTweetFields.length; i++) {
        mutableRecord.setValueAtPos(i, mutableTweetFields[i]);
    }
    recordBuilder.reset(mutableRecord.getType());
    recordBuilder.init();
    IDataParser.writeRecord(mutableRecord, out, recordBuilder);
}

From source file:org.apache.asterix.external.util.TweetProcessor.java

License:Apache License

public AMutableRecord processNextTweet(Status tweet) {
    User user = tweet.getUser();

    // Tweet user data
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.SCREEN_NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.LANGUAGE)])
            .setValue(JObjectUtil.getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FRIENDS_COUNT)])
            .setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.STATUS_COUNT)])
            .setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FOLLOWERS_COUNT)])
            .setValue(user.getFollowersCount());

    // Tweet data
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.ID)])
            .setValue(String.valueOf(tweet.getId()));

    int userPos = tweetFieldNameMap.get(Tweet.USER);
    for (int i = 0; i < mutableUserFields.length; i++) {
        ((AMutableRecord) mutableTweetFields[userPos]).setValueAtPos(i, mutableUserFields[i]);
    }//from www  .j  a v a  2  s .  c  o  m
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)])
                .setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)])
                .setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)]).setValue(0);
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.CREATED_AT)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.MESSAGE)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getText()));

    for (int i = 0; i < mutableTweetFields.length; i++) {
        mutableRecord.setValueAtPos(i, mutableTweetFields[i]);
    }

    return mutableRecord;

}

From source file:org.apache.druid.examples.twitter.TwitterSpritzerFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(InputRowParser parser, File temporaryDirectory) {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {
        @Override//from   www  .j av  a 2s .co  m
        public void onConnect() {
            log.info("Connected_to_Twitter");
        }

        @Override
        public void onDisconnect() {
            log.info("Disconnect_from_Twitter");
        }

        /**
         * called before thread gets cleaned up
         */
        @Override
        public void onCleanUp() {
            log.info("Cleanup_twitter_stream");
        }
    }; // ConnectionLifeCycleListener

    final TwitterStream twitterStream;
    final StatusListener statusListener;
    final int QUEUE_SIZE = 2000;
    /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread.   */
    final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE);
    final long startMsec = System.currentTimeMillis();

    //
    //   set up Twitter Spritzer
    //
    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener);
    statusListener = new StatusListener() { // This is what really gets called to deliver stuff from twitter4j
        @Override
        public void onStatus(Status status) {
            // time to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            try {
                boolean success = queue.offer(status, 15L, TimeUnit.SECONDS);
                if (!success) {
                    log.warn("queue too slow!");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // This notice will be sent each time a limited stream becomes unlimited.
            // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity.
            log.warn("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

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

        @Override
        public void onStallWarning(StallWarning warning) {
            log.warn("Got stall warning: %s", warning);
        }
    };

    twitterStream.addListener(statusListener);
    twitterStream.sample(); // creates a generic StatusStream
    log.info("returned from sample()");

    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {
            @Override
            public void run() {
            }
        };

        private long rowCount = 0L;
        private boolean waitIfmax = (getMaxEventCount() < 0L);
        private final Map<String, Object> theMap = new TreeMap<>();
        // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper();

        private boolean maxTimeReached() {
            if (getMaxRunMinutes() <= 0) {
                return false;
            } else {
                return (System.currentTimeMillis() - startMsec) / 60000L >= getMaxRunMinutes();
            }
        }

        private boolean maxCountReached() {
            return getMaxEventCount() >= 0 && rowCount >= getMaxEventCount();
        }

        @Override
        public boolean hasMore() {
            if (maxCountReached() || maxTimeReached()) {
                return waitIfmax;
            } else {
                return true;
            }
        }

        @Nullable
        @Override
        public InputRow nextRow() {
            // Interrupted to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }

            // all done?
            if (maxCountReached() || maxTimeReached()) {
                if (waitIfmax) {
                    // sleep a long time instead of terminating
                    try {
                        log.info("reached limit, sleeping a long time...");
                        Thread.sleep(2000000000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException("InterruptedException", e);
                    }
                } else {
                    // allow this event through, and the next hasMore() call will be false
                }
            }
            if (++rowCount % 1000 == 0) {
                log.info("nextRow() has returned %,d InputRows", rowCount);
            }

            Status status;
            try {
                status = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }

            theMap.clear();

            HashtagEntity[] hts = status.getHashtagEntities();
            String text = status.getText();
            theMap.put("text", (null == text) ? "" : text);
            theMap.put("htags", (hts.length > 0)
                    ? Lists.transform(Arrays.asList(hts), new Function<HashtagEntity, String>() {
                        @Nullable
                        @Override
                        public String apply(HashtagEntity input) {
                            return input.getText();
                        }
                    })
                    : ImmutableList.<String>of());

            long[] lcontrobutors = status.getContributors();
            List<String> contributors = new ArrayList<>();
            for (long contrib : lcontrobutors) {
                contributors.add(StringUtils.format("%d", contrib));
            }
            theMap.put("contributors", contributors);

            GeoLocation geoLocation = status.getGeoLocation();
            if (null != geoLocation) {
                double lat = status.getGeoLocation().getLatitude();
                double lon = status.getGeoLocation().getLongitude();
                theMap.put("lat", lat);
                theMap.put("lon", lon);
            } else {
                theMap.put("lat", null);
                theMap.put("lon", null);
            }

            if (status.getSource() != null) {
                Matcher m = sourcePattern.matcher(status.getSource());
                theMap.put("source", m.find() ? m.group(1) : status.getSource());
            }

            theMap.put("retweet", status.isRetweet());

            if (status.isRetweet()) {
                Status original = status.getRetweetedStatus();
                theMap.put("retweet_count", original.getRetweetCount());

                User originator = original.getUser();
                theMap.put("originator_screen_name", originator != null ? originator.getScreenName() : "");
                theMap.put("originator_follower_count",
                        originator != null ? originator.getFollowersCount() : "");
                theMap.put("originator_friends_count", originator != null ? originator.getFriendsCount() : "");
                theMap.put("originator_verified", originator != null ? originator.isVerified() : "");
            }

            User user = status.getUser();
            final boolean hasUser = (null != user);
            theMap.put("follower_count", hasUser ? user.getFollowersCount() : 0);
            theMap.put("friends_count", hasUser ? user.getFriendsCount() : 0);
            theMap.put("lang", hasUser ? user.getLang() : "");
            theMap.put("utc_offset", hasUser ? user.getUtcOffset() : -1); // resolution in seconds, -1 if not available?
            theMap.put("statuses_count", hasUser ? user.getStatusesCount() : 0);
            theMap.put("user_id", hasUser ? StringUtils.format("%d", user.getId()) : "");
            theMap.put("screen_name", hasUser ? user.getScreenName() : "");
            theMap.put("location", hasUser ? user.getLocation() : "");
            theMap.put("verified", hasUser ? user.isVerified() : "");

            theMap.put("ts", status.getCreatedAt().getTime());

            List<String> dimensions = Lists.newArrayList(theMap.keySet());

            return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap);
        }

        @Override
        public Runnable commit() {
            // ephemera in, ephemera out.
            return doNothingRunnable; // reuse the same object each time
        }

        @Override
        public void close() {
            log.info("CLOSE twitterstream");
            twitterStream.shutdown(); // invokes twitterStream.cleanUp()
        }
    };
}

From source file:org.apache.flume.sink.solr.morphline.TwitterSource.java

License:Apache License

private Record extractRecord(String idPrefix, Schema avroSchema, Status status) {
    User user = status.getUser();
    Record doc = new Record(avroSchema);

    doc.put("id", idPrefix + status.getId());
    doc.put("created_at", formatterTo.format(status.getCreatedAt()));
    doc.put("retweet_count", status.getRetweetCount());
    doc.put("retweeted", status.isRetweet());
    doc.put("in_reply_to_user_id", status.getInReplyToUserId());
    doc.put("in_reply_to_status_id", status.getInReplyToStatusId());

    addString(doc, "source", status.getSource());
    addString(doc, "text", status.getText());

    MediaEntity[] mediaEntities = status.getMediaEntities();
    if (mediaEntities.length > 0) {
        addString(doc, "media_url_https", mediaEntities[0].getMediaURLHttps());
        addString(doc, "expanded_url", mediaEntities[0].getExpandedURL());
    }//  w  w  w  .j  a  v a 2s  . co m

    doc.put("user_friends_count", user.getFriendsCount());
    doc.put("user_statuses_count", user.getStatusesCount());
    doc.put("user_followers_count", user.getFollowersCount());
    addString(doc, "user_location", user.getLocation());
    addString(doc, "user_description", user.getDescription());
    addString(doc, "user_screen_name", user.getScreenName());
    addString(doc, "user_name", user.getName());
    return doc;
}