Example usage for twitter4j GeoLocation getLongitude

List of usage examples for twitter4j GeoLocation getLongitude

Introduction

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

Prototype

public double getLongitude() 

Source Link

Document

returns the longitude of the geo location

Usage

From source file:org.nosceon.titanite.examples.TweetEventSource.java

License:Apache License

@Override
protected void onSubscribe(String id) {
    if (stream == null) {
        stream = new TwitterStreamFactory().getInstance();
        stream.addListener(new StatusAdapter() {

            @Override/*  ww  w.java  2  s  .  co  m*/
            public void onStatus(Status status) {
                GeoLocation location = status.getGeoLocation();
                if (location != null) {
                    send("{ \"lat\" : " + location.getLatitude() + ", \"lng\" : " + location.getLongitude()
                            + " }");
                }
            }

        });
        stream.filter(new FilterQuery().locations(RANGE));
    }
}

From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java

License:Open Source License

/**
 * Creates a content for the given tweet, adds it to the data set and sets
 * the author.//ww  w  .  ja v a2s.c  o  m
 * 
 * @param author
 *            Person corresponding to the twitter user which authored the
 *            tweet
 * @param tweet
 *            The tweet
 * @return The Content created from the tweet, null in error case.
 */
private Content createContentFromTweet(Person author, Status tweet) {
    if (tweet == null) {
        return null;
    }

    String tweetText = tweet.getText();
    if (tweetText == null || tweetText.isEmpty()) {
        return null;
    }
    String ident = tweet.getId() + "";

    if (this.getContentWithSourceIdent(ident) != null) {
        // status already created
        return null;
    }

    Content tweetContent = factory.createContent();
    tweetContent.setStringValue(tweetText);
    tweetContent.setName(createTitleFromTwitterText(tweetText));

    tweetContent = (Content) this.add(tweetContent, ident);

    if (tweetContent == null) {
        return null;
    }

    tweetContent.metaTag(TwitterTags.TWITTER);
    tweetContent.setCreated(tweet.getCreatedAt());

    if (author != null) {
        tweetContent.setAuthor(author);
    }

    // and tag the status
    HashtagEntity[] hashtags = tweet.getHashtagEntities();

    tagIOwithHashtags(tweetContent, hashtags);

    UserMentionEntity[] mentionedUsers = tweet.getUserMentionEntities();
    if (mentionedUsers != null && mentionedUsers.length > 0
            && source.isPropertyTrue(TwitterProperties.ADD_MENTIONED_PEOPLE_PROPERTY)) {
        for (int i = 0; i < mentionedUsers.length; i++) {
            Person mentionedPerson = getPersonForTwitterUserId(mentionedUsers[i].getId());

            if (mentionedPerson == null) {
                continue;
            }

            tweetContent.addContributor(mentionedPerson);
        }
    }

    URLEntity[] urlEntities = tweet.getURLEntities();
    if (urlEntities != null && urlEntities.length > 0
            && source.isPropertyTrue(TwitterProperties.ADD_URL_ENTITIES_PROPERTY)) {
        for (int i = 0; i < urlEntities.length; i++) {
            String url = urlEntities[i].getURL();
            if (url != null) {
                // attach url as website
                tweetContent.addWebSite(url);
            }
        }
    }

    // no more available
    //      String language = tweet.getIsoLanguageCode();
    //      if(language != null && !language.isEmpty())
    //      {
    //         // set in content
    //         tweetContent.setLocale(language);
    //         // set as meta tag
    //         tweetContent.metaTag(language);
    //      }

    // TODO check media entities
    // MediaEntity[] mediaEntities = twitterStatus.getMediaEntities();

    // add location
    GeoLocation tweetLocation = tweet.getGeoLocation();
    Place place = tweet.getPlace();

    if (tweetLocation != null || place != null) {
        Location location = factory.createLocation();
        if (place != null) {
            location.setStreet(place.getStreetAddress());
            location.setCountry(place.getCountry());
            location.setStringValue(place.getFullName());
        }
        if (tweetLocation != null) {
            location.setLatitude(tweetLocation.getLatitude() + "");
            location.setLongitude(tweetLocation.getLongitude() + "");
        }
        location = (Location) this.add(location, "tloc_" + tweet.getId());

        if (location != null) {
            location.metaTag(TwitterTags.TWITTER);
            tweetContent.extend(location);
            if (place != null) {
                location.metaTag(place.getCountryCode());
                location.metaTag(place.getPlaceType());
            }
        }
    }

    return tweetContent;
}

From source file:org.vsepml.storm.twitter.StormTwitterHashTagIdentifier.java

License:Apache License

@Override
public void execute(Tuple tuple) {
    String hashtag = (String) tuple.getValueByField("hashtag");
    if (filterHashTag(hashtag.toLowerCase())) {
        if (tuple.getValueByField("geolocation") != null) {
            GeoLocation l = (GeoLocation) tuple.getValueByField("geolocation");
            collector.emit(new Values(l.getLatitude() + "," + l.getLongitude()));
        }/*  w ww . j  a va 2 s.  c om*/
    }
}

From source file:org.wandora.application.tools.extractors.twitter.AbstractTwitterExtractor.java

License:Open Source License

public Topic reifyTweet(Status t, TopicMap tm) {
    Topic tweetTopic = null;/*from ww w  .  j a  va  2  s.  co m*/
    try {
        long tId = t.getId();
        String msg = t.getText();
        User user = t.getUser();

        if (user == null) {
            tweetTopic = reifyTweet(tId, null, msg, tm);
        }

        else {
            String userScreenName = user.getScreenName();

            tweetTopic = reifyTweet(tId, userScreenName, msg, tm);

            Topic userTopic = reifyTwitterUser(user, tm);

            if (tweetTopic != null && userTopic != null) {
                Association a = tm.createAssociation(getTwitterFromUserType(tm));
                a.addPlayer(tweetTopic, getTweetType(tm));
                a.addPlayer(userTopic, getTwitterUserType(tm));
            }
        }

        /*
        String toUser = t.getToUser();
        if(toUser != null) {
        long toUid = t.getToUserId();       
        Topic toUserTopic = reifyTwitterUser(toUser, toUid, tm);
        if(tweetTopic != null && toUserTopic != null) {
            Association a = tm.createAssociation(getTwitterToUserType(tm));
            a.addPlayer(tweetTopic, getTweetType(tm));
            a.addPlayer(toUserTopic, getTwitterUserType(tm));
        }
        }
        */

        Date d = t.getCreatedAt();
        if (tweetTopic != null && d != null) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = df.format(d);
            tweetTopic.setData(getTweetDateType(tm), TMBox.getLangTopic(tweetTopic, DEFAULT_LANG), dateStr);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            dateStr = sdf.format(d);
            Topic dateTopic = ExtractHelper.getOrCreateTopic(DATE_SI_BODY + dateStr, dateStr,
                    getTweetDateType(tm), tm);
            if (dateTopic != null) {
                Association a = tm.createAssociation(getTweetDateType(tm));
                a.addPlayer(tweetTopic, getTweetType(tm));
                a.addPlayer(dateTopic, getTweetDateType(tm));
            }
        }

        /*
        String l = t.getIsoLanguageCode();
        if(l != null) {
        Topic tweetLangTopic = TMBox.getLangTopic(tweetTopic, l);
        if(tweetLangTopic != null) {
            Association a = tm.createAssociation(getTweetLangType(tm));
            a.addPlayer(tweetTopic, getTweetType(tm));
            a.addPlayer(tweetLangTopic, getTweetLangType(tm));
        }
        }
        */

        GeoLocation geo = t.getGeoLocation();
        if (geo != null) {
            double lat = geo.getLatitude();
            double lon = geo.getLongitude();
            String geoLocStr = lat + "," + lon;
            tweetTopic.setData(getTweetGeoLocationType(tm), TMBox.getLangTopic(tweetTopic, DEFAULT_LANG),
                    geoLocStr);
        }

        HashtagEntity[] entities = t.getHashtagEntities();
        if (entities != null && entities.length > 0) {
            for (int i = 0; i < entities.length; i++) {
                Topic entityTopic = reifyHashtagEntity(entities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getHashtagType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getHashtagType(tm));
                }
            }
        }

        MediaEntity[] mediaEntities = t.getMediaEntities();
        if (mediaEntities != null && mediaEntities.length > 0) {
            for (int i = 0; i < mediaEntities.length; i++) {
                Topic entityTopic = reifyMediaEntity(mediaEntities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getMediaEntityType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getMediaEntityType(tm));
                }
            }
        }

        URLEntity[] urlEntities = t.getURLEntities();
        if (urlEntities != null && urlEntities.length > 0) {
            for (int i = 0; i < urlEntities.length; i++) {
                Topic entityTopic = reifyUrlEntity(urlEntities[i], tm);
                if (entityTopic != null) {
                    Association a = tm.createAssociation(getURLEntityType(tm));
                    a.addPlayer(tweetTopic, getTweetType(tm));
                    a.addPlayer(entityTopic, getURLEntityType(tm));
                }
            }
        }
    } catch (Exception e) {
        log(e);
    }
    return tweetTopic;
}

From source file:org.xmlsh.twitter.util.TwitterWriter.java

License:BSD License

private void write(String localName, GeoLocation geoLocation) throws XMLStreamException {
    if (geoLocation != null) {
        startElement(localName);// ww w .j a v a  2s . co m
        attribute("latitude", geoLocation.getLatitude());
        attribute("longitude", geoLocation.getLongitude());
        endElement();
    }

}

From source file:tweetmining.MiningFunctions.java

/**
 * This method creates an instance of Miningfunctions based on your TwitterApss credentials.
 * You should as well check filepaths to put yours.
 * //from   w ww .  j a  va  2  s.  c  o  m
 * @throws FileNotFoundException 
 */

public MiningFunctions() throws FileNotFoundException, IOException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);

    tf = new TwitterFactory(configurationBuilder.build());

    twitter = tf.getInstance();

    File f = new File(fichero1);
    File f2 = new File(fichero2);
    File f3 = new File(fichero3);
    if (!f.exists())
        f.createNewFile();
    if (!f2.exists())
        f2.createNewFile();
    if (!f3.exists())
        f3.createNewFile();
    pw = new PrintWriter(new FileOutputStream(f, true));
    pw2 = new PrintWriter(new FileOutputStream(f2, true));
    pw3 = new PrintWriter(new FileOutputStream(f3, true));

    listener = new StatusListener() {
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null) {
                cont++;
                System.out.println("Loc not null----" + cont);
                GeoLocation loc = status.getGeoLocation();
                pw.println(String.valueOf(loc.getLatitude()) + ";" + String.valueOf(loc.getLongitude()) + ";"
                        + status.getUser().getName());
                System.out.println(
                        loc.getLatitude() + " " + loc.getLongitude() + " " + status.getUser().getName());
            }
            pw2.println(status.getUser().getName() + "--->" + status.getText());
            try {
                CloseWriteAndOpen();
            } catch (FileNotFoundException ex) {
                java.util.logging.Logger.getLogger(MiningFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };
    configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from a particular twitter user.
 * @param user String which has the name of a Twitter user without @ 
 *///  w  ww .j  a  va  2 s .  c  o m
public void MineFromUser(String user) {
    int pageno = 1;
    List<Status> statuses = new ArrayList();

    while (true) {

        try {

            int size = statuses.size();
            Paging page = new Paging(pageno++, 100);
            statuses.addAll(twitter.getUserTimeline(user, page));
            if (statuses.size() == size)
                break;
        } catch (TwitterException e) {

            e.printStackTrace();
        }
    }

    System.out.println(statuses.size());

    for (Status st : statuses) {
        GeoLocation loc = st.getGeoLocation();
        if (loc != null) {
            System.out.println("Loc not null");
            Double lat = loc.getLatitude();
            Double lon = loc.getLongitude();
            pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
        }
        pw2.println(st.getUser().getName() + "-----" + st.getText());
    }

    pw.close();
    pw2.close();
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from youw twitter account based on the query string that you pass by
 * parameters./*from   w  w  w. j  av  a 2s .c  om*/
 * @param query Query you want to place.
 * @throws FileNotFoundException
 * @throws TwitterException 
 */
public void MineFromQuery(String query) throws FileNotFoundException, TwitterException {
    Query q = new Query(query);
    QueryResult r;
    q.count(100);

    do {
        r = twitter.search(q);
        List<Status> statuses = r.getTweets();
        for (Status st : statuses) {
            GeoLocation loc = st.getGeoLocation();
            if (loc != null) {
                System.out.println("Loc not null");
                Double lat = loc.getLatitude();
                Double lon = loc.getLongitude();
                pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
            }
        }
        q = r.nextQuery();
    } while (r.hasNext());
}

From source file:twittersentimentanalysis.TwitterSentimentAnalysis.java

private static Tweet getTweetObject(Status status) {
    Tweet tweet = new Tweet();
    int sentimentScore = StanfordCoreNLPTool.findSentiment(status.getText());
    if (sentimentScore != -1) {
        tweet.setDateTime(status.getCreatedAt());
        tweet.setTweetText(status.getText());
        tweet.setUsername(status.getUser().getScreenName());
        tweet.setSentimentScore(sentimentScore);
        GeoLocation geoLocation = status.getGeoLocation();
        if (geoLocation != null) {
            tweet.setLongitude(geoLocation.getLongitude() + "");
            tweet.setLatitude(geoLocation.getLatitude() + "");
        } else {//w  w w  .ja v  a  2  s.  c o m
            tweet.setLongitude(null);//
            tweet.setLatitude(null);//
        }
        Place place = status.getPlace();
        if (place != null) {
            tweet.setCountry(place.getCountry());
            tweet.setPlace(place.getFullName());
        } else {
            tweet.setCountry(null);//
            tweet.setPlace(null);//
        }
    } else
        tweet = null;
    return tweet;
}

From source file:uk.ac.susx.tag.method51.twitter.Tweet.java

License:Apache License

public Tweet(Status status) {
    this();//from w ww.j  a va  2 s. co  m
    created = status.getCreatedAt();
    id = status.getId();
    text = status.getText();

    inReplyToStatusId = status.getInReplyToStatusId();
    inReplyToUserId = status.getInReplyToUserId();

    originalText = null;
    retweetId = -1;
    isTruncated = status.isTruncated();
    isRetweet = status.isRetweet();
    Status entities = status;
    if (isRetweet) {
        Status origTweet = status.getRetweetedStatus();
        entities = origTweet;
        retweetId = origTweet.getId();
        originalText = text;
        text = origTweet.getText();
    }

    StringBuilder sb = new StringBuilder();

    for (HashtagEntity e : entities.getHashtagEntities()) {
        sb.append(e.getText());
        sb.append(" ");
    }
    hashtags = sb.toString();
    sb = new StringBuilder();

    for (UserMentionEntity e : entities.getUserMentionEntities()) {
        sb.append(e.getScreenName());
        sb.append(" ");
    }
    mentions = sb.toString();
    sb = new StringBuilder();

    for (URLEntity e : entities.getURLEntities()) {
        //String url = e.getURL();
        String url = e.getExpandedURL();
        if (url == null) {
            url = e.getURL();
            if (url != null) {
                sb.append(url);
            }

        } else {
            sb.append(url);
        }
        sb.append(" ");
    }
    urls = sb.toString();
    sb = new StringBuilder();

    //seems to be null if no entries
    MediaEntity[] mediaEntities = entities.getMediaEntities();
    if (mediaEntities != null) {
        for (MediaEntity e : mediaEntities) {
            String url = e.getMediaURL();
            sb.append(url);
            sb.append(" ");
        }
        mediaUrls = sb.toString();
    } else {
        mediaUrls = "";
    }

    received = new Date();

    source = status.getSource();
    GeoLocation geoLoc = status.getGeoLocation();
    Place place = status.getPlace();

    if (geoLoc != null) {

        geoLong = geoLoc.getLongitude();
        geoLat = geoLoc.getLatitude();
    } else if (place != null && place.getBoundingBoxCoordinates() != null
            && place.getBoundingBoxCoordinates().length > 0) {

        GeoLocation[] locs = place.getBoundingBoxCoordinates()[0];

        double avgLat = 0;
        double avgLon = 0;

        for (GeoLocation loc : locs) {

            avgLat += loc.getLatitude();
            avgLon += loc.getLongitude();
        }

        avgLat /= locs.length;
        avgLon /= locs.length;

        geoLat = avgLat;
        geoLong = avgLon;
    } else {

        geoLong = null;
        geoLat = null;
    }

    twitter4j.User user = status.getUser();

    if (user != null) {
        userId = user.getId();
        location = user.getLocation();
        screenName = user.getScreenName();
        following = user.getFriendsCount();
        name = user.getName();
        lang = user.getLang();
        timezone = user.getTimeZone();
        userCreated = user.getCreatedAt();
        followers = user.getFollowersCount();
        statusCount = user.getStatusesCount();
        description = user.getDescription();
        url = user.getURL();
        utcOffset = user.getUtcOffset();
        favouritesCount = user.getFavouritesCount();

        this.user = new User(user);
    }
}