Example usage for twitter4j Query setGeoCode

List of usage examples for twitter4j Query setGeoCode

Introduction

In this page you can find the example usage for twitter4j Query setGeoCode.

Prototype

public void setGeoCode(GeoLocation location, double radius, Unit unit) 

Source Link

Document

returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile

Usage

From source file:ch.schrimpf.core.TwitterCrawler.java

License:Open Source License

/**
 * @param queryString describes keywords and filters
 * @return an initialized Query/*from  w w  w . j  a  v a 2s.  co  m*/
 */
private Query initQuery(String queryString) {
    Query query = new Query(queryString);
    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("easyTwitterCrawler.properties"));
        query.setCount(Integer.parseInt(prop.getProperty("queryLimit")));
        query.setLocale(prop.getProperty("locale"));
        query.setLang(prop.getProperty("lang"));
        GeoLocation location = new GeoLocation(Double.parseDouble(prop.getProperty("latitude")),
                Double.parseDouble(prop.getProperty("longitude")));
        double radius = Double.parseDouble(prop.getProperty("radius"));
        query.setGeoCode(location, radius, Query.KILOMETERS);
    } catch (IOException e) {
        // Properties could not be load
        query.setCount(DEFAULT_QUERY_LIMIT);
        query.setLocale(DEFAULT_LOCALE);
        query.setLang(DEFAULT_LANG);
        query.setGeoCode(DEFAULT_GEO_LOCATION, DEFAULT_RADIUS, Query.KILOMETERS);
    }
    return query;
}

From source file:com.fuzuapp.model.resultados.TwitterAdapter.java

@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {

    List<Resultado> resultados = new ArrayList();
    try {/*from  w w  w. ja v  a 2s  .c  om*/
        Query query = new Query("");
        GeoLocation geo = new GeoLocation(ponto.getLatitude(), ponto.getLongitude());
        query.setGeoCode(geo, raio, Query.KILOMETERS);
        query.resultType(Query.RECENT);
        query.setCount(20);
        QueryResult result = twitter.search(query);

        for (Status status : result.getTweets()) {
            Resultado r = new Resultado();

            r.setDescricao(status.getText());
            r.setUrl("http://twitter.com/statuses/" + String.valueOf(status.getId()));
            r.setNomeUsuario(status.getUser().getName());
            r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(status.getCreatedAt()));
            r.setFotoUrl(status.getUser().getProfileImageURL());
            //r.setLocal(new GeoPoint(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
            r.setTipo(Resultado.TEXTO);

            resultados.add(r);

        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterAdapter.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultados;
}

From source file:com.javielinux.database.EntitySearch.java

License:Apache License

public Query getQuery(Context cnt) {
    String q = this.getString("words_and");

    if (!this.getString("words_or").equals("")) {
        q += Utils.getQuotedText(this.getString("words_or"), "OR ", false);
    }/*from   w  ww  .  j av  a 2s  .  com*/

    if (!this.getString("words_not").equals("")) {
        q += Utils.getQuotedText(this.getString("words_not"), "-", true);
    }

    if (!this.getString("from_user").equals("")) {
        q += " from:" + this.getString("from_user");
    }

    if (!this.getString("to_user").equals("")) {
        q += " to:" + this.getString("to_user");
    }

    if (!this.getString("source").equals("")) {
        q += " source:" + this.getString("source");
    }

    if (this.getInt("attitude") == 1)
        q += " :)";
    if (this.getInt("attitude") == 2)
        q += " :(";

    String modLinks = "filter:links";
    String websVideos = "twitvid OR youtube OR vimeo OR youtu.be";
    String webPhotos = "lightbox.com OR mytubo.net OR imgur.com OR instagr.am OR twitpic OR yfrog OR plixi OR twitgoo OR img.ly OR picplz OR lockerz";

    if (this.getInt("filter") == 1)
        q += " " + modLinks;
    if (this.getInt("filter") == 2)
        q += " " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 3)
        q += " " + websVideos + " " + modLinks;
    if (this.getInt("filter") == 4)
        q += " " + websVideos + " OR " + webPhotos + " " + modLinks;
    if (this.getInt("filter") == 5)
        q += " source:twitterfeed " + modLinks;
    if (this.getInt("filter") == 6)
        q += " ?";
    if (this.getInt("filter") == 7)
        q += " market.android.com OR androidzoom.com OR androlib.com OR appbrain.com OR bubiloop.com OR yaam.mobi OR slideme.org "
                + modLinks;

    Log.d(Utils.TAG, "Buscando: " + q);

    Query query = new Query(q);

    if (this.getInt("use_geo") == 1) {
        if (this.getInt("type_geo") == 0) { // coordenadas del mapa
            GeoLocation gl = new GeoLocation(this.getDouble("latitude"), this.getDouble("longitude"));
            String unit = Query.KILOMETERS;
            if (this.getInt("type_distance") == 0)
                unit = Query.MILES;
            query.setGeoCode(gl, this.getDouble("distance"), unit);
        }

        if (this.getInt("type_geo") == 1) { // coordenadas del gps
            Location loc = LocationUtils.getLastLocation(cnt);
            if (loc != null) {
                GeoLocation gl = new GeoLocation(loc.getLatitude(), loc.getLongitude());
                String unit = Query.KILOMETERS;
                if (this.getInt("type_distance") == 0)
                    unit = Query.MILES;
                query.setGeoCode(gl, this.getDouble("distance"), unit);
            } else {
                mErrorLastQuery = cnt.getString(R.string.no_location);
            }
        }
    }

    PreferenceManager.setDefaultValues(cnt, R.xml.preferences, false);
    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(cnt);

    int count = Integer.parseInt(preference.getString("prf_n_max_download", "60"));
    if (count <= 0)
        count = 60;

    query.setCount(count);

    String lang = "";
    if (!this.getString("lang").equals(""))
        lang = this.getString("lang");
    if (!lang.equals("all"))
        query.setLang(lang);

    // obtener desde donde quiero hacer la consulta

    if (getInt("notifications") == 1) {
        String where = "search_id = " + this.getId() + " AND favorite = 0";
        int nResult = DataFramework.getInstance().getEntityListCount("tweets", where);
        if (nResult > 0) {
            long mLastIdNotification = DataFramework.getInstance().getTopEntity("tweets", where, "date desc")
                    .getLong("tweet_id");
            query.setSinceId(mLastIdNotification);
        }
    }

    //query.setResultType(Query.POPULAR);

    return query;
}

From source file:crawling.FoundUsersBySearchGeo.java

License:Apache License

public static void main(String[] args) {

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            /* my shutdown code here */
            // Record the user status
            out.println("Final status -------------------:");
            for (Long id : discoveredUsers.keySet()) {
                out.println(id + "," + discoveredUsers.get(id));
            }//  ww  w  . j  a v  a 2 s. c  o  m
            out.close();

            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = new Date();
            date = new Date();
            System.out.println("End at: " + dateFormat.format(date));
        }
    });

    if (args.length < 5) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamGeo lati long radius unit CITY");
        System.exit(-1);
    }
    if (args.length == 6) {
        // Preload the collected user IDs
        preloadID(args[5]);
    }

    try {
        FileWriter outFile = new FileWriter("discoveredUser" + args[4] + ".txt", true);
        out = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    avgUsers = new int[histCount];

    Query query = new Query();
    query.setGeoCode(new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])),
            Double.parseDouble(args[2]), args[3]);
    // New York Metropolitan
    //query.setGeoCode(new GeoLocation(40.7, -74), 100, "km");
    // Bay Area MetroPolitan
    //query.setGeoCode(new GeoLocation(37.78, -122.4), 100, "km");
    // LA MetroPolitan
    //query.setGeoCode(new GeoLocation(34.05, -118.24), 200, "km");

    query.setCount(100);
    //query.setPage(20);

    //Twitter twitter = new TwitterFactory().getInstance();
    Twitter twitter = getOAuthTwitter();

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    //System.out.println();
    System.out.println("----------------------------------------------");
    System.out.println("Start at: " + dateFormat.format(date));

    while (true) {
        //for (int i = 1; i <= 15; i ++){
        //   query.setPage(i);
        try {
            doASearch(twitter, query);
        } catch (TwitterException te) {
            // TODO Auto-generated catch block
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());

            // back-off
            Thread.currentThread();
            try {
                Thread.sleep(60 * 1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

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

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(GeoLocation myLoc, double radius) {
    try {//from  w  w w  . java2s  . c  om
        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:dk.netarkivet.harvester.tools.TwitterDecidingScope.java

License:Open Source License

/**
 * This routine makes any necessary Twitter API calls and queues the content discovered.
 *
 * @param controller The controller for this crawl.
 *///from ww w  .  j  a  v  a  2s.c  om
@Override
public void initialize(CrawlController controller) {
    super.initialize(controller);
    twitter = (new TwitterFactory()).getInstance();
    keywords = null;
    try {
        keywords = (StringList) super.getAttribute(ATTR_KEYWORDS);
        pages = ((Integer) super.getAttribute(ATTR_PAGES)).intValue();
        geoLocations = (StringList) super.getAttribute(ATTR_GEOLOCATIONS);
        language = (String) super.getAttribute(ATTR_LANG);
        if (language == null) {
            language = "all";
        }
        resultsPerPage = (Integer) super.getAttribute(ATTR_RESULTS_PER_PAGE);
        queueLinks = (Boolean) super.getAttribute(ATTR_QUEUE_LINKS);
        queueUserStatus = (Boolean) super.getAttribute(ATTR_QUEUE_USER_STATUS);
        queueUserStatusLinks = (Boolean) super.getAttribute(ATTR_QUEUE_USER_STATUS_LINKS);
        queueKeywordLinks = (Boolean) super.getAttribute(ATTR_QUEUE_KEYWORD_LINKS);
    } catch (AttributeNotFoundException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (MBeanException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    } catch (ReflectionException e1) {
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    for (Object keyword : keywords) {
        log.info("Twitter Scope keyword: {}", keyword);
    }
    // If keywords or geoLocations is missing, add a list with a single empty string so that the main loop is
    // executed at least once.
    if (keywords == null || keywords.isEmpty()) {
        keywords = new StringList("keywords", "empty keyword list", new String[] { "" });
    }
    if (geoLocations == null || geoLocations.isEmpty()) {
        geoLocations = new StringList("geolocations", "empty geolocation list", new String[] { "" });
    }
    log.info("Twitter Scope will queue {} page(s) of results.", pages);
    // Nested loop over keywords, geo_locations and pages.
    for (Object keyword : keywords) {
        String keywordString = (String) keyword;
        for (Object geoLocation : geoLocations) {
            String urlQuery = (String) keyword;
            Query query = new Query();
            query.setRpp(resultsPerPage);
            if (language != null && !language.equals("")) {
                query.setLang(language);
                urlQuery += " lang:" + language;
                keywordString += " lang:" + language;
            }
            urlQuery = "http://twitter.com/search/" + URLEncoder.encode(urlQuery);
            if (queueKeywordLinks) {
                addSeedIfLegal(urlQuery);
            }
            for (int page = 1; page <= pages; page++) {
                query.setPage(page);
                if (!keyword.equals("")) {
                    query.setQuery(keywordString);
                }
                if (!geoLocation.equals("")) {
                    String[] locationArray = ((String) geoLocation).split(",");
                    try {
                        GeoLocation location = new GeoLocation(Double.parseDouble(locationArray[0]),
                                Double.parseDouble(locationArray[1]));
                        query.setGeoCode(location, Double.parseDouble(locationArray[2]), locationArray[3]);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    final QueryResult result = twitter.search(query);
                    List<Tweet> tweets = result.getTweets();
                    for (Tweet tweet : tweets) {
                        long id = tweet.getId();
                        String fromUser = tweet.getFromUser();
                        String tweetUrl = "http://www.twitter.com/" + fromUser + "/status/" + id;
                        addSeedIfLegal(tweetUrl);
                        tweetCount++;
                        if (queueLinks) {
                            extractEmbeddedLinks(tweet);
                        }
                        if (queueUserStatus) {
                            String statusUrl = "http://twitter.com/" + tweet.getFromUser() + "/";
                            addSeedIfLegal(statusUrl);
                            linkCount++;
                            if (queueUserStatusLinks) {
                                queueUserStatusLinks(tweet.getFromUser());
                            }
                        }
                    }
                } catch (TwitterException e1) {
                    log.error(e1.getMessage());
                }
            }
        }

    }
    System.out.println(
            TwitterDecidingScope.class + " added " + tweetCount + " tweets and " + linkCount + " other links.");
}

From source file:es.portizsan.twitrector.tasks.TweetSearchTask.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    long before = System.currentTimeMillis() - (1000 * 60 * 15);
    try {/*ww w .  j a  va  2 s.c om*/
        List<Twitrector> trl = new TwitrectorService().getTwitrectors();
        if (trl == null || trl.isEmpty()) {
            logger.log(Level.WARNING, "No Twitrectors found!!!!!");
            return;
        }
        for (Twitrector tr : trl) {
            logger.info("Searching for :" + tr.getQuery());
            String search = tr.getQuery();
            Twitter twitter = new TwitterService().getTwitterInstance();
            Query query = new Query(search);
            query.setLocale("es");
            query.setCount(100);
            if (tr.getLocation() != null) {
                GeoLocation location = new GeoLocation(tr.getLocation().getLatitude(),
                        tr.getLocation().getLongitude());
                Unit unit = Unit.valueOf(tr.getLocation().getUnit().name());
                query.setGeoCode(location, tr.getLocation().getRadius(), unit);
            }
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    if (tweet.getCreatedAt().getTime() < before)
                        continue;
                    Queue queue = QueueFactory.getQueue("default");
                    queue.add(TaskOptions.Builder.withUrl("/tasks/tweetReply")
                            .param("statusId", String.valueOf(tweet.getId()))
                            .param("message", "@" + tweet.getUser().getScreenName() + " "
                                    + String.valueOf(tr.getResponse())));

                    logger.info("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
        }
    } catch (TwitterException te) {
        logger.log(Level.WARNING, "Failed to search tweets: ", te);
    }
}

From source file:eu.smartfp7.SocialNetworkDriver.TwitterDriver.java

License:Mozilla Public License

@Override
public void SearchForTermUsingGeolocation(String queryPar, int PageSize, double latitude, double longitude,
        double radius) {
    try {/*from  ww  w. j ava  2s. c  om*/
        results = new ArrayList<TwitterPostData>();

        if (queryPar != null) {
            this.pageSize = PageSize;
            this.queryPar = queryPar;
            Query query = new Query(queryPar);
            query.setPage(pageIndex);
            query.setRpp(PageSize);
            query.setResultType(Query.RECENT);
            query.setGeoCode(new GeoLocation(latitude, longitude), radius, "km");
            QueryResult result = twitter.search(query);
            ArrayList tweets = (ArrayList) result.getTweets();
            for (int i = 0; i < tweets.size(); i++) {
                results.add(new TwitterPostData((Tweet) tweets.get(i)));
            }

        }
    } catch (TwitterException ex) {
        System.err.println("Twitter Error");
        // Logger.getLogger(TwitterSearch.class.getName()).log(Level.SEVERE,
        // null, ex);
    }

}

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

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

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

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

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

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

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

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

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

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

From source file:org.codice.ddf.catalog.twitter.source.TwitterSource.java

License:Open Source License

@Override
public SourceResponse query(QueryRequest request) throws UnsupportedQueryException {
    Twitter instance = twitterFactory.getInstance();
    try {/*from w ww . j  a  v  a 2s .  co m*/
        instance.getOAuth2Token();
    } catch (TwitterException e) {
        throw new UnsupportedQueryException("Unable to get OAuth2 token.", e);
    }
    TwitterFilterVisitor visitor = new TwitterFilterVisitor();
    request.getQuery().accept(visitor, null);
    Query query = new Query();
    query.setCount(request.getQuery().getPageSize());
    if (visitor.hasSpatial()) {
        GeoLocation geoLocation = new GeoLocation(visitor.getLatitude(), visitor.getLongitude());
        query.setGeoCode(geoLocation, visitor.getRadius(), Query.Unit.km);
    }
    if (visitor.getContextualSearch() != null) {
        query.setQuery(visitor.getContextualSearch().getSearchPhrase());
    }
    if (visitor.getTemporalSearch() != null) {
        Calendar.Builder builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getStartDate());
        Calendar calendar = builder.build();
        query.setSince(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));

        builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getEndDate());
        calendar = builder.build();
        query.setUntil(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));
    }

    QueryResult queryResult;
    try {
        queryResult = instance.search().search(query);
    } catch (TwitterException e) {
        throw new UnsupportedQueryException(e);
    }
    List<Result> resultList = new ArrayList<>(queryResult.getCount());
    resultList.addAll(queryResult.getTweets().stream().map(status -> new ResultImpl(getMetacard(status)))
            .collect(Collectors.toList()));
    return new SourceResponseImpl(request, resultList);
}