Example usage for twitter4j User getLang

List of usage examples for twitter4j User getLang

Introduction

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

Prototype

String getLang();

Source Link

Document

Returns the preferred language of the user

Usage

From source file:io.druid.examples.twitter.TwitterSpritzerFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(InputRowParser parser) throws IOException {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {
        @Override/*  w  ww. jav a  2  s .c  o 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) {
            ex.printStackTrace();
        }

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

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

    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {
            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;
            }
        }

        @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...");
                        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(String.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 ? String.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() throws IOException {
            log.info("CLOSE twitterstream");
            twitterStream.shutdown(); // invokes twitterStream.cleanUp()
        }
    };
}

From source file:io.rakam.datasource.twitter.TweetProcessor.java

License:Apache License

@Override
public void onStatus(Status status) {
    Map<String, Object> map = new HashMap<>();

    GeoLocation geoLocation = status.getGeoLocation();
    if (geoLocation != null) {
        map.put("latitude", geoLocation.getLatitude());
        map.put("longitude", geoLocation.getLongitude());
    }//from ww w. j a  v a  2s  . c om

    map.put("_time", status.getCreatedAt().getTime());
    Place place = status.getPlace();
    if (place != null) {
        map.put("country_code", place.getCountryCode());
        map.put("place", place.getName());
        map.put("place_type", place.getPlaceType());
        map.put("place_id", place.getId());
    }

    User user = status.getUser();
    map.put("_user", user.getId());
    map.put("user_lang", user.getLang());
    map.put("user_created", user.getCreatedAt());
    map.put("user_followers", user.getFollowersCount());
    map.put("user_status_count", user.getStatusesCount());
    map.put("user_verified", user.isVerified());

    map.put("id", status.getId());
    map.put("is_reply", status.getInReplyToUserId() > -1);
    map.put("is_retweet", status.isRetweet());
    map.put("has_media", status.getMediaEntities().length > 0);
    map.put("urls",
            Arrays.stream(status.getURLEntities()).map(URLEntity::getText).collect(Collectors.toList()));
    map.put("hashtags", Arrays.stream(status.getHashtagEntities()).map(HashtagEntity::getText)
            .collect(Collectors.toList()));
    map.put("user_mentions", Arrays.stream(status.getUserMentionEntities()).map(UserMentionEntity::getText)
            .collect(Collectors.toList()));
    map.put("language", "und".equals(status.getLang()) ? null : status.getLang());
    map.put("is_positive", classifier.isPositive(status.getText()));

    Event event = new Event().properties(map).collection(collection);
    buffer.add(event);

    commitIfNecessary();
}

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();//  w  w  w.  jav a2s .co 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 ww w. ja va 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//  w  ww .ja va 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.bireme.interop.toJson.Twitter2Json.java

License:Open Source License

private JSONObject getDocument(final Status status) {
    assert status != null;

    final JSONObject obj = new JSONObject();
    final GeoLocation geo = status.getGeoLocation();
    final Place place = status.getPlace();
    final User user = status.getUser();

    obj.put("createdAt", status.getCreatedAt()).put("id", status.getId()).put("lang", status.getLang());
    if (geo != null) {
        obj.put("location_latitude", geo.getLatitude()).put("location_longitude", geo.getLongitude());
    }//from   w  w  w .j a  va2  s. c om
    if (place != null) {
        obj.put("place_country", place.getCountry()).put("place_fullName", place.getFullName())
                .put("place_id", place.getId()).put("place_name", place.getName())
                .put("place_type", place.getPlaceType()).put("place_streetAddress", place.getStreetAddress())
                .put("place_url", place.getURL());
    }
    obj.put("source", status.getSource()).put("text", status.getText());
    if (user != null) {
        obj.put("user_description", user.getDescription()).put("user_id", user.getId())
                .put("user_lang", user.getLang()).put("user_location", user.getLocation())
                .put("user_name", user.getName()).put("user_url", user.getURL());
    }
    obj.put("isTruncated", status.isTruncated()).put("isRetweet", status.isRetweet());

    return obj;
}

From source file:org.botlibre.sense.twitter.Twitter.java

License:Open Source License

public boolean checkFriendship(long friendId, boolean welcomeOnly) throws TwitterException {
    long[] lookup = new long[1];
    lookup[0] = friendId;//from  w ww.j  a v  a  2  s.  co  m
    ResponseList<User> users = getConnection().lookupUsers(lookup);
    User friend = users.get(0);
    if (friend.getScreenName().equals(getUserName())) {
        return false;
    }
    if (!getAutoFollowKeywords().isEmpty()) {
        StringWriter writer = new StringWriter();
        writer.write(friend.getScreenName().toLowerCase());
        writer.write(" ");
        writer.write(friend.getDescription().toLowerCase());
        writer.write(" ");
        writer.write(friend.getLocation().toLowerCase());
        writer.write(" ");
        writer.write(friend.getLang().toLowerCase());
        writer.write(" ");
        writer.write(friend.getName().toLowerCase());
        boolean match = false;
        for (String text : getAutoFollowKeywords()) {
            List<String> keywords = new TextStream(text.toLowerCase()).allWords();
            if (new TextStream(writer.toString()).allWords().containsAll(keywords)) {
                match = true;
                break;
            }
        }
        if (!match) {
            log("Autofollow skipping friend, does not match keywords", Level.FINE, friend.getScreenName());
            return false;
        }
    }
    Network memory = getBot().memory().newMemory();
    Vertex speaker = memory.createSpeaker(friend.getScreenName());
    speaker.setPinned(true);
    // Only try to follow a user once.
    if (!speaker.hasRelationship(Primitive.FOLLOWED)) {
        speaker.addRelationship(Primitive.FOLLOWED, memory.createTimestamp());
        memory.save();
        if (!welcomeOnly && getAutoFollow()) {
            log("Adding autofollow friend.", Level.INFO, friend.getScreenName());
            getConnection().createFriendship(friendId);
            Utils.sleep(1000);
        }
        if (!getWelcomeMessage().isEmpty()) {
            log("Sending welcome message.", Level.INFO, friend.getScreenName());
            sendMessage(getWelcomeMessage(), friend.getScreenName());
            Utils.sleep(1000);
        }
        if (welcomeOnly) {
            return false;
        }
        return true;
    }
    log("Autofollow skipping friend, already followed once", Level.FINE, friend.getScreenName());
    return false;
}

From source file:org.graylog2.inputs.twitter.TwitterCodec.java

License:Open Source License

private Message createMessageFromStatus(final Status status) {
    final Message message = new Message(status.getText(), "twitter.com", new DateTime(status.getCreatedAt()));

    message.addField("facility", "Tweets");
    message.addField("level", 6);
    message.addField("tweet_id", status.getId());
    message.addField("tweet_is_retweet", Boolean.toString(status.isRetweet()));
    message.addField("tweet_favorite_count", status.getFavoriteCount());
    message.addField("tweet_retweet_count", status.getRetweetCount());
    message.addField("tweet_language", status.getLang());

    final GeoLocation geoLocation = status.getGeoLocation();
    if (geoLocation != null) {
        message.addField("tweet_geo_long", geoLocation.getLongitude());
        message.addField("tweet_geo_lat", geoLocation.getLatitude());
    }/* w ww .j ava 2 s.co  m*/

    final User user = status.getUser();
    if (user != null) {
        message.addField("tweet_url",
                "https://twitter.com/" + user.getScreenName() + "/status/" + status.getId());
        message.addField("user_id", user.getId());
        message.addField("user_name", user.getScreenName());
        message.addField("user_description", user.getDescription());
        message.addField("user_timezone", user.getTimeZone());
        message.addField("user_utc_offset", user.getUtcOffset());
        message.addField("user_location", user.getLocation());
        message.addField("user_language", user.getLang());
        message.addField("user_url", user.getURL());
        message.addField("user_followers", user.getFollowersCount());
        message.addField("user_tweets", user.getStatusesCount());
        message.addField("user_favorites", user.getFavouritesCount());
    }
    return message;
}

From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java

License:Apache License

private void getUserData(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();//from   w w  w  . ja  va  2s . c o  m

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);
    String lUsername = aToken.getString("username");
    Integer lUserId = aToken.getInteger("userid");
    try {
        User lUser;
        // if user id is given use this to get user data
        if (lUserId != null && lUserId != 0) {
            lUser = mTwitter.showUser(lUserId);
            // if user name is given use this to get user data
        } else if (lUsername != null && lUsername.length() > 0) {
            lUser = mTwitter.showUser(lUsername);
            // otherwise return user data of provider (ourselves)
        } else {
            lUser = mTwitter.verifyCredentials();
        }
        if (lUser != null) {
            lResponse.setString("screenname", lUser.getScreenName());
            lResponse.setLong("id", lUser.getId());
            lResponse.setString("description", lUser.getDescription());
            lResponse.setString("location", lUser.getLocation());
            lResponse.setString("lang", lUser.getLang());
            lResponse.setString("name", lUser.getName());
        } else {
            lResponse.setInteger("code", -1);
            lResponse.setString("msg", "Neither UserId nor Username passed.");
        }
    } catch (Exception lEx) {
        String lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.soluvas.buzz.twitter.TwitterUser.java

License:Apache License

/**
 * Clones attributes from Twitter4j's {@link User}.
 * @param src/*  w w w .j a  va  2 s  . co m*/
 */
public TwitterUser(User src, int revId, DateTime fetchTime) {
    super();
    this.revId = revId;
    this.fetchTime = fetchTime;
    id = src.getId();
    name = src.getName();
    screenName = src.getScreenName();
    location = src.getLocation();
    description = src.getDescription();
    contributorsEnabled = src.isContributorsEnabled();
    profileImageUrl = src.getProfileImageURL();
    biggerProfileImageUrl = src.getBiggerProfileImageURL();
    miniProfileImageUrl = src.getMiniProfileImageURL();
    originalProfileImageUrl = src.getOriginalProfileImageURL();
    profileImageUrlHttps = src.getProfileImageURLHttps();
    biggerProfileImageUrlHttps = src.getBiggerProfileImageURLHttps();
    miniProfileImageUrlHttps = src.getMiniProfileImageURLHttps();
    originalProfileImageUrlHttps = src.getOriginalProfileImageURLHttps();
    url = src.getURL();
    protectedState = src.isProtected();
    followersCount = src.getFollowersCount();
    status = src.getStatus();
    profileBackgroundColor = src.getProfileBackgroundColor();
    profileTextColor = src.getProfileTextColor();
    profileLinkColor = src.getProfileLinkColor();
    profileSidebarFillColor = src.getProfileSidebarFillColor();
    profileSidebarBorderColor = src.getProfileSidebarBorderColor();
    profileUseBackgroundImage = src.isProfileUseBackgroundImage();
    showAllInlineMedia = src.isShowAllInlineMedia();
    friendsCount = src.getFriendsCount();
    createdAt = new DateTime(src.getCreatedAt());
    favouritesCount = src.getFavouritesCount();
    utcOffset = src.getUtcOffset();
    timeZone = src.getTimeZone();
    profileBackgroundImageUrl = src.getProfileBackgroundImageURL();
    profileBackgroundImageUrlHttps = src.getProfileBackgroundImageUrlHttps();
    profileBannerUrl = src.getProfileBannerURL();
    profileBannerRetinaUrl = src.getProfileBannerRetinaURL();
    profileBannerIpadUrl = src.getProfileBannerIPadURL();
    profileBannerIpadRetinaUrl = src.getProfileBannerIPadRetinaURL();
    profileBannerMobileUrl = src.getProfileBannerMobileURL();
    profileBannerMobileRetinaUrl = src.getProfileBannerMobileRetinaURL();
    profileBackgroundTiled = src.isProfileBackgroundTiled();
    lang = src.getLang();
    statusesCount = src.getStatusesCount();
    geoEnabled = src.isGeoEnabled();
    verified = src.isVerified();
    translator = src.isTranslator();
    listedCount = src.getListedCount();
    followRequestSent = src.isFollowRequestSent();
}