fix: OpenMeteo implementation

This commit is contained in:
Martin Eyben 2024-11-18 22:09:24 +01:00
parent e51b7de1e0
commit 4605b28d79
2 changed files with 27 additions and 8 deletions

View File

@ -1,5 +1,6 @@
package eirb.pg203;
import org.json.JSONArray;
import org.json.JSONObject;
import eirb.pg203.utils.JSONFetcher;
@ -19,15 +20,16 @@ public class OpenMeteo implements WeatherDataAPI {
// https://www.nodc.noaa.gov/archive/arc0021/0002199/1.1/data/0-data/HTML/WMO-CODE/WMO4677.HTM
private JSONObject fetchWeather(int days, City city) throws IOException {
URL url = URI.create(
String.format(forecastBaseURL + "?latitude=%.2f&longitude=%.2f&forecast_days=%d&daily=" + dailyQuery,
city.getCityCoords().getLat(),
city.getCityCoords().getLon(),
days
)
).toURL();
URL url = URI.create(
String.format(forecastBaseURL + "?latitude=%.2f&longitude=%.2f&forecast_days=%d&daily=" + dailyQuery,
city.getCityCoords().getLat(),
city.getCityCoords().getLon(),
days
)
).toURL();
return JSONFetcher.fetch(url);
JSONArray jsonArray = JSONFetcher.fetchArray(url);
return jsonArray.getJSONObject(0);
}
private static Condition getConditionFromCode(int WMOCode) {

View File

@ -6,6 +6,7 @@ import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONFetcher {
@ -20,6 +21,22 @@ public class JSONFetcher {
}
}
return new JSONObject(result.toString());
}
public static JSONArray fetchArray(URL url) throws IOException {
StringBuilder result = new StringBuilder();
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 JSONArray(result.toString());
}
}