diff --git a/src/main/java/eirb/pg203/city.java b/src/main/java/eirb/pg203/city.java new file mode 100644 index 0000000..af20548 --- /dev/null +++ b/src/main/java/eirb/pg203/city.java @@ -0,0 +1,97 @@ +package eirb.pg203; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URL; + +import org.json.JSONArray; +import org.json.JSONObject; + +import eirb.pg203.utils.Coords; + +class City { + private String cityName; + private Coords cityCoords; + + /** + * Fetch data from adresse.data.gouv.fr + * @throws IOException if the request fails + */ + private static JSONObject getDataFromName(String cityName) throws IOException { + StringBuilder result = new StringBuilder(); + URL url = URI.create( + String.format("https://api-adresse.data.gouv.fr/search/?q=%s&autocomplete=0&limit=1", + cityName + ) + ).toURL(); + + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(conn.getInputStream()))) { + for (String line; (line = reader.readLine()) != null; ) { + result.append(line); + } + } + + return new JSONObject(result.toString()); + } + + private static Coords getCoordsFromName(String cityName) throws IOException { + JSONObject data = getDataFromName(cityName); + JSONArray rawCoords = data.getJSONArray("features") + .getJSONObject(0) + .getJSONObject("geometry") + .getJSONArray("coordinates"); + + final float lon = rawCoords.getFloat(0); + final float lat = rawCoords.getFloat(1); + + return new Coords(lat, lon); + } + + City (String cityName) { + this.cityName = cityName; + } + + public String getCityName() { + return cityName; + } + + /** + * Returns the city coords using adresse.data.gouv.fr, cache the result + * @return the city Coords + * @throws IOException if the request to adresse.data.gouv.fr fails + * + */ + public Coords getCityCoords() throws IOException { + if (this.cityCoords == null) { + this.cityCoords = getCoordsFromName(cityName); + } + + return cityCoords; + } + + @Override + public String toString() { + try { + Coords coords = this.getCityCoords(); + return String.format( + "City(%s, lat: %f, lon: %f)", + this.cityName, + coords.getLat(), + coords.getLon() + ); + } + catch (IOException e) { + return String.format( + "City(%s, lat: Request failed, lon: Request Failed)", + this.cityName + ); + } + } +}