Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/main/java/HWLesson_6/WeatherApp.java
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а почему это в main? мы же должны пользователю меню показать


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);


}

}
26 changes: 26 additions & 0 deletions src/main/java/HWLesson_7/GlobalState.java
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;
}

}
12 changes: 12 additions & 0 deletions src/main/java/HWLesson_7/WeatherAppInterface.java
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();
}
}
7 changes: 7 additions & 0 deletions src/main/java/HWLesson_7/controller/IWeatherController.java
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 src/main/java/HWLesson_7/controller/WeatherController.java
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);
}
}
80 changes: 80 additions & 0 deletions src/main/java/HWLesson_7/entity/WeatherObject.java
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 src/main/java/HWLesson_7/model/AccuWeatherProvider.java
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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;
}
}
Loading