Example usage for twitter4j GeoLocation getLatitude

List of usage examples for twitter4j GeoLocation getLatitude

Introduction

In this page you can find the example usage for twitter4j GeoLocation getLatitude.

Prototype

public double getLatitude() 

Source Link

Document

returns the latitude of the geo location

Usage

From source file:com.klinker.android.twitter.activities.tweet_viewer.fragments.TweetFragment.java

License:Apache License

public void getInfo(final View favButton, final TextView favCount, final TextView retweetCount,
        final long tweetId, final View retweetButton) {

    Thread getInfo = new Thread(new Runnable() {
        @Override/*from w w  w .  j a v  a2 s. c om*/
        public void run() {
            String location = "";
            String via = "";
            long realTime = 0;
            boolean retweetedByMe = false;
            try {
                Twitter twitter = getTwitter();

                TwitterMultipleImageHelper helper = new TwitterMultipleImageHelper();
                status = twitter.showStatus(tweetId);

                ArrayList<String> i = new ArrayList<String>();

                if (picture) {
                    i = helper.getImageURLs(status, twitter);
                }

                final ArrayList<String> images = i;

                GeoLocation loc = status.getGeoLocation();
                try {
                    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(),
                            1);
                    if (addresses.size() > 0) {
                        Address address = addresses.get(0);
                        location += address.getLocality() + ", " + address.getCountryName();
                    } else {
                        location = "";
                    }
                } catch (Exception x) {
                    location = "";
                }

                via = android.text.Html.fromHtml(status.getSource()).toString();

                final String sfavCount;
                if (status.isRetweet()) {
                    twitter4j.Status status2 = status.getRetweetedStatus();
                    via = android.text.Html.fromHtml(status2.getSource()).toString();
                    realTime = status2.getCreatedAt().getTime();
                    sfavCount = status2.getFavoriteCount() + "";
                } else {
                    realTime = status.getCreatedAt().getTime();
                    sfavCount = status.getFavoriteCount() + "";
                }

                retweetedByMe = status.isRetweetedByMe();
                final String retCount = "" + status.getRetweetCount();

                final String timeDisplay;

                if (!settings.militaryTime) {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(realTime)
                            + " " + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(realTime);
                } else {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN).format(realTime)
                            + " "
                            + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.GERMAN).format(realTime);
                }
                final String fVia = " " + getResources().getString(R.string.via) + " " + via;
                final String fLoc = location.equals("") ? "" : "\n" + location;

                final boolean fRet = retweetedByMe;
                final long fTime = realTime;
                final Status fStatus = status;
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        retweetCount.setText(" " + retCount);

                        if (retweetButton instanceof ImageButton) {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    ((ImageButton) retweetButton)
                                            .setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) retweetButton).setColorFilter(settings.accentInt);
                                }
                            } else {
                                ((ImageButton) retweetButton).clearColorFilter();
                            }
                        } else {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    retweetButton.setBackgroundColor(
                                            context.getResources().getColor(R.color.app_color));
                                } else {
                                    retweetButton.setBackgroundColor(settings.accentInt);
                                }
                            } else {
                                retweetButton.setBackgroundColor(
                                        getResources().getColor(android.R.color.transparent));
                            }
                        }

                        timetv.setText(timeDisplay + fVia);
                        timetv.append(fLoc);

                        favCount.setText(" " + sfavCount);

                        if (favButton instanceof ImageButton) {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                if (!settings.addonTheme) {
                                    ((ImageButton) favButton)
                                            .setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) favButton).setColorFilter(settings.accentInt);
                                }

                                ((ImageButton) favButton)
                                        .setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = true;
                            } else {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.notFavoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                ((ImageButton) favButton)
                                        .setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = false;

                                ((ImageButton) favButton).clearColorFilter();
                            }
                        } else {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                if (!settings.addonTheme) {
                                    favButton.setBackgroundColor(
                                            context.getResources().getColor(R.color.app_color));
                                } else {
                                    favButton.setBackgroundColor(settings.accentInt);
                                }

                                isFavorited = true;
                            } else {
                                isFavorited = false;

                                favButton.setBackgroundColor(
                                        getResources().getColor(android.R.color.transparent));
                            }
                        }

                        for (String s : images) {
                            Log.v("talon_image", s);
                        }
                        if (images.size() > 1) {
                            Log.v("talon_images", "size: " + images.size());
                            try {
                                mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                                    @Override
                                    public void onViewTap(View view, float x, float y) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            } catch (Exception e) {
                                // addon theme without the attacher
                                profilePic.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            }
                        }

                    }
                });
            } catch (Exception e) {

            }
        }
    });

    getInfo.setPriority(Thread.MAX_PRIORITY);
    getInfo.start();
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.fragments.TweetFragment.java

License:Apache License

public void getInfo(final View favButton, final TextView favCount, final TextView retweetCount,
        final long tweetId, final View retweetButton) {

    Thread getInfo = new Thread(new Runnable() {
        @Override//from ww  w .ja  va2s. c  o m
        public void run() {
            String location = "";
            String via = "";
            long realTime = 0;
            boolean retweetedByMe = false;
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                TwitterMultipleImageHelper helper = new TwitterMultipleImageHelper();
                status = twitter.showStatus(tweetId);

                ArrayList<String> i = new ArrayList<String>();

                if (picture) {
                    i = helper.getImageURLs(status, twitter);
                }

                final ArrayList<String> images = i;

                GeoLocation loc = status.getGeoLocation();
                try {
                    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(),
                            1);
                    if (addresses.size() > 0) {
                        Address address = addresses.get(0);
                        location += address.getLocality() + ", " + address.getCountryName();
                    } else {
                        location = "";
                    }
                } catch (Exception x) {
                    location = "";
                }

                via = android.text.Html.fromHtml(status.getSource()).toString();

                final String sfavCount;
                if (status.isRetweet()) {
                    twitter4j.Status status2 = status.getRetweetedStatus();
                    via = android.text.Html.fromHtml(status2.getSource()).toString();
                    realTime = status2.getCreatedAt().getTime();
                    sfavCount = status2.getFavoriteCount() + "";
                } else {
                    realTime = status.getCreatedAt().getTime();
                    sfavCount = status.getFavoriteCount() + "";
                }

                retweetedByMe = status.isRetweetedByMe();
                final String retCount = "" + status.getRetweetCount();

                final String timeDisplay;

                if (!settings.militaryTime) {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(realTime)
                            + " " + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.US).format(realTime);
                } else {
                    timeDisplay = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN).format(realTime)
                            + " "
                            + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.GERMAN).format(realTime);
                }
                final String fVia = " " + getResources().getString(R.string.via) + " " + via;
                final String fLoc = location.equals("") ? "" : "\n" + location;

                final boolean fRet = retweetedByMe;
                final long fTime = realTime;
                final Status fStatus = status;
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        // you can't retweet a protected account
                        if (status.getUser().isProtected()) {
                            retweetButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Toast.makeText(context, getString(R.string.protected_account),
                                            Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        retweetCount.setText(" " + retCount);

                        if (retweetButton instanceof ImageButton) {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    ((ImageButton) retweetButton)
                                            .setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) retweetButton).setColorFilter(settings.accentInt);
                                }
                            } else {
                                ((ImageButton) retweetButton).clearColorFilter();
                            }
                        } else {
                            if (fRet) {
                                if (!settings.addonTheme) {
                                    retweetButton.setBackgroundColor(
                                            context.getResources().getColor(R.color.app_color));
                                } else {
                                    retweetButton.setBackgroundColor(settings.accentInt);
                                }
                            } else {
                                retweetButton.setBackgroundColor(
                                        getResources().getColor(android.R.color.transparent));
                            }
                        }

                        timetv.setText(timeDisplay + fVia);
                        timetv.append(fLoc);

                        favCount.setText(" " + sfavCount);

                        if (favButton instanceof ImageButton) {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                if (!settings.addonTheme) {
                                    ((ImageButton) favButton)
                                            .setColorFilter(context.getResources().getColor(R.color.app_color));
                                } else {
                                    ((ImageButton) favButton).setColorFilter(settings.accentInt);
                                }

                                ((ImageButton) favButton)
                                        .setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = true;
                            } else {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.notFavoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                ((ImageButton) favButton)
                                        .setImageDrawable(context.getResources().getDrawable(resource));
                                isFavorited = false;

                                ((ImageButton) favButton).clearColorFilter();
                            }
                        } else {
                            if (fStatus.isFavorited()) {
                                TypedArray a = context.getTheme()
                                        .obtainStyledAttributes(new int[] { R.attr.favoritedButton });
                                int resource = a.getResourceId(0, 0);
                                a.recycle();

                                if (!settings.addonTheme) {
                                    favButton.setBackgroundColor(
                                            context.getResources().getColor(R.color.app_color));
                                } else {
                                    favButton.setBackgroundColor(settings.accentInt);
                                }

                                isFavorited = true;
                            } else {
                                isFavorited = false;

                                favButton.setBackgroundColor(
                                        getResources().getColor(android.R.color.transparent));
                            }
                        }

                        for (String s : images) {
                            Log.v("talon_image", s);
                        }
                        if (images.size() > 1) {
                            Log.v("talon_images", "size: " + images.size());
                            try {
                                mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
                                    @Override
                                    public void onViewTap(View view, float x, float y) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            } catch (Exception e) {
                                // addon theme without the attacher
                                profilePic.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent viewPics = new Intent(context, ViewPictures.class);
                                        viewPics.putExtra("images", images);
                                        startActivity(viewPics);
                                    }
                                });
                            }
                        }

                    }
                });
            } catch (Exception e) {

            }
        }
    });

    getInfo.setPriority(Thread.MAX_PRIORITY);
    getInfo.start();
}

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(String keyword) {
    try {//w w w .j  av  a  2 s .  c  om
        Query query = new Query(keyword);
        query.setCount(20000);
        QueryResult result;
        result = twitter.search(query);

        //System.out.println("Getting Tweets..by Key.");
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_Rname", tweet.getUser().getName());
            basicObj.put("user_name", tweet.getUser().getScreenName());
            basicObj.put("retweet_count", tweet.getRetweetCount());
            basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount());

            UserMentionEntity[] mentioned = tweet.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", tweet.getId());
            basicObj.put("tweet_text", tweet.getText());
            Status temp1 = tweet.getRetweetedStatus();
            if (temp1 != null)
                basicObj.put("Re_tweet_ID", temp1.getUser().getId());
            GeoLocation loc = tweet.getGeoLocation();
            if (loc != null) {
                basicObj.put("Latitude", loc.getLatitude());
                basicObj.put("Longitude", loc.getLongitude());
            }
            basicObj.put("CreateTime", tweet.getCreatedAt());
            basicObj.put("FavoriteCount", tweet.getFavoriteCount());
            basicObj.put("user_Id", tweet.getUser().getId());

            if (tweet.getUser().getTimeZone() != null)
                basicObj.put("UsertimeZone", tweet.getUser().getTimeZone());
            if (tweet.getUser().getStatus() != null)
                basicObj.put("UserStatus", tweet.getUser().getStatus());
            //basicObj.put("tweetLocation", tweet.getPlace().getGeometryCoordinates());
            String U_Loc = tweet.getUser().getLocation();
            if (U_Loc != null)
                basicObj.put("userLocation", U_Loc);
            basicObj.put("number_of_rt", tweet.getRetweetCount());

            if (mentioned.length > 0) {
                basicObj.append("mentions", pickMentions(mentioned));
            }
            try {

                collection.insert(basicObj);
            } catch (Exception e) {
                //System.out.println("MongoDB Connection Error : " + e.getMessage());
                //                            loadMenu();
            }
        }
        collection.ensureIndex(new BasicDBObject("tweet_ID", 1), new BasicDBObject("unique", true));
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(GeoLocation myLoc, double radius) {
    try {//from   w ww .  ja v a 2s. co  m
        Query query = new Query();
        Query.Unit unit = Query.KILOMETERS; // or Query.MILES;
        query.setGeoCode(myLoc, radius, unit);
        if (radius > 200)
            query.setCount(20000);
        else
            query.setCount(20000);

        QueryResult result;
        result = this.twitter.search(query);

        //System.out.println("Getting Tweets. by Geo..");
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_Rname", tweet.getUser().getName());
            basicObj.put("user_name", tweet.getUser().getScreenName());
            basicObj.put("retweet_count", tweet.getRetweetCount());
            basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount());

            UserMentionEntity[] mentioned = tweet.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", tweet.getId());
            basicObj.put("tweet_text", tweet.getText());
            Status temp1 = tweet.getRetweetedStatus();
            if (temp1 != null)
                basicObj.put("Re_tweet_ID", temp1.getUser().getId());
            GeoLocation loc = tweet.getGeoLocation();
            if (loc != null) {
                basicObj.put("Latitude", loc.getLatitude());
                basicObj.put("Longitude", loc.getLongitude());
            }
            basicObj.put("CreateTime", tweet.getCreatedAt());
            basicObj.put("FavoriteCount", tweet.getFavoriteCount());
            basicObj.put("user_Id", tweet.getUser().getId());

            if (tweet.getUser().getTimeZone() != null)
                basicObj.put("UsertimeZone", tweet.getUser().getTimeZone());
            if (tweet.getUser().getStatus() != null)
                basicObj.put("UserStatus", tweet.getUser().getStatus());
            //basicObj.put("tweetLocation", tweet.getPlace().getGeometryCoordinates());
            String U_Loc = tweet.getUser().getLocation();
            if (U_Loc != null)
                basicObj.put("userLocation", U_Loc);
            basicObj.put("number_of_rt", tweet.getRetweetCount());
            //basicObj.put("isRetweet", tweet.getPlace().getGeometryCoordinates());                
            //basicObj.put("POS", tweet.getWithheldInCountries());

            if (mentioned.length > 0) {
                basicObj.append("mentions", pickMentions(mentioned));
            }
            try {
                //items.insert(basicObj);
                collection.insert(basicObj);
            } catch (Exception e) {
                //     System.out.println("MongoDB Connection Error : " + e.getMessage());
                //                            loadMenu();
            }
        }
        collection.ensureIndex(new BasicDBObject("tweet_ID", 1), new BasicDBObject("unique", true));
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:DataCollections.PlaceHelper.java

public String stringifyBoundingBoxCoordinates(GeoLocation[][] boundingboxcoor) {
    JSONArray jsonarray = new JSONArray();

    for (GeoLocation[] gls : boundingboxcoor) {
        for (GeoLocation g : gls) {
            JSONArray coor = new JSONArray();
            coor.add(g.getLongitude());//from  www  .  j av  a2  s  .  c o  m
            coor.add(g.getLatitude());
            jsonarray.add(coor);
        }
    }

    return jsonarray.toJSONString();
}

From source file:DataCollections.PlaceHelper.java

public double[] computeCentroid(GeoLocation[][] boundingboxcoor) {
    double[] centroid = new double[2];
    int count = 0;
    for (GeoLocation[] gls : boundingboxcoor) {
        for (GeoLocation g : gls) {
            centroid[0] += g.getLongitude();
            centroid[1] += g.getLatitude();
            count++;/*from   ww  w.ja  va 2  s.com*/
        }
    }

    centroid[0] /= count;
    centroid[1] /= count;
    return centroid;
}

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 ww . j av  a  2  s. c  om*/
    } 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  www .  jav a  2s.  co 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: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()));
    }//w w w. j a va  2s. 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);
        }
    }
}

From source file:im.ligas.twittermap.portlet.TwitterStatusListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    Place place = status.getPlace();//www .jav  a  2  s.  c om
    if (place != null) {
        String iso3Country = new Locale(status.getLang(), status.getPlace().getCountryCode()).getISO3Country();
        JSONObject json = JSONFactoryUtil.createJSONObject();
        json.put("country", iso3Country);
        GeoLocation[][] coordinates = place.getBoundingBoxCoordinates();
        GeoLocation location = coordinates[0][0];
        json.put("lat", location.getLatitude());
        json.put("lng", location.getLongitude());
        LOG.debug(json);
        broadcast(json.toString());
    }
}