-
Notifications
You must be signed in to change notification settings - Fork 0
Прошу проверить ДЗ7 #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Ekarry
wants to merge
2
commits into
master
Choose a base branch
from
HWLesson_7
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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); | ||
|
|
||
|
|
||
| } | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package HWLesson_7.controller; | ||
|
|
||
| import java.io.IOException; | ||
|
|
||
| public interface IWeatherController { | ||
| void onUserInput(int command) throws IOException; | ||
| } |
35 changes: 35 additions & 0 deletions
35
src/main/java/HWLesson_7/controller/WeatherController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 + '\'' + | ||
| '}'; | ||
| } | ||
|
|
||
| } |
164 changes: 164 additions & 0 deletions
164
src/main/java/HWLesson_7/model/AccuWeatherProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. дублирующие блоки кода говорят о том, что логику можно вынести в методы и переиспользовать их. Тут в блоке if-else почти весь код дублируется |
||
| 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<WeatherResponse>() {}); | ||
| List<WeatherObject> 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<WeatherObject> createWeatherObject(WeatherResponse weatherResponse) throws ParseException { | ||
| List<WeatherObject> 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; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
а почему это в main? мы же должны пользователю меню показать