List of usage examples for twitter4j GeoLocation GeoLocation
public GeoLocation(double latitude, double longitude)
From source file:de.hoesel.dav.buv.twitter.baustelle.BaustelleTwitternDialog.java
License:Open Source License
private GeoLocation ermittleGeoLocation(Feld<StrassenSegment> segmente) { if (segmente == null || segmente.isEmpty()) { return null; }//from w ww. j av a 2 s. c o m final StrassenSegment segment = segmente.get(0); Feld<Linie> linienReferenz = segment.getKdBestehtAusLinienObjekten().getDatum().getLinienReferenz(); if (linienReferenz.isEmpty()) { return null; } final StrassenTeilSegment sts = (StrassenTeilSegment) linienReferenz.iterator().next(); final KdLinienKoordinaten.Daten koordinaten = sts.getKdLinienKoordinaten().getDatum(); AttWgs84Laenge attWgs84Laenge = koordinaten.getX().get(0); AttWgs84Breite attWgs84Breite = koordinaten.getY().get(0); return new GeoLocation(attWgs84Breite.doubleValue(), attWgs84Laenge.doubleValue()); }
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. *//* ww w.ja 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:edu.mum.cs.wap.TwitterUtil.java
public static List<Trend> getTrends(double latitude, double longitude) { try {//from w ww . j a v a2 s . c om GeoLocation gl = new GeoLocation(latitude, longitude); ResponseList<Location> locations = twitter.getClosestTrends(gl); return TwitterUtil.getPlacedTrends(locations.get(0).getWoeid()); } catch (TwitterException ex) { Logger.getLogger(TwitterUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; }
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 {/*from w w w.ja va 2 s . co m*/ 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 w w w. j a v a 2 s. co m*/ 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:geo.GetSimilarPlaces.java
License:Apache License
/** * Usage: java twitter4j.examples.geo.GetSimilarPlaces [latitude] [longitude] [place id] * * @param args message//from w ww . ja v a 2s. com */ public static void main(String[] args) { if (args.length < 3) { System.out.println( "Usage: java twitter4j.examples.geo.GetSimilarPlaces [latitude] [longitude] [name] [place id]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); GeoLocation location = new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1])); String name = args[2]; String containedWithin = null; if (args.length >= 4) { containedWithin = args[3]; } ResponseList<Place> places = twitter.getSimilarPlaces(location, name, containedWithin, null); if (places.size() == 0) { System.out.println("No location associated with the specified condition"); } else { for (Place place : places) { System.out.println("id: " + place.getId() + " name: " + place.getFullName() + " name: " + place.getFullName()); Place[] containedWithinArray = place.getContainedWithIn(); if (containedWithinArray != null && containedWithinArray.length != 0) { System.out.println(" contained within:"); for (Place containedWithinPlace : containedWithinArray) { System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName()); } } } } System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to find similar places: " + te.getMessage()); System.exit(-1); } }
From source file:geo.ReverseGeoCode.java
License:Apache License
/** * Usage: java twitter4j.examples.geo.ReverseGeoCode [latitude] [longitude] * * @param args message/*from w w w . j a va2 s .c om*/ */ public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: java twitter4j.examples.geo.ReverseGeoCode [latitude] [longitude]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); GeoQuery query = new GeoQuery( new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1]))); ResponseList<Place> places = twitter.reverseGeoCode(query); if (places.size() == 0) { System.out.println("No location associated with the specified lat/lang"); } else { for (Place place : places) { System.out.println("id: " + place.getId() + " name: " + place.getFullName()); Place[] containedWithinArray = place.getContainedWithIn(); if (containedWithinArray != null && containedWithinArray.length != 0) { System.out.println(" contained within:"); for (Place containedWithinPlace : containedWithinArray) { System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName()); } } } } System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to retrieve places: " + te.getMessage()); System.exit(-1); } }
From source file:geo.SearchPlaces.java
License:Apache License
/** * Usage: java twitter4j.examples.geo.SearchPlaces [ip address] or [latitude] [longitude] * * @param args message/*from w w w . j a v a 2 s . c o m*/ */ public static void main(String[] args) { if (args.length < 1) { System.out.println( "Usage: java twitter4j.examples.geo.SearchPlaces [ip address] or [latitude] [longitude]"); System.exit(-1); } try { Twitter twitter = new TwitterFactory().getInstance(); GeoQuery query; if (args.length == 2) { query = new GeoQuery(new GeoLocation(Double.parseDouble(args[0]), Double.parseDouble(args[1]))); } else { query = new GeoQuery(args[0]); } ResponseList<Place> places = twitter.searchPlaces(query); if (places.size() == 0) { System.out.println("No location associated with the specified IP address or lat/lang"); } else { for (Place place : places) { System.out.println("id: " + place.getId() + " name: " + place.getFullName()); Place[] containedWithinArray = place.getContainedWithIn(); if (containedWithinArray != null && containedWithinArray.length != 0) { System.out.println(" contained within:"); for (Place containedWithinPlace : containedWithinArray) { System.out.println(" id: " + containedWithinPlace.getId() + " name: " + containedWithinPlace.getFullName()); } } } } System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to retrieve places: " + te.getMessage()); System.exit(-1); } }
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);/*www . ja v a2 s .c om*/ 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.anc.lapps.datasource.twitter.TwitterDatasource.java
/** * Entry point for a Lappsgrid service./* w w w . j av a2 s . co m*/ * <p> * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container} * payload. * <p> * Errors and exceptions that occur during processing should be wrapped in a {@code Data} * object with the discriminator set to http://vocab.lappsgrid.org/ns/error * <p> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br /> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br /> * * @param input A JSON string representing a Data object * @return A JSON string containing a Data object with a Container payload. */ @Override public String execute(String input) { Data<String> data = Serializer.parse(input, Data.class); String discriminator = data.getDiscriminator(); // Return ERRORS back if (Discriminators.Uri.ERROR.equals(discriminator)) { return input; } // Generate an error if the used discriminator is wrong if (!Discriminators.Uri.GET.equals(discriminator)) { return generateError( "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator); } Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false) .build(); // Authentication using saved keys Twitter twitter = new TwitterFactory(config).getInstance(); String key = readProperty(KEY_PROPERTY); if (key == null) { return generateError("The Twitter Consumer Key property has not been set."); } String secret = readProperty(SECRET_PROPERTY); if (secret == null) { return generateError("The Twitter Consumer Secret property has not been set."); } twitter.setOAuthConsumer(key, secret); try { twitter.getOAuth2Token(); } catch (TwitterException te) { String errorData = generateError(te.getMessage()); logger.error(errorData); return errorData; } // Get query String from data payload Query query = new Query(data.getPayload()); // Set the type to Popular or Recent if specified // Results will be Mixed by default. if (data.getParameter("type") == "Popular") query.setResultType(Query.POPULAR); if (data.getParameter("type") == "Recent") query.setResultType(Query.RECENT); // Get lang string String langCode = (String) data.getParameter("lang"); // Verify the validity of the language code and add it to the query if it's valid if (validateLangCode(langCode)) query.setLang(langCode); // Get date strings String sinceString = (String) data.getParameter("since"); String untilString = (String) data.getParameter("until"); // Verify the format of the date strings and set the parameters to query if correctly given if (validateDateFormat(untilString)) query.setUntil(untilString); if (validateDateFormat(sinceString)) query.setSince(sinceString); // Get GeoLocation if (data.getParameter("address") != null) { String address = (String) data.getParameter("address"); double radius = (double) data.getParameter("radius"); if (radius <= 0) radius = 10; Query.Unit unit = Query.MILES; if (data.getParameter("unit") == "km") unit = Query.KILOMETERS; GeoLocation geoLocation; try { double[] coordinates = getGeocode(address); geoLocation = new GeoLocation(coordinates[0], coordinates[1]); } catch (Exception e) { String errorData = generateError(e.getMessage()); logger.error(errorData); return errorData; } query.geoCode(geoLocation, radius, String.valueOf(unit)); } // Get the number of tweets from count parameter, and set it to default = 15 if not specified int numberOfTweets; try { numberOfTweets = (int) data.getParameter("count"); } catch (NullPointerException e) { numberOfTweets = 15; } // Generate an ArrayList of the wanted number of tweets, and handle possible errors. // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed ArrayList<Status> allTweets; Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter); String tweetsDataDisc = tweetsData.getDiscriminator(); if (Discriminators.Uri.ERROR.equals(tweetsDataDisc)) return tweetsData.asPrettyJson(); else { allTweets = (ArrayList<Status>) tweetsData.getPayload(); } // Initialize StringBuilder to hold the final string StringBuilder builder = new StringBuilder(); // Append each Status (each tweet) to the initialized builder for (Status status : allTweets) { String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : " + status.getText() + "\n"; builder.append(single); } // Output results Container container = new Container(); container.setText(builder.toString()); Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container); return output.asPrettyJson(); }