Example usage for twitter4j Status getGeoLocation

List of usage examples for twitter4j Status getGeoLocation

Introduction

In this page you can find the example usage for twitter4j Status getGeoLocation.

Prototype

GeoLocation getGeoLocation();

Source Link

Document

Returns The location that this tweet refers to if available.

Usage

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();//  w  w w .  jav a  2s  . c  o 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;
}

From source file:de.vanita5.twittnuker.util.ContentValuesCreator.java

License:Open Source License

public static ContentValues makeStatusContentValues(final Status orig, final long accountId,
        final boolean largeProfileImage) {
    if (orig == null || orig.getId() <= 0)
        return null;
    final ContentValues values = new ContentValues();
    values.put(Statuses.ACCOUNT_ID, accountId);
    values.put(Statuses.STATUS_ID, orig.getId());
    values.put(Statuses.STATUS_TIMESTAMP, orig.getCreatedAt().getTime());
    values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
    final boolean isRetweet = orig.isRetweet();
    final Status status;
    final Status retweetedStatus = isRetweet ? orig.getRetweetedStatus() : null;
    if (retweetedStatus != null) {
        final User retweetUser = orig.getUser();
        values.put(Statuses.RETWEET_ID, retweetedStatus.getId());
        values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime());
        values.put(Statuses.RETWEETED_BY_USER_ID, retweetUser.getId());
        values.put(Statuses.RETWEETED_BY_USER_NAME, retweetUser.getName());
        values.put(Statuses.RETWEETED_BY_USER_SCREEN_NAME, retweetUser.getScreenName());
        values.put(Statuses.RETWEETED_BY_USER_PROFILE_IMAGE,
                ParseUtils.parseString(retweetUser.getProfileImageUrlHttps()));
        status = retweetedStatus;//from  w w w  . j  av  a2s  .  c o m
    } else {
        status = orig;
    }
    final User user = status.getUser();
    if (user != null) {
        final long userId = user.getId();
        final String profileImageUrl = ParseUtils.parseString(user.getProfileImageUrlHttps());
        final String name = user.getName(), screenName = user.getScreenName();
        values.put(Statuses.USER_ID, userId);
        values.put(Statuses.USER_NAME, name);
        values.put(Statuses.USER_SCREEN_NAME, screenName);
        values.put(Statuses.IS_PROTECTED, user.isProtected());
        values.put(Statuses.IS_VERIFIED, user.isVerified());
        values.put(Statuses.USER_PROFILE_IMAGE_URL,
                largeProfileImage ? getBiggerTwitterProfileImage(profileImageUrl) : profileImageUrl);
        values.put(CachedUsers.IS_FOLLOWING, user.isFollowing());
    }
    final String text_html = Utils.formatStatusText(status);
    values.put(Statuses.TEXT_HTML, text_html);
    values.put(Statuses.TEXT_PLAIN, status.getText());
    values.put(Statuses.TEXT_UNESCAPED, toPlainText(text_html));
    values.put(Statuses.RETWEET_COUNT, status.getRetweetCount());
    values.put(Statuses.REPLY_COUNT, status.getReplyCount());
    values.put(Statuses.DESCENDENT_REPLY_COUNT, status.getDescendentReplyCount());
    values.put(Statuses.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
    values.put(Statuses.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
    values.put(Statuses.IN_REPLY_TO_USER_NAME, Utils.getInReplyToName(status));
    values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, status.getInReplyToScreenName());
    values.put(Statuses.SOURCE, status.getSource());
    values.put(Statuses.IS_POSSIBLY_SENSITIVE, status.isPossiblySensitive());
    final GeoLocation location = status.getGeoLocation();
    if (location != null) {
        values.put(Statuses.LOCATION, location.getLatitude() + "," + location.getLongitude());
    }
    values.put(Statuses.IS_RETWEET, isRetweet);
    values.put(Statuses.IS_FAVORITE, status.isFavorited());
    final ParcelableMedia[] media = ParcelableMedia.fromEntities(status);
    if (media != null) {
        values.put(Statuses.MEDIA, JSONSerializer.toJSONArrayString(media));
        values.put(Statuses.FIRST_MEDIA, media[0].url);
    }
    final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status);
    if (mentions != null) {
        values.put(Statuses.MENTIONS, JSONSerializer.toJSONArrayString(mentions));
    }
    return values;
}

From source file:edu.cmu.cs.lti.discoursedb.io.twitter.converter.TwitterConverterService.java

License:Open Source License

/**
 * Maps a Tweet represented as a Twitter4J Status object to DiscourseDB
 * //from   w  ww .j  a va2 s.  c o m
 * @param discourseName the name of the discourse
 * @param datasetName the dataset identifier
 * @param tweet the Tweet to store in DiscourseDB
 */
public void mapTweet(String discourseName, String datasetName, Status tweet, PemsStationMetaData pemsMetaData) {
    if (tweet == null) {
        return;
    }

    Assert.hasText(discourseName, "The discourse name has to be specified and cannot be empty.");
    Assert.hasText(datasetName, "The dataset name has to be specified and cannot be empty.");

    if (dataSourceService.dataSourceExists(String.valueOf(tweet.getId()), TweetSourceMapping.ID_TO_CONTRIBUTION,
            datasetName)) {
        log.trace("Tweet with id " + tweet.getId() + " already exists in database. Skipping");
        return;
    }
    log.trace("Mapping Tweet " + tweet.getId());

    Discourse discourse = discourseService.createOrGetDiscourse(discourseName);

    twitter4j.User tUser = tweet.getUser();
    User user = null;
    if (!userService.findUserByDiscourseAndUsername(discourse, tUser.getScreenName()).isPresent()) {
        user = userService.createOrGetUser(discourse, tUser.getScreenName());
        user.setRealname(tUser.getName());
        user.setEmail(tUser.getEmail());
        user.setLocation(tUser.getLocation());
        user.setLanguage(tUser.getLang());
        user.setStartTime(tweet.getUser().getCreatedAt());

        AnnotationInstance userInfo = annoService.createTypedAnnotation("twitter_user_info");
        annoService.addFeature(userInfo,
                annoService.createTypedFeature(String.valueOf(tUser.getFavouritesCount()), "favorites_count"));
        annoService.addFeature(userInfo,
                annoService.createTypedFeature(String.valueOf(tUser.getFollowersCount()), "followers_count"));
        annoService.addFeature(userInfo,
                annoService.createTypedFeature(String.valueOf(tUser.getFriendsCount()), "friends_count"));
        annoService.addFeature(userInfo,
                annoService.createTypedFeature(String.valueOf(tUser.getStatusesCount()), "statuses_count"));
        annoService.addFeature(userInfo,
                annoService.createTypedFeature(String.valueOf(tUser.getListedCount()), "listed_count"));
        if (tUser.getDescription() != null) {
            annoService.addFeature(userInfo,
                    annoService.createTypedFeature(String.valueOf(tUser.getDescription()), "description"));
        }
        annoService.addAnnotation(user, userInfo);
    }

    Contribution curContrib = contributionService.createTypedContribution(ContributionTypes.TWEET);
    DataSourceInstance contribSource = dataSourceService.createIfNotExists(new DataSourceInstance(
            String.valueOf(tweet.getId()), TweetSourceMapping.ID_TO_CONTRIBUTION, datasetName));
    curContrib.setStartTime(tweet.getCreatedAt());
    dataSourceService.addSource(curContrib, contribSource);

    AnnotationInstance tweetInfo = annoService.createTypedAnnotation("twitter_tweet_info");
    if (tweet.getSource() != null) {
        annoService.addFeature(tweetInfo, annoService.createTypedFeature(tweet.getSource(), "tweet_source"));
    }

    annoService.addFeature(tweetInfo,
            annoService.createTypedFeature(String.valueOf(tweet.getFavoriteCount()), "favorites_count"));

    if (tweet.getHashtagEntities() != null) {
        for (HashtagEntity hashtag : tweet.getHashtagEntities()) {
            annoService.addFeature(tweetInfo, annoService.createTypedFeature(hashtag.getText(), "hashtag"));
        }
    }

    if (tweet.getMediaEntities() != null) {
        for (MediaEntity media : tweet.getMediaEntities()) {
            //NOTE: additional info is available for MediaEntities
            annoService.addFeature(tweetInfo, annoService.createTypedFeature(media.getMediaURL(), "media_url"));
        }
    }

    //TODO this should be represented as a relation if the related tweet is part of the dataset
    if (tweet.getInReplyToStatusId() > 0) {
        annoService.addFeature(tweetInfo, annoService
                .createTypedFeature(String.valueOf(tweet.getInReplyToStatusId()), "in_reply_to_status_id"));
    }

    //TODO this should be represented as a relation if the related tweet is part of the dataset
    if (tweet.getInReplyToScreenName() != null) {
        annoService.addFeature(tweetInfo,
                annoService.createTypedFeature(tweet.getInReplyToScreenName(), "in_reply_to_screen_name"));
    }
    annoService.addAnnotation(curContrib, tweetInfo);

    GeoLocation geo = tweet.getGeoLocation();
    if (geo != null) {
        AnnotationInstance coord = annoService.createTypedAnnotation("twitter_tweet_geo_location");
        annoService.addFeature(coord,
                annoService.createTypedFeature(String.valueOf(geo.getLongitude()), "long"));
        annoService.addFeature(coord, annoService.createTypedFeature(String.valueOf(geo.getLatitude()), "lat"));
        annoService.addAnnotation(curContrib, coord);
    }

    Place place = tweet.getPlace();
    if (place != null) {
        AnnotationInstance placeAnno = annoService.createTypedAnnotation("twitter_tweet_place");
        annoService.addFeature(placeAnno,
                annoService.createTypedFeature(String.valueOf(place.getPlaceType()), "place_type"));
        if (place.getGeometryType() != null) {
            annoService.addFeature(placeAnno,
                    annoService.createTypedFeature(String.valueOf(place.getGeometryType()), "geo_type"));
        }
        annoService.addFeature(placeAnno, annoService
                .createTypedFeature(String.valueOf(place.getBoundingBoxType()), "bounding_box_type"));
        annoService.addFeature(placeAnno,
                annoService.createTypedFeature(String.valueOf(place.getFullName()), "place_name"));
        if (place.getStreetAddress() != null) {
            annoService.addFeature(placeAnno,
                    annoService.createTypedFeature(String.valueOf(place.getStreetAddress()), "street_address"));
        }
        annoService.addFeature(placeAnno,
                annoService.createTypedFeature(String.valueOf(place.getCountry()), "country"));
        if (place.getBoundingBoxCoordinates() != null) {
            annoService.addFeature(placeAnno, annoService.createTypedFeature(
                    convertGeoLocationArray(place.getBoundingBoxCoordinates()), "bounding_box_lat_lon_array"));
        }
        if (place.getGeometryCoordinates() != null) {
            annoService.addFeature(placeAnno, annoService.createTypedFeature(
                    convertGeoLocationArray(place.getGeometryCoordinates()), "geometry_lat_lon_array"));
        }
        annoService.addAnnotation(curContrib, placeAnno);
    }

    Content curContent = contentService.createContent();
    curContent.setText(tweet.getText());
    curContent.setAuthor(user);
    curContent.setStartTime(tweet.getCreatedAt());
    curContrib.setCurrentRevision(curContent);
    curContrib.setFirstRevision(curContent);

    DataSourceInstance contentSource = dataSourceService.createIfNotExists(new DataSourceInstance(
            String.valueOf(tweet.getId()), TweetSourceMapping.ID_TO_CONTENT, datasetName));
    dataSourceService.addSource(curContent, contentSource);

    if (pemsMetaData != null) {
        log.warn("PEMS station meta data mapping not implemented yet");
        //TODO map pems meta data if available         
    }
}

From source file:edu.cmu.geolocator.coder.utils.JSON2Tweet.java

License:Apache License

public JSONTweet readLine() {
    String line;/*from ww w  . j  av a  2  s  .c o  m*/
    try {
        line = br.readLine();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    if (line == null)
        return null;

    Status tweet = null;
    try {
        // parse json to object type
        tweet = DataObjectFactory.createStatus(line);
    } catch (TwitterException e) {
        System.err.println("error parsing tweet object");
        return null;
    }

    jsontweet.JSON = line;
    jsontweet.id = tweet.getId();
    jsontweet.source = tweet.getSource();
    jsontweet.text = tweet.getText();
    jsontweet.createdat = tweet.getCreatedAt();
    jsontweet.tweetgeolocation = tweet.getGeoLocation();

    User user;
    if ((user = tweet.getUser()) != null) {

        jsontweet.userdescription = user.getDescription();
        jsontweet.userid = user.getId();
        jsontweet.userlanguage = user.getLang();
        jsontweet.userlocation = user.getLocation();
        jsontweet.username = user.getName();
        jsontweet.usertimezone = user.getTimeZone();
        jsontweet.usergeoenabled = user.isGeoEnabled();

        if (user.getURL() != null) {
            String url = user.getURL().toString();

            jsontweet.userurl = url;

            String addr = url.substring(7).split("/")[0];
            String[] countrysuffix = addr.split("[.]");
            String suffix = countrysuffix[countrysuffix.length - 1];

            jsontweet.userurlsuffix = suffix;

            try {
                InetAddress address = null;//InetAddress.getByName(user.getURL().getHost());

                String generate_URL
                // =
                // "http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="
                        = "http://www.geoplugin.net/php.gp?ip=" + address.getHostAddress();
                URL data = new URL(generate_URL);
                URLConnection yc = data.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                String inputLine;
                String temp = "";
                while ((inputLine = in.readLine()) != null) {
                    temp += inputLine + "\n";
                }
                temp = temp.split("s:2:\"")[1].split("\"")[0];

                jsontweet.userurllocation = temp;

            } catch (Exception uhe) {
                //uhe.printStackTrace();
                jsontweet.userurllocation = null;
            }
        }
    }

    return jsontweet;

}

From source file:edu.cmu.geolocator.coder.utils.JSON2Tweet.java

License:Apache License

public static JSONTweet getJSONTweet(String JSONString) {
    JSONTweet jsontweet = new JSONTweet();
    if (JSONString == null)
        return null;

    Status tweet = null;
    try {// w w w.j a  va  2s .c o m
        // parse json to object type
        tweet = DataObjectFactory.createStatus(JSONString);
    } catch (TwitterException e) {
        System.err.println("error parsing tweet object");
        return null;
    }

    jsontweet.JSON = JSONString;
    jsontweet.id = tweet.getId();
    jsontweet.source = tweet.getSource();
    jsontweet.text = tweet.getText();
    jsontweet.createdat = tweet.getCreatedAt();
    jsontweet.tweetgeolocation = tweet.getGeoLocation();

    User user;
    if ((user = tweet.getUser()) != null) {

        jsontweet.userdescription = user.getDescription();
        jsontweet.userid = user.getId();
        jsontweet.userlanguage = user.getLang();
        jsontweet.userlocation = user.getLocation();
        jsontweet.username = user.getName();
        jsontweet.usertimezone = user.getTimeZone();
        jsontweet.usergeoenabled = user.isGeoEnabled();

        if (user.getURL() != null) {
            String url = user.getURL().toString();

            jsontweet.userurl = url;

            String addr = url.substring(7).split("/")[0];
            String[] countrysuffix = addr.split("[.]");
            String suffix = countrysuffix[countrysuffix.length - 1];

            jsontweet.userurlsuffix = suffix;

            try {
                InetAddress address = null;//InetAddress.getByName(user.getURL().getHost());

                String generate_URL
                // =
                // "http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="
                        = "http://www.geoplugin.net/php.gp?ip=" + address.getHostAddress();
                URL data = new URL(generate_URL);
                URLConnection yc = data.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                String inputLine;
                String temp = "";
                while ((inputLine = in.readLine()) != null) {
                    temp += inputLine + "\n";
                }
                temp = temp.split("s:2:\"")[1].split("\"")[0];

                jsontweet.userurllocation = temp;

            } catch (Exception uhe) {
                //uhe.printStackTrace();
                jsontweet.userurllocation = null;
            }
        }
    }

    return jsontweet;

}

From source file:edu.uci.ics.asterix.external.util.TweetProcessor.java

License:Apache License

public AMutableRecord processNextTweet(Status tweet) {
    User user = tweet.getUser();/*from   w w w . j  ava 2  s.  c  o m*/
    ((AMutableString) mutableUserFields[0]).setValue(getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[1]).setValue(getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[2]).setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[3]).setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[4]).setValue(getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[5]).setValue(user.getFollowersCount());

    ((AMutableString) mutableTweetFields[0]).setValue(tweet.getId() + "");

    for (int i = 0; i < 6; i++) {
        ((AMutableRecord) mutableTweetFields[1]).setValueAtPos(i, mutableUserFields[i]);
    }
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[2]).setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[3]).setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[2]).setValue(0);
        ((AMutableDouble) mutableTweetFields[3]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[4]).setValue(getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[5]).setValue(getNormalizedString(tweet.getText()));

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

    return mutableRecord;

}

From source file:es.upm.oeg.entity.extractor.extractor.gate.TwitterCorpus.java

public void createCorpus() {

    repository = new FarolasRepo();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//from  ww w .  j  a  va 2s .com
    try {
        corpus = Factory.newCorpus("tweetcorpus");
        Query query = new Query(queryString); //"oddfarolas"
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            Document doc = Factory.newDocument(tweet.getText());
            doc.setName(String.valueOf(tweet.getId()));
            corpus.add(doc);

            logger.info(tweet.getId() + "  @" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " -"
                    + tweet.getGeoLocation());
            repository.instanciateNew(String.valueOf(tweet.getId()), tweet.getUser().getScreenName(),
                    tweet.getText(), tweet.getGeoLocation());

        }

    } catch (TwitterException te) {
        logger.error(te);
        logger.error("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    } catch (ResourceInstantiationException ex) {
        logger.error(ex);
    }
    logger.info("corpus size" + corpus.size());

}

From source file:ezbake.training.TweetIngestParser.java

License:Apache License

private Tweet convertToTweet(Status status) {
    Tweet tweet = new Tweet();
    tweet.setTimestamp(status.getCreatedAt().getTime());
    tweet.setId(status.getId());// ww w  .j av  a2s  .c o m
    tweet.setText(status.getText());
    tweet.setUserId(status.getUser().getId());
    tweet.setUserName(status.getUser().getName());
    tweet.setIsFavorite(status.isFavorited());
    tweet.setIsRetweet(status.isRetweet());
    if (status.getGeoLocation() != null) {
        tweet.setGeoLocation(
                new Coordinate(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
    }
    return tweet;
}

From source file:gui.project2.v1.FXMLDocumentController.java

@FXML
public void searchloaction() throws InterruptedException {
    int maxFollowerCount = 0;
    userslocations = new ArrayList<>();
    nodes = new ArrayList<>();

    GraphicsContext gc = graph.getGraphicsContext2D();
    gc.setFill(Color.GAINSBORO);//from  w ww.  ja v a  2 s. c o m
    gc.fillRect(0, 0, 308, 308);
    Twitter twitter;
    twitter = tf.getInstance();
    ArrayList<User> users = new ArrayList<>();
    try {
        Query query = new Query("");

        GeoLocation location;
        location = new GeoLocation(parseDouble(latitude.getText()), parseDouble(longitude.getText()));
        Query.Unit unit = Query.KILOMETERS;
        query.setGeoCode(location, parseDouble(radius.getText()), unit);
        QueryResult result;

        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();

            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                boolean q = false;
                if (userslocations != null && !userslocations.isEmpty()) {
                    for (int i = 0; i < userslocations.size(); i++) {
                        if (userslocations.get(i).getName().equals(tweet.getUser().getScreenName())) {
                            q = true;
                            break;
                        }
                    }
                }

                if (!q && tweet.getGeoLocation() != null) {
                    pair n;
                    String latString = "";
                    String lonString = "";
                    int la = 0;
                    int lo = 0;
                    String geoString = tweet.getGeoLocation().toString();
                    for (int i = 0; i < geoString.length(); i++) {
                        if (geoString.charAt(i) == '=') {
                            if (la == 0) {
                                la = 1;
                            } else if (la == -1) {
                                lo = 1;
                            }
                        } else if (geoString.charAt(i) == ',') {
                            la = -1;
                        } else if (geoString.charAt(i) == '}') {
                            lo = -1;
                        } else if (la == 1) {
                            latString = latString + geoString.charAt(i);
                        } else if (lo == 1) {
                            lonString = lonString + geoString.charAt(i);
                        }
                    }
                    User thisUser;
                    thisUser = tweet.getUser();
                    double lat = parseDouble(latString);
                    double lon = parseDouble(lonString);
                    System.out.println(tweet.getGeoLocation().toString());
                    n = new pair(tweet.getUser().getScreenName(), lat, lon);
                    userslocations.add(n);
                    users.add(thisUser);
                    if (thisUser.getFollowersCount() > maxFollowerCount) {
                        maxFollowerCount = thisUser.getFollowersCount();
                    }
                }

            }
        } while ((query = result.nextQuery()) != null);
        for (int i = 0; i < users.size(); i++) {
            if (i % 14 == 0 && i != 0) {
                Thread.sleep(1000 * 60 * 15 + 30);
            }
            IDs friends;
            friends = twitter.getFriendsIDs(users.get(i).getId(), -1);
            for (long j : friends.getIDs()) {
                for (int k = i + 1; k < users.size(); k++) {
                    if (users.get(k).getId() == j) {
                        nodes.add(users.get(i).getScreenName() + ":" + users.get(k).getScreenName());
                    }
                }
            }
        }

    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    double xmin;
    double xmax;
    double ymin;
    double ymax;
    xmin = userslocations.get(0).getA();
    xmax = userslocations.get(0).getA();
    ymin = userslocations.get(0).getB();
    ymax = userslocations.get(0).getB();
    for (int i = 1; i < userslocations.size(); i++) {
        if (xmin > userslocations.get(i).getA()) {
            xmin = userslocations.get(i).getA();
        }
        if (xmax < userslocations.get(i).getA()) {
            xmax = userslocations.get(i).getA();
        }
        if (ymin > userslocations.get(i).getB()) {
            ymin = userslocations.get(i).getB();
        }
        if (ymax < userslocations.get(i).getB()) {
            ymax = userslocations.get(i).getB();
        }
    }
    for (int i = 0; i < userslocations.size(); i++) {
        if (userslocations.get(i).getA() - xmin >= 0 && userslocations.get(i).getB() - ymin >= 0) {
            gc.setLineWidth(users.get(i).getFollowersCount() / maxFollowerCount * 3 + 1);
            gc.strokeOval((userslocations.get(i).getA() - xmin) / (xmax - xmin) * 300 + 4,
                    (userslocations.get(i).getB() - ymin) / (ymax - ymin) * 300 + 4, 4, 4);
        }

    }
    ObservableList<String> usersLeftList = FXCollections.observableArrayList();
    for (int i = 0; i < users.size() - 1; i++) {
        User k = null;
        for (int j = i + 1; j < users.size(); j++) {
            if (users.get(j).getFollowersCount() > users.get(i).getFollowersCount()) {
                k = users.get(i);
                users.set(i, users.get(j));
                users.set(j, k);
            }
        }
    }
    for (int i = 0; i < users.size() / 5; i++) {
        usersLeftList.add(users.get(i).getScreenName() + " " + users.get(i).getFollowersCount());
    }
    listView.setItems(usersLeftList);
    gc.setLineWidth(1);
    gc.setFill(Color.BLUE);
    for (int i = 0; i < nodes.size(); i++) {
        String user1 = "";
        String user2 = "";
        int p = 0;
        double x1 = 0;
        double x2 = 0;
        double y1 = 0;
        double y2 = 0;
        for (int j = 0; j < nodes.get(i).length(); j++) {
            if (nodes.get(i).charAt(j) == ':') {
                p = 1;
            } else if (p == 0) {
                user1 = user1 + nodes.get(i).charAt(j);
            } else if (p == 1) {
                user2 = user2 + nodes.get(i).charAt(j);
            }
        }
        for (int j = 0; j < userslocations.size(); j++) {
            if (userslocations.get(j).getName().equals(user1)) {
                x1 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6;
                y1 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6;
            } else if (userslocations.get(j).getName().equals(user2)) {
                x2 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6;
                y2 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6;
            }
        }
        gc.strokeLine(x1, y1, x2, y2);
        gc.fillOval(x1 - 2, y1 - 2, 4, 4);
        gc.fillOval(x2 - 2, y2 - 2, 4, 4);
    }
}

From source file:h2weibo.Twitter2Weibo.java

License:Open Source License

public void syncTwitter(String userId) {
    T2WUser user = helper.findOneByUser(userId);

    weibo.setToken(user.getToken(), user.getTokenSecret());

    Twitter twitter = new TwitterFactory().getInstance();
    if (user.getTwitterToken() != null) {
        twitter.setOAuthAccessToken(new AccessToken(user.getTwitterToken(), user.getTwitterTokenSecret()));
        log.debug(String.format("Using OAuth for %s", user.getUserId()));
    }/*from w w  w .j  a va 2  s .co m*/

    StatusFilters filters = new StatusFilters();
    filters.use(new NoSyncFilter()); // should be used first
    filters.use(new TcoStatusFilter()).use(new URLStatusFilter()).use(new TagStatusFilter())
            .use(new FlickrImageFilter());

    NoMentionFilter mentionFilter = new NoMentionFilter();
    UserMappingFilter mappingFilter = new UserMappingFilter(helper);

    if (!user.ready()) {
        log.debug(String.format("Skipping @%s ...", user.getUserId()));
        return;
    }

    // gets Twitter instance with default credentials
    String screenName = user.getUserId();
    long latestId = user.getLatestId();

    log.debug(String.format("Checking @%s's timeline, latest ID = %d.", userId, latestId));

    try {
        if (latestId == 0) {
            List<Status> statuses = twitter.getUserTimeline(screenName);
            if (statuses.size() > 0) {
                user.setLatestId(statuses.get(0).getId()); // Record latestId, and sync next time
            }
            log.info(String.format("First time use for @%s. Set latest ID to %d.", userId, latestId));
        } else {
            Paging paging = new Paging(latestId);
            List<Status> statuses = twitter.getUserTimeline(screenName, paging);

            // sync from the oldest one
            for (int i = statuses.size() - 1; i >= 0; i--) {
                Status status = statuses.get(i);

                if (status.getId() < user.getLatestId())
                    continue; // safe keeper

                String name = status.getUser().getScreenName();
                String statusText = status.getText();
                log.info(String.format("%s - %s", name, statusText));
                try {
                    if (status.isRetweet()) {
                        if (user.isDropRetweets()) {
                            user.setLatestId(status.getId());
                            log.debug("Skipped " + statusText + " because status is a retweet.");
                            continue;
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    } else {
                        if (user.isDropMentions()) {
                            filters.remove(mappingFilter);
                            filters.use(mentionFilter);
                        } else {
                            filters.remove(mentionFilter);
                            filters.use(mappingFilter);
                        }
                    }

                    statusText = filters.filter(statusText);
                    if (statusText == null) {
                        user.setLatestId(status.getId());
                        log.info(String.format("Skipped %s because of the filter.", statusText));
                        continue;
                    }

                    if (!user.isNoImage()) {
                        // add twitter images to status text
                        MediaEntity[] mediaEntities = status.getMediaEntities();
                        if (mediaEntities != null) {
                            for (MediaEntity entity : mediaEntities) {
                                statusText += " " + entity.getMediaURL();
                            }
                            log.info("with media url: " + statusText);
                        }

                        StatusImageExtractor ex = new StatusImageExtractor();
                        StringBuffer buf = new StringBuffer(statusText);
                        byte[] image = ex.extract(buf);
                        if (image != null) {
                            user.setLatestId(status.getId());
                            try {
                                statusText = buf.toString(); // with image urls removed
                                weibo.uploadStatus(statusText, new ImageItem(image));
                                log.info(String.format("@%s - %s sent with image.", name, statusText));
                            } catch (WeiboException e) {
                                log.error("Faile to update image.", e);
                            }
                            continue;
                        }
                    }

                    GeoLocation location = status.getGeoLocation();
                    if (user.isWithGeo() && location != null) {
                        weibo.updateStatus(statusText, location.getLatitude(), location.getLongitude());
                        log.info(String.format("@%s - %s sent with geo locations.", name, statusText));
                    } else {
                        weibo.updateStatus(statusText);
                        log.info(String.format("@%s - %s sent.", name, statusText));
                    }
                } catch (WeiboException e) {
                    if (e.getStatusCode() != 400) { // resending same tweet
                        log.error("Failed to update Weibo", e);
                        break;
                    } else {
                        log.error("Sending same message", e);
                    }
                }
                log.info(String.format("Sent: by %s - %s", name, statusText));
                user.setLatestId(status.getId());
            }
        }
        helper.saveUser(user);
    } catch (Exception e) {
        if (!(e instanceof TwitterException)) {
            log.error("Failed to update.", e);
        }
    }
}