Sure! Here's the refactored version of your code, with improvements and explanations for each change:
java
package org.example.api;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.example.utils.Utils;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
public class ApiMain {
// A simple class to hold coordinates
public static class Coordinates {
private final double latitude;
private final double longitude;
public Coordinates(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
public static Coordinates getLatitudeLongitudeByCity(String city) throws IOException, InterruptedException {
// URL-encode the city name to handle spaces and special characters
String encodedCity = URLEncoder.encode(city, StandardCharsets.UTF_8);
String uri = String.format(
"https://geocoding-api.open-meteo.com/v1/search?name=%s&count=1&language=ru&format=json",
encodedCity
);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(uri)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseText = response.body();
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> responseMap = gson.fromJson(responseText, mapType);
List<Map<String, Object>> results = (List<Map<String, Object>>) responseMap.get("results");
if (results == null || results.isEmpty()) {
// Return null or throw an exception if the city is not found
return null;
}
Map<String, Object> firstResult = results.get(0);
double latitude = ((Number) firstResult.get("latitude")).doubleValue();
double longitude = ((Number) firstResult.get("longitude")).doubleValue();
return new Coordinates(latitude, longitude);
}
public static String getWeatherOnTomorrow(double latitude, double longitude) throws IOException, InterruptedException {
String tomorrow = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String uri = String.format(
"https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s&daily=weather_code,temperature_2m_max,temperature_2m_min&start_date=%s&end_date=%s",
latitude, longitude, tomorrow, tomorrow
);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(uri)).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseText = response.body();
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> responseMap = gson.fromJson(responseText, mapType);
Map<String, Object> daily = (Map<String, Object>) responseMap.get("daily");
if (daily == null) {
return "Ошибка: данные погоды не найдены.";
}
List<Double> weatherCodes = (List<Double>) daily.get("weather_code");
List<Double> tempMaxList = (List<Double>) daily.get("temperature_2m_max");
List<Double> tempMinList = (List<Double>) daily.get("temperature_2m_min");
if (weatherCodes == null || weatherCodes.isEmpty()
|| tempMaxList == null || tempMaxList.isEmpty()
|| tempMinList == null || tempMinList.isEmpty()) {
return "Ошибка: неполные данные погоды.";
}
int weatherCode = weatherCodes.get(0).intValue();
double tempMax = tempMaxList.get(0);
double tempMin = tempMinList.get(0);
Utils utils = new Utils();
String weatherDescription = utils.getWMOWeatherByCode(weatherCode);
return String.format(
"Завтра, %s:%nМаксимальная температура: %.1f°C%nМинимальная температура: %.1f°C%nПогода: %s",
tomorrow, tempMax, tempMin, weatherDescription
);
}
public static String getWeatherOnTomorrow(String city) throws IOException, InterruptedException {
Coordinates coords = getLatitudeLongitudeByCity(city);
if (coords == null) {
return "Ошибка: город \"" + city + "\" не найден.";
}
return getWeatherOnTomorrow(coords.getLatitude(), coords.getLongitude());
}
}
Explanation of Changes:
Created a Coordinates Class:
Introduced a new class Coordinates to encapsulate the latitude and longitude. This makes the code more readable and type-safe compared to using a list or array.
Fixed Typos:
Corrected responceText to responseText.
Removed Unnecessary close() Calls:
Removed client.close(); because HttpClient instances do not require closing. They are designed to be reused and are thread-safe.
Used URL Encoding for City Names:
Encoded the city parameter using URLEncoder to handle spaces and special characters in city names.
Replaced getFirst() with get(0):
Replaced non-existent getFirst() method calls with get(0) on lists.
Proper Date Formatting:
Changed the date format pattern from "YYYY-MM-dd" to "yyyy-MM-dd". In Java's DateTimeFormatter, "yyyy" represents the year, whereas "YYYY" represents the week-year, which can cause issues.
Added Null and Empty Checks:
Included checks for null and empty lists when processing the JSON response to prevent NullPointerExceptions.
Improved Error Messages:
Provided more descriptive error messages when data is missing or the city is not found.
Simplified JSON Parsing:
Used proper generic types with TypeToken for parsing JSON with Gson.
Cast types appropriately and used Number to handle both integer and floating-point numbers uniformly.
Removed Unnecessary Casting:
Eliminated unnecessary casts and used the appropriate generic types to avoid ClassCastException.
Cleaned Up Variable Names and Formatting:
Additional Suggestions:
Handle Exceptions Gracefully:
Consider adding custom exception handling to provide more context-specific error messages or to retry requests in case of transient network issues.
Logging:
Implement logging to track the flow of execution and aid in debugging.
Configuration Management:
Extract hard-coded URLs and API endpoints into configuration files or constants.
Unit Testing:
Write unit tests for each method to ensure they work correctly with various inputs, including edge cases.
API Rate Limiting and Caching:
Implement caching mechanisms if the API usage is high, to minimize the number of API calls and respect rate limits.
Usage Example:
java
public class Main {
public static void main(String[] args) {
try {
String weatherReport = ApiMain.getWeatherOnTomorrow("Москва");
System.out.println(weatherReport);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
Note: Replace "Москва" with the desired city name.
By applying these changes, the code becomes cleaner, more robust, and easier to maintain. Feel free to ask if you have any questions or need further assistance!