Example usage for twitter4j Status getGeoLocation

List of usage examples for twitter4j Status getGeoLocation

Introduction

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

Prototype

GeoLocation getGeoLocation();

Source Link

Document

Returns The location that this tweet refers to if available.

Usage

From source file:au.net.moon.tUtils.twitterFields.java

License:Open Source License

/**
 * Get a <CODE>HashMap</CODE> of tweet fields by parsing a twitter4j Status
 * //from   ww w  .  j  a  v  a 2 s .co m
 * @param status
 *            the twitter4j Status object
 * @return the tweet fields as name, value pairs in a <CODE>HashMap</CODE>.
 */
public static HashMap<String, String> parseStatusObj(Status status) {
    HashMap<String, String> splitFields = new HashMap<String, String>();

    splitFields.put("createdAt", status.getCreatedAt().toString());
    splitFields.put("id", Long.toString(status.getId()));
    splitFields.put("text", status.getText());
    splitFields.put("source", status.getSource());
    splitFields.put("isTruncated", status.isTruncated() ? "1" : "0");
    splitFields.put("inReplyToStatusId", Long.toString(status.getInReplyToStatusId()));
    splitFields.put("inReplyToUserId", Long.toString(status.getInReplyToUserId()));
    splitFields.put("isFavorited", status.isFavorited() ? "1" : "0");
    splitFields.put("inReplyToScreenName", status.getInReplyToScreenName());
    if (status.getGeoLocation() != null) {
        splitFields.put("geoLocation", status.getGeoLocation().toString());
    } else {
        splitFields.put("geoLocation", "");
    }
    if (status.getPlace() != null) {
        splitFields.put("place", status.getPlace().toString());
    } else {
        splitFields.put("place", "");
    }
    splitFields.put("retweetCount", Long.toString(status.getRetweetCount()));
    splitFields.put("wasRetweetedByMe", status.isRetweetedByMe() ? "1" : "0");
    String contributors = "";
    if (status.getContributors() != null) {
        long[] tempContributors = status.getContributors();
        for (int i = 0; i < tempContributors.length; i++) {
            contributors += Long.toString(tempContributors[i]);
            if (i != tempContributors.length - 1) {
                contributors += ", ";
            }
        }
    }
    splitFields.put("contributors", contributors);
    splitFields.put("annotations", "");
    if (status.getRetweetedStatus() != null) {
        splitFields.put("retweetedStatus", "1");
    } else {
        splitFields.put("retweetedStatus", "0");
    }
    splitFields.put("userMentionEntities", status.getUserMentionEntities().toString());
    splitFields.put("urlEntities", status.getURLEntities().toString());
    splitFields.put("hashtagEntities", status.getHashtagEntities().toString());
    splitFields.put("user", status.getUser().toString());
    return splitFields;
}

From source file:br.com.porcelli.hornetq.integration.twitter.support.TweetMessageConverterSupport.java

License:Apache License

public static ServerMessage buildMessage(final String queueName, final Status status) {
    final ServerMessage msg = new ServerMessageImpl(status.getId(),
            InternalTwitterConstants.INITIAL_MESSAGE_BUFFER_SIZE);
    msg.setAddress(new SimpleString(queueName));
    msg.setDurable(true);// ww  w  .  j a va2s.c o  m

    msg.putStringProperty(TwitterConstants.KEY_MSG_TYPE, MessageType.TWEET.toString());
    msg.putStringProperty(TwitterConstants.KEY_CREATED_AT, read(status.getCreatedAt()));
    msg.putStringProperty(TwitterConstants.KEY_ID, read(status.getId()));

    msg.putStringProperty(TwitterConstants.KEY_TEXT, read(status.getText()));
    msg.putStringProperty(TwitterConstants.KEY_SOURCE, read(status.getSource()));
    msg.putStringProperty(TwitterConstants.KEY_TRUNCATED, read(status.isTruncated()));
    msg.putStringProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID, read(status.getInReplyToStatusId()));
    msg.putStringProperty(TwitterConstants.KEY_IN_REPLY_TO_USER_ID, read(status.getInReplyToUserId()));
    msg.putStringProperty(TwitterConstants.KEY_IN_REPLY_TO_SCREEN_NAME, read(status.getInReplyToScreenName()));

    msg.putStringProperty(TwitterConstants.KEY_RETWEET, read(status.isRetweet()));
    msg.putStringProperty(TwitterConstants.KEY_FAVORITED, read(status.isFavorited()));

    msg.putStringProperty(TwitterConstants.KEY_ENTITIES_URLS_JSON, read(status.getURLEntities()));
    msg.putStringProperty(TwitterConstants.KEY_ENTITIES_HASHTAGS_JSON, read(status.getHashtagEntities()));
    msg.putStringProperty(TwitterConstants.KEY_ENTITIES_MENTIONS_JSON, read(status.getUserMentionEntities()));

    msg.putStringProperty(TwitterConstants.KEY_CONTRIBUTORS_JSON, read(status.getContributors()));

    if (status.getUser() != null) {
        buildUserData("", status.getUser(), msg);
    }

    GeoLocation gl;
    if ((gl = status.getGeoLocation()) != null) {
        msg.putStringProperty(TwitterConstants.KEY_GEO_LATITUDE, read(gl.getLatitude()));
        msg.putStringProperty(TwitterConstants.KEY_GEO_LONGITUDE, read(gl.getLongitude()));
    }

    Place place;
    if ((place = status.getPlace()) != null) {
        msg.putStringProperty(TwitterConstants.KEY_PLACE_ID, read(place.getId()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_URL, read(place.getURL()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_NAME, read(place.getName()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_FULL_NAME, read(place.getFullName()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_COUNTRY_CODE, read(place.getCountryCode()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_COUNTRY, read(place.getCountry()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_STREET_ADDRESS, read(place.getStreetAddress()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_TYPE, read(place.getPlaceType()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_GEO_TYPE, read(place.getGeometryType()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_BOUNDING_BOX_TYPE, read(place.getBoundingBoxType()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_BOUNDING_BOX_COORDINATES_JSON,
                read(place.getBoundingBoxCoordinates().toString()));
        msg.putStringProperty(TwitterConstants.KEY_PLACE_BOUNDING_BOX_GEOMETRY_COORDINATES_JSON,
                read(place.getGeometryCoordinates().toString()));
    }

    msg.putStringProperty(TwitterConstants.KEY_RAW_JSON, status.toString());

    return msg;
}

From source file:br.unisal.twitter.bean.TwitterBean.java

public void postingToTwitter() {
    try {/*from   w ww  . java 2s.  c  om*/
        TwitterFactory TwitterFactory = new TwitterFactory();
        Twitter twitter = TwitterFactory.getSingleton();

        String message = getTwitt();
        Status status = twitter.updateStatus(message);

        /*String s = "status.toString() = " + status.toString()
         + "status.getInReplyToScreenName() = " + status.getInReplyToScreenName()
         + "status.getSource() = " + status.getSource()
         + "status.getText() = " + status.getText()
         + "status.getContributors() = " + Arrays.toString(status.getContributors())
         + "status.getCreatedAt() = " + status.getCreatedAt()
         + "status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId()
         + "status.getGeoLocation() = " + status.getGeoLocation()
         + "status.getId() = " + status.getId()
         + "status.getInReplyToStatusId() = " + status.getInReplyToStatusId()
         + "status.getInReplyToUserId() = " + status.getInReplyToUserId()
         + "status.getPlace() = " + status.getPlace()
         + "status.getRetweetCount() = " + status.getRetweetCount()
         + "status.getRetweetedStatus() = " + status.getRetweetedStatus()
         + "status.getUser() = " + status.getUser()
         + "status.getAccessLevel() = " + status.getAccessLevel()
         + "status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities())
         + "status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities())
         + "status.getURLEntities() = " + Arrays.toString(status.getURLEntities())
         + "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities());*/
        String s = "status.getId() = " + status.getId() + "\nstatus.getUser() = " + status.getUser().getName()
                + " - " + status.getUser().getScreenName() + "\nstatus.getGeoLocation() = "
                + status.getGeoLocation() + "\nstatus.getText() = " + status.getText();
        setTwittsResult(s);
        this.getUiMsg().setSubmittedValue("");
        this.getUiResultMsg().setSubmittedValue(getTwittsResult());
    } catch (TwitterException ex) {
        LOG.error("Erro no postingToTwitter() - " + ex.toString());
    }
}

From source file:br.unisal.twitter.bean.TwitterBean.java

public void consultarTweets() {
    TwitterFactory TwitterFactory = new TwitterFactory();
    Twitter twitter = TwitterFactory.getSingleton();
    List<Status> tweets = new ArrayList<>();
    Query query = new Query(getTwittQuery());
    try {//from   w  w w  . jav a  2s .c  o m
        QueryResult result = twitter.search(query);
        tweets.addAll(result.getTweets());
        StringBuilder builder = new StringBuilder();
        double lon = 0;
        double lat = 0;
        for (Status s : tweets) {
            if ((s.getGeoLocation() != null)) {
                lon = s.getGeoLocation().getLongitude();
                lat = s.getGeoLocation().getLatitude();
            }
            Tweet t = new Tweet(s.getUser().getName(), s.getUser().getLocation(), s.getText(), s.getCreatedAt(),
                    lat, lon);
            dao.insert(t);
            builder.append(t.toString());
        }
        this.getUiResultQuery().setSubmittedValue(builder.toString());
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
}

From source file:cats.twitter.collect.Collect.java

@Override
public boolean runCollect() {

    dateEnd = Calendar.getInstance();
    dateEnd.add(Calendar.DAY_OF_YEAR, duree);
    cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);//from  ww  w. j  a va2s.  c  om
    cb.setOAuthConsumerKey(user.getConsumerKey());
    System.out.println("CONSUMER KEY " + user.getConsumerKey());
    cb.setOAuthConsumerSecret(user.getConsumerSecret());
    System.out.printf("CONSUMER SECRET " + user.getConsumerSecret());
    cb.setOAuthAccessToken(user.getToken());
    System.out.printf("TOKEN" + user.getToken());
    cb.setOAuthAccessTokenSecret(user.getTokenSecret());
    System.out.printf("TOKEN SECRET " + user.getTokenSecret());

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

    setStatus(State.WAITING_FOR_CONNECTION);

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            if (!corpus.getState().equals(State.INPROGRESS)) {
                setStatus(State.INPROGRESS);
            }
            if (status.getCreatedAt().after(dateEnd.getTime())) {
                shutdown();

            } else if (corpus.getLang() == null || corpus.getLang().equals(status.getLang())) {
                Tweet t = new Tweet();
                t.setText(status.getText().replace("\r", "\n"));
                t.setAuthor(status.getUser().getId());
                t.setId(status.getId());
                t.setDate(status.getCreatedAt());
                if (status.getGeoLocation() != null)
                    t.setLocation(status.getGeoLocation().toString());
                t.setName(status.getUser().getName());
                t.setDescriptionAuthor(status.getUser().getDescription());
                t.setLang(status.getLang());
                t.setCorpus(corpus);
                if (tweetRepository != null)
                    tweetRepository.save(t);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
            System.out.println(sdn);
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            corpus.setLimitationNotice(i);
            corpus = corpusRepository.save(corpus);

        }

        @Override
        public void onScrubGeo(long l, long l1) {
            System.out.println(l + "" + l1);
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println(sw);
        }

        @Override
        public void onException(Exception excptn) {
            corpus.setErrorMessage(excptn.getMessage());
            setStatus(State.ERROR);
            excptn.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.filter(filter);

    return false;
}

From source file:co.cask.cdap.template.etl.realtime.source.TwitterSource.java

License:Apache License

private StructuredRecord convertTweet(Status tweet) {
    StructuredRecord.Builder recordBuilder = StructuredRecord.builder(this.schema);
    recordBuilder.set(ID, tweet.getId());
    recordBuilder.set(MSG, tweet.getText());
    recordBuilder.set(LANG, tweet.getLang());
    Date tweetDate = tweet.getCreatedAt();
    if (tweetDate != null) {
        recordBuilder.set(TIME, tweetDate.getTime());
    }/* w w  w  .  j  av  a  2  s.c o  m*/
    recordBuilder.set(FAVC, tweet.getFavoriteCount());
    recordBuilder.set(RTC, tweet.getRetweetCount());
    recordBuilder.set(SRC, tweet.getSource());
    if (tweet.getGeoLocation() != null) {
        recordBuilder.set(GLAT, tweet.getGeoLocation().getLatitude());
        recordBuilder.set(GLNG, tweet.getGeoLocation().getLongitude());
    }
    recordBuilder.set(ISRT, tweet.isRetweet());
    return recordBuilder.build();
}

From source file:co.cask.hydrator.plugin.realtime.source.TwitterSource.java

License:Apache License

private StructuredRecord convertTweet(Status tweet) {
    StructuredRecord.Builder recordBuilder = StructuredRecord.builder(SCHEMA);
    recordBuilder.set(ID, tweet.getId());
    recordBuilder.set(MSG, tweet.getText());
    recordBuilder.set(LANG, tweet.getLang());
    Date tweetDate = tweet.getCreatedAt();
    if (tweetDate != null) {
        recordBuilder.set(TIME, tweetDate.getTime());
    }//from  ww  w  . j  ava  2  s.  co  m
    recordBuilder.set(FAVC, tweet.getFavoriteCount());
    recordBuilder.set(RTC, tweet.getRetweetCount());
    recordBuilder.set(SRC, tweet.getSource());
    if (tweet.getGeoLocation() != null) {
        recordBuilder.set(GLAT, tweet.getGeoLocation().getLatitude());
        recordBuilder.set(GLNG, tweet.getGeoLocation().getLongitude());
    }
    recordBuilder.set(ISRT, tweet.isRetweet());
    return recordBuilder.build();
}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> search(String queryExpression, int maxResults) {
    Query query = new Query(queryExpression);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    query = query.lang("pt");
    List<Status> tweets = new ArrayList<>();
    boolean finish = false;
    while ((tweets.size() < numberOfTweets) && !finish) {
        System.out.print(".");
        if (numberOfTweets - tweets.size() > 100) {//100) {
            query.setCount(100);//100);
        } else {// w w w.jav  a2  s  .  c  o m
            query.setCount(numberOfTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            List<Status> resultList = result.getTweets();
            if (resultList == null || resultList.isEmpty()) {
                finish = true;
                System.out.println("no foram encontrados mais tweets");
            } else {
                tweets.addAll(resultList);
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        query.setMaxId(lastID - 1);
    }
    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    for (Status status : tweets) {
        if (!status.getText().startsWith("RT")) {
            TwitterUser user;
            user = new TwitterUser().addID(status.getUser().getId()).addName(status.getUser().getName())
                    .addLocation(status.getUser().getLocation()).addDateSignin(status.getUser().getCreatedAt())
                    .addCountTweets(status.getUser().getStatusesCount())
                    .addCountFavorites(status.getUser().getFavouritesCount())
                    .addCountFriends(status.getUser().getFriendsCount())
                    .addCountFollowers(status.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(status.getText()).addID(status.getId())
                    .addDate(status.getCreatedAt())
                    .addLatitude(status.getGeoLocation() != null ? status.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(status.getGeoLocation() != null ? status.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        }
    }
    return out;
}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> userSearchData(String userName, int maxResults) {

    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    Paging paging = new Paging(1, 180);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    ArrayList<Status> status = new ArrayList<>();
    while (status.size() < numberOfTweets) {
        if (numberOfTweets - status.size() > 180) {//100) {
            paging.setCount(180);//100);
        } else {/*from  w  w  w . jav a 2  s  .  com*/
            paging.setCount(numberOfTweets - status.size());
        }
        try {
            List<Status> timeLine = twitter.getUserTimeline(userName, paging);
            status.addAll(timeLine);
            for (Status t : status) {
                if (t.getId() < lastID) {
                    lastID = t.getId();
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        paging.setMaxId(lastID - 1);
    }

    //armazenar os atributos interessantes a analise dos tweets
    int qtdretweet = 0;
    for (Status sta : status) {
        String text = sta.getText();
        if (!sta.isRetweet() && !sta.isRetweeted() && !text.startsWith("RT")) { //&& !TweetMediaDetect.detect(text)) {
            TwitterUser user;
            user = new TwitterUser().addID(sta.getUser().getId()).addName(sta.getUser().getName())
                    .addLocation(sta.getUser().getLocation()).addDateSignin(sta.getUser().getCreatedAt())
                    .addCountTweets(sta.getUser().getStatusesCount())
                    .addCountFavorites(sta.getUser().getFavouritesCount())
                    .addCountFriends(sta.getUser().getFriendsCount())
                    .addCountFollowers(sta.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(sta.getText()).addID(sta.getId())
                    .addDate(sta.getCreatedAt())
                    .addLatitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        } else {
            qtdretweet++;
        }
    }

    return out;
}

From source file:com.appspot.bitlyminous.handler.twitter.NearByHandler.java

License:Apache License

@Override
public StatusUpdate execute(Status tweet) {
    GeoLocation geoLocation = tweet.getGeoLocation();
    String text = getMentionText(tweet);
    if (geoLocation == null) {
        StatusUpdate reply = new StatusUpdate(
                ApplicationResources.getLocalizedString("com.appspot.bitlyminous.message.noLocation",
                        new String[] { "@" + tweet.getUser().getScreenName() }));
        reply.setInReplyToStatusId(tweet.getId());
        return reply;
    } else {/*from  ww w  .j  a  v  a2  s .co  m*/
        try {
            GeoQuery query = new GeoQuery(geoLocation);
            List<Tip> nearbyTips = getFoursquareGateway()
                    .getNearbyTips(new com.appspot.bitlyminous.entity.GeoLocation(geoLocation.getLatitude(),
                            geoLocation.getLongitude()), 1);
            String status = buildTipsStatus(nearbyTips);

            if (nearbyTips.isEmpty()) {
                List<Venue> nearbyVenues = new ArrayList<Venue>();
                if (text != null) {
                    nearbyVenues = getFoursquareGateway().getNearbyVenues(
                            new com.appspot.bitlyminous.entity.GeoLocation(geoLocation.getLatitude(),
                                    geoLocation.getLongitude()),
                            text, 1);
                }
                status = status + buildVenuesStatus(nearbyVenues);
                if (nearbyVenues.isEmpty()) {
                    List<Place> nearbyPlaces = getTwitterClient().getNearbyPlaces(query);
                    status = status + buildPlacesStatus(nearbyPlaces);
                }

            }
            status = "@" + tweet.getUser().getScreenName() + " " + status;
            StatusUpdate reply = new StatusUpdate(status);
            reply.setInReplyToStatusId(tweet.getId());
            return reply;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error while getting nearby places", e);
        }
        return null;
    }
}