Example usage for twitter4j Status getPlace

List of usage examples for twitter4j Status getPlace

Introduction

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

Prototype

Place getPlace();

Source Link

Document

Returns the place attached to this status

Usage

From source file:de.jetwick.tw.TwitterSearch.java

License:Apache License

public static Twitter4JTweet toTweet(Status st, User user) {
    if (user == null)
        throw new IllegalArgumentException("User mustn't be null!");
    if (st == null)
        throw new IllegalArgumentException("Status mustn't be null!");

    Twitter4JTweet tw = new Twitter4JTweet(st.getId(), st.getText(), user.getScreenName());
    tw.setCreatedAt(st.getCreatedAt());//from ww w .j  a  v a2 s . co  m
    tw.setFromUser(user.getScreenName());

    if (user.getProfileImageURL() != null)
        tw.setProfileImageUrl(user.getProfileImageURL().toString());

    tw.setSource(st.getSource());
    tw.setToUser(st.getInReplyToUserId(), st.getInReplyToScreenName());
    tw.setInReplyToStatusId(st.getInReplyToStatusId());

    if (st.getGeoLocation() != null) {
        tw.setGeoLocation(st.getGeoLocation());
        tw.setLocation(st.getGeoLocation().getLatitude() + ", " + st.getGeoLocation().getLongitude());
    } else if (st.getPlace() != null)
        tw.setLocation(st.getPlace().getCountryCode());
    else if (user.getLocation() != null)
        tw.setLocation(toStandardLocation(user.getLocation()));

    return tw;
}

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 .  ja v a2s .  com*/
 * @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:gh.polyu.user.TrackUsers.java

License:Apache License

public void track(final int no, final int p) {
    final TwitterDBHandle handle = new TwitterDBHandle();
    handle.intialTwitterDBhandle();//w w w.  j  ava2  s  .co m

    while (alive) {
        alive = false;
        StatusListener listener = new StatusListener() {
            ArrayList<_TweetLink> listlink = new ArrayList<_TweetLink>();
            int cnt = 0;
            String oldmonth = "20138";
            String table = "UserTweet20138";
            String oldday = "";
            String currentday = "";
            String currentmonth = "";
            long lastinsert = 0l;
            long nowinsert = 0l;
            int newday = 0;
            String newtime = "";

            @Override

            public void onStatus(Status status) {
                if (status.getId() == 123 && status.getText().equals("YOU are WORNG!.")) {
                    System.out.println("Connection Need to be rebuilt!!");
                    alive = true;
                } else if (status.getLang().equals("en")) {
                    _TweetLink tweet = new _TweetLink();
                    String Test = status.getText();
                    tweet.setText(Test);
                    Date time = status.getCreatedAt();
                    tweet.setTime(time);
                    tweet.setUserName(status.getUser().getName());
                    HashtagEntity[] hashtagentity = status.getHashtagEntities();
                    StringBuffer hashen = new StringBuffer();
                    for (int i = 0; i < hashtagentity.length; i++) {
                        hashen.append(hashtagentity[i].getText());
                        hashen.append(";");

                    }
                    tweet.setHashtag(hashen.toString());

                    URLEntity[] URLEn = status.getURLEntities();
                    StringBuffer URL = new StringBuffer();
                    for (int i = 0; i < URLEn.length; i++) {
                        URL.append(URLEn[i].getURL());
                        URL.append(";");

                    }
                    tweet.setURL(URL.toString());

                    //user mention
                    UserMentionEntity[] userEn = status.getUserMentionEntities();
                    StringBuffer mentuser = new StringBuffer();
                    for (int i = 0; i < userEn.length; i++) {
                        mentuser.append(userEn[i].getId());
                        mentuser.append(";");
                    }
                    tweet.setUerMention(mentuser.toString());
                    //if(mentuser.length()!=0);
                    //System.out.println("mentuser: "+ mentuser);
                    //tweetID
                    tweet.setTweetID(status.getId());
                    //if(ID!=null)
                    // original twitterID
                    tweet.setOriginID(status.getInReplyToStatusId());
                    //original user ID
                    tweet.setOriginUser(status.getInReplyToUserId());

                    // user ID

                    User users = status.getUser();
                    tweet.setTweetUser(users.getId());

                    //places
                    Place Pl = status.getPlace();
                    String place = "";
                    if (Pl != null) {
                        place = Pl.getFullName();
                        //System.out.println("place "+place);
                    }
                    tweet.setPlace(place);
                    // Retweetcoun
                    long num = 0;
                    if (status.getRetweetedStatus() != null) {
                        num = status.getRetweetedStatus().getRetweetCount();
                        //System.out.println("retweetcount"+num);
                        tweet.setRetweetCount(num);
                        tweet.setRetweet(1);
                    } else {
                        tweet.setRetweetCount(0);
                        tweet.setRetweet(0);
                    }
                    //   if(Retweet!=null)

                    //System.out.println("Retweetcount: "+ Retweet);

                    //isfavourate
                    boolean favourate = status.isFavorited();
                    /*if(favourate)
                    {
                    fav = 1;
                    tweet.setFavourate(fav);
                    fav =0;
                    System.out.println("isf "+ fav);
                    }*/

                    // is retweet

                    //String other = status.toString();
                    // tweet.setOther(other);
                    listlink.add(tweet);
                    Calendar cal = Calendar.getInstance();
                    int year = cal.get(Calendar.YEAR);
                    int month = cal.get(Calendar.MONTH) + 1;
                    int day = cal.get(Calendar.DAY_OF_MONTH);
                    currentmonth = String.valueOf(year) + String.valueOf(month);
                    currentday = String.valueOf(day);
                    if (currentmonth.equals(oldmonth)) {
                        if (currentday.equals(oldday))
                            ;
                        else {
                            newday = 1;
                            SimpleDateFormat formatter = new SimpleDateFormat("MMddHH:mm:ss ");
                            Date curDate = new Date(System.currentTimeMillis());//     
                            newtime = formatter.format(curDate);
                        }
                    } else {
                        try {
                            handle.database_connection();
                            table = "UserTweet" + String.valueOf(year) + String.valueOf(month);
                            System.out.println("create new table " + table);
                            String CREATE_TABLE = "create table " + table
                                    + "(TweetID varchar(100), UserName varchar(200), TwitterUser varchar(145), OriginID varchar(100), OriginUser varchar(100), place varchar(100), RetweetCount varchar(100), isRetweet int(5), Text varchar(500), Time datetime,"
                                    + "Hashtag varchar(200), URL varchar(200), UerMention varchar(200))";
                            Statement st = handle.conn.createStatement();
                            st.execute(CREATE_TABLE);
                            String Create_Index = "alter table " + table + " add index time (Time)";
                            st.execute(Create_Index);
                            String Create_Index2 = "alter table " + table + " add index userID (TwitterUser)";
                            st.execute(Create_Index2);
                            String key = "ALTER TABLE " + table + " ADD PRIMARY KEY (TweetID)";
                            st.execute(key);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                        handle.close_databasehandle();
                        try {
                            TwitterDBHandle handle2 = new TwitterDBHandle();
                            handle2.intialTwitterDBhandle2();
                            handle2.database_connection();
                            table = "UserTweet" + String.valueOf(year) + String.valueOf(month);
                            System.out.println("create new table " + table);
                            String CREATE_TABLE = "create table " + table
                                    + "(TweetID varchar(100), UserName varchar(200), TwitterUser varchar(145), OriginID varchar(100), OriginUser varchar(100), place varchar(100), RetweetCount varchar(100), isRetweet int(5), Text varchar(500), Time datetime,"
                                    + "Hashtag varchar(200), URL varchar(200), UerMention varchar(200))";
                            Statement st = handle2.conn.createStatement();
                            st.execute(CREATE_TABLE);
                            String Create_Index = "alter table " + table + " add index time (Time)";
                            st.execute(Create_Index);
                            String Create_Index2 = "alter table " + table + " add index userID (TwitterUser)";
                            st.execute(Create_Index2);
                            String key = "ALTER TABLE " + table + " ADD PRIMARY KEY (TweetID)";
                            st.execute(key);
                            handle2.close_databasehandle();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    //System.out.println("OTHER: "+ other);

                    if ((cnt++) % 1000 == 0) {

                        if (newday == 1) {
                            newday = 0;
                            oldday = currentday;
                            GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                            gs.send("THREAD" + p + " :" + "program no" + no + "message" + newtime,
                                    "I am still alive");
                            newtime = "";
                        }

                        try {
                            handle.database_connection();
                            handle.userTweet(table, listlink);
                            nowinsert = System.currentTimeMillis();
                            System.err.println(
                                    "No: " + no + "program " + "totally " + cnt + " tweets downloaded!\n"
                                            + new Date(nowinsert) + "  " + new Date(lastinsert));
                            lastinsert = nowinsert;
                            nowinsert = 0l;
                            handle.close_databasehandle();
                        } catch (SQLException e) {
                            handle.close_databasehandle();
                            e.printStackTrace();
                            // TODO Auto-generated catch block
                            TwitterDBHandle handle2 = new TwitterDBHandle();
                            handle2.intialTwitterDBhandle2();
                            handle2.database_connection();

                            try {
                                handle2.userTweet(table, listlink);
                                nowinsert = System.currentTimeMillis();
                                System.err.println("New Database No: " + no + "program " + "totally " + cnt
                                        + " tweets downloaded!\n" + new Date(nowinsert) + new Date(lastinsert));
                                lastinsert = nowinsert;
                                nowinsert = 0l;
                                handle2.close_databasehandle();
                            } catch (SQLException e1) {
                                // TODO Auto-generated catch block
                                GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                                try {
                                    gs.SendSSLMessage("cscchenyoyo@gmail.com", "program error",
                                            "both databases are down");
                                } catch (MessagingException ee) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            GmailSend gs = new GmailSend("cscchenyoyo@gmail.com", "910316ccy");
                            try {
                                gs.SendSSLMessage("cscchenyoyo@gmail.com", "program error",
                                        "change database to another one");
                            } catch (MessagingException ee) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        listlink.clear();
                    }
                }
            }

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

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

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

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

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

            }
        };
        TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
        twitterOAuth twtOauth = new twitterOAuth();
        twtOauth.AuthoritywithS(twitterStream, key);
        twitterStream.addListener(listener);
        twitterStream.filter(new FilterQuery(0, follow));

        /*  try {
           Thread.sleep(3000);
                   
        } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }*/
    }
}

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

License:Open Source License

@Override
public void onStatus(Status status) {
    Place place = status.getPlace();
    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);/* w w  w.j  av a  2s . c om*/
        broadcast(json.toString());
    }
}

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   w  w w .j  a v  a  2s.  c  o m*/

    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:nl.isaac.dotcms.twitter.pojo.CustomStatus.java

License:Creative Commons License

public CustomStatus(Status status) {
    this.createdAt = status.getCreatedAt();
    this.id = status.getId();
    this.id_str = String.valueOf(status.getId());
    this.text = status.getText();
    this.source = status.getSource();
    this.isTruncated = status.isTruncated();
    this.inReplyToStatusId = status.getInReplyToStatusId();
    this.inReplyToUserId = status.getInReplyToUserId();
    this.isFavorited = status.isFavorited();
    this.inReplyToScreenName = status.getInReplyToScreenName();
    this.geoLocation = status.getGeoLocation();
    this.place = status.getPlace();
    this.retweetCount = status.getRetweetCount();
    this.isPossiblySensitive = status.isPossiblySensitive();

    this.contributorsIDs = status.getContributors();

    this.retweetedStatus = status.getRetweetedStatus();
    this.userMentionEntities = status.getUserMentionEntities();
    this.urlEntities = status.getURLEntities();
    this.hashtagEntities = status.getHashtagEntities();
    this.mediaEntities = status.getMediaEntities();
    this.currentUserRetweetId = status.getCurrentUserRetweetId();

    this.isRetweet = status.isRetweet();
    this.isRetweetedByMe = status.isRetweetedByMe();

    this.rateLimitStatus = status.getRateLimitStatus();
    this.accessLevel = status.getAccessLevel();
    this.user = status.getUser();
}

From source file:nyu.twitter.lg.FentchTwitter.java

License:Open Source License

public static void invoke() throws Exception {
    init();/*w ww .  ja  v a  2 s.co m*/
    // Create table if it does not exist yet
    if (Tables.doesTableExist(dynamoDB, tableName)) {
        System.out.println("Table " + tableName + " is already ACTIVE");
    } else {
        // Create a table with a primary hash key named 'name', which holds
        // a string
        CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
                .withKeySchema(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH))
                .withAttributeDefinitions(new AttributeDefinition().withAttributeName("id")
                        .withAttributeType(ScalarAttributeType.S))
                .withProvisionedThroughput(
                        new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
        TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest)
                .getTableDescription();
        System.out.println("Created Table: " + createdTableDescription);
        // Wait for it to become active
        System.out.println("Waiting for " + tableName + " to become ACTIVE...");
        Tables.waitForTableToBecomeActive(dynamoDB, tableName);
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Emwo2pG").setOAuthConsumerSecret("RM9B7fske5T")
            .setOAuthAccessToken("19ubQOirq").setOAuthAccessTokenSecret("Lbg3C");

    final TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            if (status.getGeoLocation() != null && status.getPlace() != null) {

                //               if (count == 0) {
                //                  count++;
                //               }
                //               
                latitude = status.getGeoLocation().getLatitude();
                longtitude = status.getGeoLocation().getLongitude();
                place = status.getPlace().getCountry() + "," + status.getPlace().getFullName();
                date = status.getCreatedAt().toString();
                id = Integer.toString(count);
                name = status.getUser().getScreenName();
                message = status.getText();
                System.out.println("---------------------------");
                System.out.println("ID:" + count);
                System.out.println("latitude:" + latitude);
                System.out.println("longtitude:" + longtitude);
                System.out.println("place:" + place);
                System.out.println("name:" + name);
                System.out.println("message:" + message);
                System.out.println("data:" + date);
                System.out.println("-------------8-------------");

                insertDB(id, count, name, longtitude, latitude, place, message, date);

                if (++count > 100) {
                    twitterStream.shutdown();
                    System.out.println("Information Collection Completed");
                }
                //      count = (count+1) % 101;
            }
        }

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

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

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

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

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

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());
    }//  ww w  .  j a v a 2  s .c  o m
    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.getlantern.firetweet.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();//from w w  w.  j a v a 2s  . c o m
    timestamp = getTime(orig.getCreatedAt());

    final Status retweeted = orig.getRetweetedStatus();
    final User retweet_user = retweeted != null ? orig.getUser() : null;
    is_retweet = orig.isRetweet();
    retweet_id = retweeted != null ? retweeted.getId() : -1;
    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 ? retweet_user.getProfileImageUrlHttps() : null;

    final Status quoted = orig.getQuotedStatus();
    final User quote_user = quoted != null ? orig.getUser() : null;
    is_quote = orig.isQuote();
    quote_id = quoted != null ? quoted.getId() : -1;
    quote_text_html = TwitterContentUtils.formatStatusText(orig);
    quote_text_plain = orig.getText();
    quote_text_unescaped = HtmlEscapeHelper.toPlainText(quote_text_html);
    quote_timestamp = orig.getCreatedAt().getTime();
    quote_source = orig.getSource();

    quoted_by_user_id = quote_user != null ? quote_user.getId() : -1;
    quoted_by_user_name = quote_user != null ? quote_user.getName() : null;
    quoted_by_user_screen_name = quote_user != null ? quote_user.getScreenName() : null;
    quoted_by_user_profile_image = quote_user != null ? quote_user.getProfileImageUrlHttps() : null;
    quoted_by_user_is_protected = quote_user != null && quote_user.isProtected();
    quoted_by_user_is_verified = quote_user != null && quote_user.isVerified();

    final Status status;
    if (quoted != null) {
        status = quoted;
    } else if (retweeted != null) {
        status = retweeted;
    } else {
        status = orig;
    }
    final User user = status.getUser();
    user_id = user.getId();
    user_name = user.getName();
    user_screen_name = user.getScreenName();
    user_profile_image_url = user.getProfileImageUrlHttps();
    user_is_protected = user.isProtected();
    user_is_verified = user.isVerified();
    user_is_following = user.isFollowing();
    text_html = TwitterContentUtils.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 = TwitterContentUtils.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 = ParcelableLocation.fromGeoLocation(status.getGeoLocation());
    is_favorite = status.isFavorited();
    text_unescaped = HtmlEscapeHelper.toPlainText(text_html);
    my_retweet_id = retweeted_by_id == account_id ? id : status.getCurrentUserRetweet();
    is_possibly_sensitive = status.isPossiblySensitive();
    mentions = ParcelableUserMention.fromUserMentionEntities(status.getUserMentionEntities());
    card = ParcelableCardEntity.fromCardEntity(status.getCard(), account_id);
    place_full_name = getPlaceFullName(status.getPlace());
    card_name = card != null ? card.name : null;
}

From source file:org.getlantern.firetweet.util.ContentValuesCreator.java

License:Open Source License

public static ContentValues createStatus(final Status orig, final long accountId) {
    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());
    final Status status;
    if (orig.isRetweet()) {
        final Status retweetedStatus = orig.getRetweetedStatus();
        final User retweetUser = orig.getUser();
        final long retweetedById = retweetUser.getId();
        values.put(Statuses.RETWEET_ID, retweetedStatus.getId());
        values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime());
        values.put(Statuses.RETWEETED_BY_USER_ID, retweetedById);
        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, (retweetUser.getProfileImageUrlHttps()));
        values.put(Statuses.IS_RETWEET, true);
        if (retweetedById == accountId) {
            values.put(Statuses.MY_RETWEET_ID, orig.getId());
        } else {// w  ww .  ja v a2s .  com
            values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
        }
        status = retweetedStatus;
    } else if (orig.isQuote()) {
        final Status quotedStatus = orig.getQuotedStatus();
        final User quoteUser = orig.getUser();
        final long quotedById = quoteUser.getId();
        values.put(Statuses.QUOTE_ID, quotedStatus.getId());
        final String textHtml = TwitterContentUtils.formatStatusText(orig);
        values.put(Statuses.QUOTE_TEXT_HTML, textHtml);
        values.put(Statuses.QUOTE_TEXT_PLAIN, orig.getText());
        values.put(Statuses.QUOTE_TEXT_UNESCAPED, toPlainText(textHtml));
        values.put(Statuses.QUOTE_TIMESTAMP, orig.getCreatedAt().getTime());
        values.put(Statuses.QUOTE_SOURCE, orig.getSource());

        values.put(Statuses.QUOTED_BY_USER_ID, quotedById);
        values.put(Statuses.QUOTED_BY_USER_NAME, quoteUser.getName());
        values.put(Statuses.QUOTED_BY_USER_SCREEN_NAME, quoteUser.getScreenName());
        values.put(Statuses.QUOTED_BY_USER_PROFILE_IMAGE, quoteUser.getProfileImageUrlHttps());
        values.put(Statuses.QUOTED_BY_USER_IS_VERIFIED, quoteUser.isVerified());
        values.put(Statuses.QUOTED_BY_USER_IS_PROTECTED, quoteUser.isProtected());
        values.put(Statuses.IS_QUOTE, true);
        if (quotedById == accountId) {
            values.put(Statuses.MY_QUOTE_ID, orig.getId());
            //            } else {
            //                values.put(Statuses.MY_QUOTE_ID, orig.getCurrentUserRetweet());
        }
        status = quotedStatus;
    } else {
        values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
        status = orig;
    }
    final User user = status.getUser();
    final long userId = user.getId();
    final String profileImageUrl = (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, profileImageUrl);
    values.put(CachedUsers.IS_FOLLOWING, user.isFollowing());
    final String textHtml = TwitterContentUtils.formatStatusText(status);
    values.put(Statuses.TEXT_HTML, textHtml);
    values.put(Statuses.TEXT_PLAIN, status.getText());
    values.put(Statuses.TEXT_UNESCAPED, toPlainText(textHtml));
    values.put(Statuses.RETWEET_COUNT, status.getRetweetCount());
    values.put(Statuses.REPLY_COUNT, status.getReplyCount());
    values.put(Statuses.FAVORITE_COUNT, status.getFavoriteCount());
    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, TwitterContentUtils.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,
                ParcelableLocation.toString(location.getLatitude(), location.getLongitude()));
    }
    final Place place = status.getPlace();
    if (place != null) {
        values.put(Statuses.PLACE_FULL_NAME, place.getFullName());
    }
    values.put(Statuses.IS_FAVORITE, status.isFavorited());
    final ParcelableMedia[] media = ParcelableMedia.fromEntities(status);
    if (media != null) {
        values.put(Statuses.MEDIA_LIST, SimpleValueSerializer.toSerializedString(media));
    }
    final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status);
    if (mentions != null) {
        values.put(Statuses.MENTIONS_LIST, SimpleValueSerializer.toSerializedString(mentions));
    }
    final ParcelableCardEntity card = ParcelableCardEntity.fromCardEntity(status.getCard(), accountId);
    if (card != null) {
        values.put(Statuses.CARD_NAME, card.name);
        values.put(Statuses.CARD, JSONSerializer.toJSONObjectString(card));
    }
    return values;
}