From 9b19742464825ee5e865bdfe33f5592dda8a7f7f Mon Sep 17 00:00:00 2001 From: Ekarry <81385639+Ekarry@users.noreply.github.com> Date: Thu, 3 Jun 2021 21:39:41 +0300 Subject: [PATCH 1/2] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D1=8C?= =?UTF-8?q?=D1=82=D0=B5,=20=D0=BF=D0=BE=D0=B6=D0=B0=D0=BB=D1=83=D0=B9?= =?UTF-8?q?=D1=81=D1=82=D0=B0,=20=D0=94=D0=976?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/HWLesson_6/WeatherApp.java | 50 ++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/main/java/HWLesson_6/WeatherApp.java diff --git a/src/main/java/HWLesson_6/WeatherApp.java b/src/main/java/HWLesson_6/WeatherApp.java new file mode 100644 index 0000000..fd54863 --- /dev/null +++ b/src/main/java/HWLesson_6/WeatherApp.java @@ -0,0 +1,50 @@ +package HWLesson_6; + +import java.io.IOException; +import java.util.Objects; + +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; + +public class WeatherApp { + private static final String BASE_HOST = "dataservice.accuweather.com"; + private static final String FORECAST = "forecasts"; + private static final String API_VERSION = "v1"; + private static final String FORECAST_TYPE = "daily"; + private static final String FORECAST_PERIOD = "5day"; + private static final String SAINT_PETERSBURG_KEY = "295212"; + private static final String API_KEY = "NMhWOUAJY8cgKzdgm5fBqcOsGluxsD5T"; + + + + public static void main(String[] args) throws IOException { + + OkHttpClient client = new OkHttpClient(); + HttpUrl url = new HttpUrl.Builder() + .scheme("http") + .host(BASE_HOST) + .addPathSegment(FORECAST) + .addPathSegment(API_VERSION) + .addPathSegment(FORECAST_TYPE) + .addPathSegment(FORECAST_PERIOD) + .addPathSegment(SAINT_PETERSBURG_KEY) + .addQueryParameter("apikey", API_KEY) + .addQueryParameter("language", "ru-ru") + .addQueryParameter("metric", "true") + .build(); + + System.out.println(url); + + Request requesthttp = new Request.Builder() + .addHeader("accept", "application/json") + .url(url) + .build(); + + String jsonResponse = Objects.requireNonNull(client.newCall(requesthttp).execute().body()).string(); + System.out.println(jsonResponse); + + + } + +} From 124461bd6254233b3c75ebf725db36b861bf44f7 Mon Sep 17 00:00:00 2001 From: Ekarry <81385639+Ekarry@users.noreply.github.com> Date: Thu, 10 Jun 2021 23:25:13 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D1=8C?= =?UTF-8?q?=D1=82=D0=B5,=20=D0=BF=D0=BE=D0=B6=D0=B0=D0=BB=D1=83=D0=B9?= =?UTF-8?q?=D1=81=D1=82=D0=B0,=20=D0=94=D0=977?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/HWLesson_7/GlobalState.java | 26 +++ .../java/HWLesson_7/WeatherAppInterface.java | 12 ++ .../controller/IWeatherController.java | 7 + .../controller/WeatherController.java | 35 ++++ .../java/HWLesson_7/entity/WeatherObject.java | 80 +++++++++ .../HWLesson_7/model/AccuWeatherProvider.java | 164 ++++++++++++++++++ .../java/HWLesson_7/model/DailyForecasts.java | 66 +++++++ src/main/java/HWLesson_7/model/Day.java | 29 ++++ .../HWLesson_7/model/IWeatherProvider.java | 7 + src/main/java/HWLesson_7/model/Night.java | 29 ++++ src/main/java/HWLesson_7/model/Period.java | 6 + .../java/HWLesson_7/model/Temperature.java | 43 +++++ src/main/java/HWLesson_7/model/Value.java | 29 ++++ .../HWLesson_7/model/WeatherResponse.java | 23 +++ .../java/HWLesson_7/view/IUserInterface.java | 7 + .../java/HWLesson_7/view/UserInterface.java | 53 ++++++ 16 files changed, 616 insertions(+) create mode 100644 src/main/java/HWLesson_7/GlobalState.java create mode 100644 src/main/java/HWLesson_7/WeatherAppInterface.java create mode 100644 src/main/java/HWLesson_7/controller/IWeatherController.java create mode 100644 src/main/java/HWLesson_7/controller/WeatherController.java create mode 100644 src/main/java/HWLesson_7/entity/WeatherObject.java create mode 100644 src/main/java/HWLesson_7/model/AccuWeatherProvider.java create mode 100644 src/main/java/HWLesson_7/model/DailyForecasts.java create mode 100644 src/main/java/HWLesson_7/model/Day.java create mode 100644 src/main/java/HWLesson_7/model/IWeatherProvider.java create mode 100644 src/main/java/HWLesson_7/model/Night.java create mode 100644 src/main/java/HWLesson_7/model/Period.java create mode 100644 src/main/java/HWLesson_7/model/Temperature.java create mode 100644 src/main/java/HWLesson_7/model/Value.java create mode 100644 src/main/java/HWLesson_7/model/WeatherResponse.java create mode 100644 src/main/java/HWLesson_7/view/IUserInterface.java create mode 100644 src/main/java/HWLesson_7/view/UserInterface.java diff --git a/src/main/java/HWLesson_7/GlobalState.java b/src/main/java/HWLesson_7/GlobalState.java new file mode 100644 index 0000000..bd454eb --- /dev/null +++ b/src/main/java/HWLesson_7/GlobalState.java @@ -0,0 +1,26 @@ +package HWLesson_7; + +public final class GlobalState { + + private static GlobalState INSTANCE; + private String selectedCity = null; + public final String API_KEY = "fx9gkDPNYPPSGK87ixzUPZKVsbl01DQR"; + + private GlobalState(){} + + public static GlobalState getInstance(){ + if (INSTANCE == null) { + INSTANCE = new GlobalState(); + } + return INSTANCE; + } + + public String getSelectedCity() { + return selectedCity; + } + + public void setSelectedCity(String selectedCity) { + this.selectedCity = selectedCity; + } + +} diff --git a/src/main/java/HWLesson_7/WeatherAppInterface.java b/src/main/java/HWLesson_7/WeatherAppInterface.java new file mode 100644 index 0000000..587840b --- /dev/null +++ b/src/main/java/HWLesson_7/WeatherAppInterface.java @@ -0,0 +1,12 @@ +package HWLesson_7; + +import HWLesson_7.view.IUserInterface; +import HWLesson_7.view.UserInterface; +import java.io.IOException; + +public class WeatherAppInterface { + public static void main(String[] args) throws IOException { + IUserInterface userInterface = new UserInterface(); + userInterface.showUI(); + } +} diff --git a/src/main/java/HWLesson_7/controller/IWeatherController.java b/src/main/java/HWLesson_7/controller/IWeatherController.java new file mode 100644 index 0000000..8d7b800 --- /dev/null +++ b/src/main/java/HWLesson_7/controller/IWeatherController.java @@ -0,0 +1,7 @@ +package HWLesson_7.controller; + +import java.io.IOException; + +public interface IWeatherController { + void onUserInput(int command) throws IOException; +} diff --git a/src/main/java/HWLesson_7/controller/WeatherController.java b/src/main/java/HWLesson_7/controller/WeatherController.java new file mode 100644 index 0000000..84e1a43 --- /dev/null +++ b/src/main/java/HWLesson_7/controller/WeatherController.java @@ -0,0 +1,35 @@ +package HWLesson_7.controller; + +import HWLesson_7.model.AccuWeatherProvider; +import HWLesson_7.model.IWeatherProvider; +import HWLesson_7.model.Period; + +import java.io.IOException; + +public class WeatherController implements IWeatherController { + + private final IWeatherProvider weatherProvider = new AccuWeatherProvider(); + + @Override + public void onUserInput(int command) throws IOException { + switch (command){ + case 1: + getCurrentWeather(); + break; + case 2: + getFiveDayWeather(); + break; + default: + System.out.println("Нет такой команды"); + System.exit(1); + } + } + + private void getCurrentWeather() throws IOException { + weatherProvider.getWeather(Period.NOW); + } + + private void getFiveDayWeather() throws IOException { + weatherProvider.getWeather(Period.FIVE_DAYS); + } +} diff --git a/src/main/java/HWLesson_7/entity/WeatherObject.java b/src/main/java/HWLesson_7/entity/WeatherObject.java new file mode 100644 index 0000000..0df4f04 --- /dev/null +++ b/src/main/java/HWLesson_7/entity/WeatherObject.java @@ -0,0 +1,80 @@ +package HWLesson_7.entity; + +public class WeatherObject { + private String cityName; + private String date; + private String dayDescription; + private String nightDescription; + private String maxTemperature; + private String minTemperature; + + public WeatherObject(String cityName, String date, String dayDescription, String nightDescription, String maxTemperature, String minTemperature) { + this.cityName = cityName; + this.date = date; + this.dayDescription = dayDescription; + this.nightDescription = nightDescription; + this.maxTemperature = maxTemperature; + this.minTemperature = minTemperature; + } + + public String getCityName() { + return cityName; + } + + public void setCityName(String cityName) { + this.cityName = cityName; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public String getDayDescription() { + return dayDescription; + } + + public void setDayDescription(String dayDescription) { + this.dayDescription = dayDescription; + } + + public String getNightDescription() { + return nightDescription; + } + + public void setNightDescription(String nightDescription) { + this.nightDescription = nightDescription; + } + + public String getMaxTemperature() { + return maxTemperature; + } + + public void setMaxTemperature(String maxTemperature) { + this.maxTemperature = maxTemperature; + } + + public String getMinTemperature() { + return minTemperature; + } + + public void setMinTemperature(String minTemperature) { + this.minTemperature = minTemperature; + } + + @Override + public String toString() { + return "WeatherObject{" + + "cityName='" + cityName + '\'' + + ", date='" + date + '\'' + + ", dayDescription='" + dayDescription + '\'' + + ", nightDescription='" + nightDescription + '\'' + + ", maxTemperature='" + maxTemperature + '\'' + + ", minTemperature='" + minTemperature + '\'' + + '}'; + } + +} diff --git a/src/main/java/HWLesson_7/model/AccuWeatherProvider.java b/src/main/java/HWLesson_7/model/AccuWeatherProvider.java new file mode 100644 index 0000000..cf09333 --- /dev/null +++ b/src/main/java/HWLesson_7/model/AccuWeatherProvider.java @@ -0,0 +1,164 @@ +package HWLesson_7.model; + +import HWLesson_7.GlobalState; +import HWLesson_7.entity.WeatherObject; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +public class AccuWeatherProvider implements IWeatherProvider { + private final String BASE_HOST = "dataservice.accuweather.com"; + private final String VERSION = "v1"; + private final OkHttpClient okHttpClient = new OkHttpClient(); + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Override + public void getWeather(Period period) throws RuntimeException { + String key = detectCityKeyNyName(); + if (period.equals(Period.NOW)){ + Request request = makeRequest(makeRequestURL(Period.NOW, key)); + try { + String weatherResponse = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); + if (objectMapper.readTree(weatherResponse).size() > 0) { + makeWeatherForecast(weatherResponse); + } else { + throw new RuntimeException(GlobalState.getInstance().getSelectedCity()+" - такой город не найден\n"); + } + } catch (RuntimeException | IOException | ParseException e) { + throw new RuntimeException(e); + } + } else if (period.equals(Period.FIVE_DAYS)) { + Request request = makeRequest(makeRequestURL(Period.FIVE_DAYS, key)); + try { + String weatherResponse = Objects.requireNonNull(okHttpClient.newCall(request).execute().body()).string(); + if (objectMapper.readTree(weatherResponse).size() > 0) { + makeWeatherForecast(weatherResponse); + } else { + throw new RuntimeException(GlobalState.getInstance().getSelectedCity()+" - такой город не найден\n"); + } + } catch (RuntimeException | IOException | ParseException e) { + throw new RuntimeException(e); + } + } else { + throw new RuntimeException(period + " - такой временной интервал не верен\n"); + } + } + + private String detectCityKeyNyName() { + String selectedCity = GlobalState.getInstance().getSelectedCity(); + Request request = makeRequest(makeRequestURL(selectedCity)); + + Response locationResponse; + try { + locationResponse = okHttpClient.newCall(request).execute(); + if (!locationResponse.isSuccessful()) { + throw new RuntimeException("Сервер ответил "+locationResponse.code()); + } + assert locationResponse.body() != null; + String jsonResponse = locationResponse.body().string(); + if (objectMapper.readTree(jsonResponse).size() > 0) { + String code = objectMapper.readTree(jsonResponse).get(0).at("/Key").asText(); + String cityName = objectMapper.readTree(jsonResponse).get(0).at("/LocalizedName").asText(); + String countryName = objectMapper.readTree(jsonResponse).get(0).at("/Country/LocalizedName").asText(); + System.out.printf("Найден город %s в стране %s, код - %s\n", cityName,countryName, code); + return code; + } else { + throw new RuntimeException(selectedCity+" - такой город не найден\n"); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private HttpUrl makeRequestURL(Period period, String key) { + String forecastPeriod; + if (period.equals(Period.NOW)) { + forecastPeriod = "1day"; + } else if (period.equals(Period.FIVE_DAYS)) { + forecastPeriod = "5day"; + } else { + System.out.println("Неверный формат для прогноза погоды"); + return null; + } + String LANGUAGE = "ru"; + String FORECASTS = "forecasts"; + String DAILY = "daily"; + String METRIC = "true"; + return new HttpUrl.Builder() + .scheme("http") + .host(BASE_HOST) + .addPathSegment(FORECASTS) + .addPathSegment(VERSION) + .addPathSegment(DAILY) + .addPathSegment(forecastPeriod) + .addPathSegment(key) + .addQueryParameter("apikey", GlobalState.getInstance().API_KEY) + .addQueryParameter("language", LANGUAGE) + .addQueryParameter("metric", METRIC) + .build(); + } + + private HttpUrl makeRequestURL(String selectedCity) { + if (selectedCity.length() != 0) { + String LOCATIONS = "locations"; + String CITIES = "cities"; + String SEARCH = "search"; + return new HttpUrl.Builder() + .scheme("http") + .host(BASE_HOST) + .addPathSegment(LOCATIONS) + .addPathSegment(VERSION) + .addPathSegment(CITIES) + .addPathSegment(SEARCH) + .addQueryParameter("apikey", GlobalState.getInstance().API_KEY) + .addQueryParameter("q", selectedCity) + .build(); + } else { + System.out.println("Неверный формат для поиска кода города"); + return null; + } + } + + private Request makeRequest(HttpUrl url) { + return new Request.Builder() + .addHeader("accept", "application/json") + .url(url) + .build(); + } + + private String changeDateFormat(String date) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + SimpleDateFormat output = new SimpleDateFormat("dd MMMM yyyy г.", new Locale("ru")); + Date newDate = sdf.parse(date); + Date d = sdf.parse(date); + return output.format(d); + } + + private void makeWeatherForecast(String jsonResponse) throws JsonProcessingException, ParseException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + WeatherResponse weatherResponse = objectMapper.readValue(jsonResponse,new TypeReference() {}); + List weatherObject = createWeatherObject(weatherResponse); + for (WeatherObject i: weatherObject) { + System.out.printf("В городе %s на дату %s днем ожидается %s, вечером - %s. Максимальная температура составит %s \u00B0С, минимальная - %s \u00B0С.\n", i.getCityName(),i.getDate(), i.getDayDescription(), i.getNightDescription(), i.getMaxTemperature(), i.getMinTemperature()); + } + } + + private List createWeatherObject(WeatherResponse weatherResponse) throws ParseException { + List weatherObject = new ArrayList<>(); + for (DailyForecasts i: weatherResponse.getDailyForecasts()) { + weatherObject.add(new WeatherObject(GlobalState.getInstance().getSelectedCity(), changeDateFormat(i.getDate()),i.getDay().getDescription(),i.getNight().getDescription(),i.getTempInfo().getMax().getTemperatureValue(),i.getTempInfo().getMin().getTemperatureValue())); + } + return weatherObject; + } +} diff --git a/src/main/java/HWLesson_7/model/DailyForecasts.java b/src/main/java/HWLesson_7/model/DailyForecasts.java new file mode 100644 index 0000000..3f1755f --- /dev/null +++ b/src/main/java/HWLesson_7/model/DailyForecasts.java @@ -0,0 +1,66 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DailyForecasts { + + @JsonProperty(value = "Date") + private String date; + @JsonProperty(value = "Temperature") + private Temperature tempInfo; + @JsonProperty(value = "Day") + private Day day; + @JsonProperty(value = "Night") + private Night night; + + public DailyForecasts(String date, Temperature tempInfo, Day day, Night night) { + this.date = date; + this.tempInfo = tempInfo; + this.day = day; + this.night = night; + } + + public String getDate() { + return date; + } + + public void setDate(String date) { + this.date = date; + } + + public Temperature getTempInfo() { + return tempInfo; + } + + public void setTempInfo(Temperature tempInfo) { + this.tempInfo = tempInfo; + } + + public Day getDay() { + return day; + } + + public void setDay(Day day) { + this.day = day; + } + + public Night getNight() { + return night; + } + + public void setNight(Night night) { + this.night = night; + } + + @Override + public String toString() { + return "DailyForecasts{" + + "date='" + date + '\'' + + ", tempInfo=" + tempInfo + + ", day=" + day + + ", night=" + night + + '}'; + } +} diff --git a/src/main/java/HWLesson_7/model/Day.java b/src/main/java/HWLesson_7/model/Day.java new file mode 100644 index 0000000..516e293 --- /dev/null +++ b/src/main/java/HWLesson_7/model/Day.java @@ -0,0 +1,29 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Day { + @JsonProperty(value = "IconPhrase") + private String description; + + public Day(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "Day{" + + "description='" + description + '\'' + + '}'; + } +} diff --git a/src/main/java/HWLesson_7/model/IWeatherProvider.java b/src/main/java/HWLesson_7/model/IWeatherProvider.java new file mode 100644 index 0000000..ed0612c --- /dev/null +++ b/src/main/java/HWLesson_7/model/IWeatherProvider.java @@ -0,0 +1,7 @@ +package HWLesson_7.model; + +import java.io.IOException; + +public interface IWeatherProvider { + void getWeather(Period period) throws IOException; +} diff --git a/src/main/java/HWLesson_7/model/Night.java b/src/main/java/HWLesson_7/model/Night.java new file mode 100644 index 0000000..d223eef --- /dev/null +++ b/src/main/java/HWLesson_7/model/Night.java @@ -0,0 +1,29 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Night { + @JsonProperty(value = "IconPhrase") + private String description; + + public Night(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "Night{" + + "description='" + description + '\'' + + '}'; + } +} diff --git a/src/main/java/HWLesson_7/model/Period.java b/src/main/java/HWLesson_7/model/Period.java new file mode 100644 index 0000000..47d53a2 --- /dev/null +++ b/src/main/java/HWLesson_7/model/Period.java @@ -0,0 +1,6 @@ +package HWLesson_7.model; + +public enum Period { + NOW, + FIVE_DAYS +} diff --git a/src/main/java/HWLesson_7/model/Temperature.java b/src/main/java/HWLesson_7/model/Temperature.java new file mode 100644 index 0000000..cc7db57 --- /dev/null +++ b/src/main/java/HWLesson_7/model/Temperature.java @@ -0,0 +1,43 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Temperature { + @JsonProperty(value = "Minimum") + private Value min; + @JsonProperty(value = "Maximum") + private Value max; + + public Temperature() {} + + public Temperature(Value min, Value max) { + this.min = min; + this.max = max; + } + + public Value getMin() { + return min; + } + + public void setMin(Value min) { + this.min = min; + } + + public Value getMax() { + return max; + } + + @Override + public String toString() { + return "Temperature{" + + "min=" + min + + ", max=" + max + + '}'; + } + + public void setMax(Value max) { + this.max = max; + } +} diff --git a/src/main/java/HWLesson_7/model/Value.java b/src/main/java/HWLesson_7/model/Value.java new file mode 100644 index 0000000..f7f33b2 --- /dev/null +++ b/src/main/java/HWLesson_7/model/Value.java @@ -0,0 +1,29 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class Value { + @JsonProperty(value = "Value") + private String temperatureValue; + + public Value(String temperatureValue) { + this.temperatureValue = temperatureValue; + } + + public String getTemperatureValue() { + return temperatureValue; + } + + public void setTemperatureValue(String temperatureValue) { + this.temperatureValue = temperatureValue; + } + + @Override + public String toString() { + return "Value{" + + "temperatureValue='" + temperatureValue + '\'' + + '}'; + } +} diff --git a/src/main/java/HWLesson_7/model/WeatherResponse.java b/src/main/java/HWLesson_7/model/WeatherResponse.java new file mode 100644 index 0000000..a85eb5c --- /dev/null +++ b/src/main/java/HWLesson_7/model/WeatherResponse.java @@ -0,0 +1,23 @@ +package HWLesson_7.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public class WeatherResponse { + @JsonProperty(value = "DailyForecasts") + private List dailyForecasts; + + public WeatherResponse(List dailyForecasts) { + this.dailyForecasts = dailyForecasts; + } + + public List getDailyForecasts() { + return dailyForecasts; + } + + public void setDailyForecasts(List dailyForecasts) { + this.dailyForecasts = dailyForecasts; + } +} diff --git a/src/main/java/HWLesson_7/view/IUserInterface.java b/src/main/java/HWLesson_7/view/IUserInterface.java new file mode 100644 index 0000000..6a1899f --- /dev/null +++ b/src/main/java/HWLesson_7/view/IUserInterface.java @@ -0,0 +1,7 @@ +package HWLesson_7.view; + +import java.io.IOException; + +public interface IUserInterface { + void showUI() throws IOException; +} diff --git a/src/main/java/HWLesson_7/view/UserInterface.java b/src/main/java/HWLesson_7/view/UserInterface.java new file mode 100644 index 0000000..5a15f63 --- /dev/null +++ b/src/main/java/HWLesson_7/view/UserInterface.java @@ -0,0 +1,53 @@ +package HWLesson_7.view; + +import HWLesson_7.GlobalState; +import HWLesson_7.controller.IWeatherController; +import HWLesson_7.controller.WeatherController; + +import java.io.IOException; +import java.util.Scanner; + +public class UserInterface implements IUserInterface { + + private IWeatherController controller = new WeatherController(); + + @Override + public void showUI() throws IOException { + Scanner scanner = new Scanner(System.in); + while (true) { + System.out.println("Введите название города или exit для выхода"); + String userInput = scanner.nextLine(); + checkIsExit(userInput); + GlobalState.getInstance().setSelectedCity(userInput); + System.out.print("Введите команду: \n1. - погода на 1 день\n2. - погода на 5 дней\n"); + String command = scanner.nextLine(); + try { + validateUserInput(command); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Неверная команда"); + continue; + } + controller.onUserInput(Integer.parseInt(command)); + } + } + + private void checkIsExit(String input) { + if (input.equalsIgnoreCase("exit") || input.equalsIgnoreCase("выход") ) { + System.out.println("Завершаю работу"); + System.exit(0); + } + } + + private void validateUserInput(String command) throws Exception { + if (command == null || command.length() != 1) { + throw new Exception("Неверная команда"); + } + int answer = 0; + try { + answer = Integer.parseInt(command); + } catch (NumberFormatException e) { + throw new Exception("Неверная команда"); + } + } +}