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
96 changes: 96 additions & 0 deletions src/main/java/HWLesson_8/AppGlobalState.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package HWLesson_8;

import java.sql.*;

public class AppGlobalState {

static {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

private static Connection connection;

private static Statement statement;

private static PreparedStatement insertWeatherPreparedStatement;

private static AppGlobalState instance;

public String cityName1;

private String cityKey;

public String getCityName1() {

return cityName1;
}

public static Connection getConnection() {

return connection;
}

public static Statement getStatement(){
return statement;
}

public static PreparedStatement getInsertWeatherPreparedStatement() {

return insertWeatherPreparedStatement;
}

public void setCityName1(String cityName1) {

this.cityName1 = cityName1;
}

public String getCityKey() {

return cityKey;
}

public void setCityKey(String cityKey) {

this.cityKey = cityKey;
}

public String getDbName() {

return "weather-app.db";
}


private AppGlobalState() {
try {
connection = DriverManager.getConnection("jdbc:sqlite:c:\\sqlite\\"+getDbName());
statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS weather(" +
"date TEXT NOT NULL,city TEXT NOT NULL, temp TEXT NOT NULL, text TEXT NOT NULL);");
insertWeatherPreparedStatement = connection.prepareStatement(
"INSERT INTO weather (date, city, temp, text) VALUES (?,?,?,?);"
);



} catch (SQLException throwable) {
throwable.printStackTrace();
System.exit(1);
}
}
public static AppGlobalState getInstance () {
if (instance == null) {
instance = new AppGlobalState();
}
return instance;
}


public String getApiKey() {

return "fx9gkDPNYPPSGK87ixzUPZKVsbl01DQR";
}
}
6 changes: 6 additions & 0 deletions src/main/java/HWLesson_8/UserCommands.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package HWLesson_8;

public enum UserCommands {
GET_CURRENT_WEATHER,
GET_NEXT_FIVE_DAYS_WEATHER
}
15 changes: 15 additions & 0 deletions src/main/java/HWLesson_8/WeatherApp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package HWLesson_8;

import HWLesson_8.view.IUserInterface;
import HWLesson_8.view.UserInterface;

public class WeatherApp {
public static void main(String[] args) {

IUserInterface ui = new UserInterface();

ui.showMenu();


}
}
53 changes: 53 additions & 0 deletions src/main/java/HWLesson_8/controller/Controller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package HWLesson_8.controller;

import HWLesson_8.*;
import HWLesson_8.model.*;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

public class Controller implements IController {

ICityCodeProvider codeProvider = new AccuWeatherCityCodeProvider();
IWeatherProvider weatherProvider = new AccuWeatherProvider();
IWeatherRepository weatherRepository = new SQLiteWeatherRepository();


@Override
public void onCityInput(String city) throws IOException {

if(city.length() == 1) {
throw new IOException("Недопустимо короткое название города");
}
codeProvider.getCodeByCityName(city);

}

@Override
public void onCommandChosen(int selectedCommand) throws IOException, ParseException {
System.out.println(" ");
switch (selectedCommand) {
case 1: {
Weather currentWeather = weatherProvider.getCurrentWeather(AppGlobalState.getInstance().getCityKey());
System.out.println(currentWeather);
weatherRepository.saveWeatherObject(currentWeather);
break;
}
case 2: {
weatherProvider.getWeatherForFiveDays(AppGlobalState.getInstance().getCityKey());
break;
}
case 3: {
List<Weather> allData = weatherRepository.getAllData();
allData.forEach(System.out::println);

break;
}
default: {
throw new IOException("Вы ввели данные неверно.\n");
}
}
}

}
11 changes: 11 additions & 0 deletions src/main/java/HWLesson_8/controller/IController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package HWLesson_8.controller;

import java.io.IOException;
import java.text.ParseException;

public interface IController {

void onCityInput(String city) throws IOException;

void onCommandChosen(int selectedCommand) throws IOException, ParseException;
}
72 changes: 72 additions & 0 deletions src/main/java/HWLesson_8/model/AccuWeatherCityCodeProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package HWLesson_8.model;

import HWLesson_8.AppGlobalState;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class AccuWeatherCityCodeProvider implements ICityCodeProvider {

private static final String BASE_HOST = "dataservice.accuweather.com";
private static final String LOCATIONS_SERVICE_PATH = "locations";
private static final String API_VERSION = "v1";
private static final String API_KEY = AppGlobalState.getInstance().getApiKey();


private final OkHttpClient client = new OkHttpClient();
private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void getCodeByCityName(String cityName) throws IOException {
//http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey={{accuweatherApiKey}}&q=Brest

HttpUrl detectLocationUrl = new HttpUrl.Builder()
.scheme("http")
.host(BASE_HOST)
.addPathSegment(LOCATIONS_SERVICE_PATH)
.addPathSegment(API_VERSION)
.addPathSegment("cities")
.addPathSegment("autocomplete")
.addQueryParameter("apikey", API_KEY)
.addQueryParameter("q", cityName)
.build();

Request detectLocationRequest = new Request.Builder()
.addHeader("accept", "application/json")
.url(detectLocationUrl)
.build();


Response response = client.newCall(detectLocationRequest).execute();
if (!response.isSuccessful()) {
throw new IOException("Сетевая ошибка\n");
}

assert response.body() != null;
String jsonBody = response.body().string();

if (objectMapper.readTree(jsonBody).size() < 1) {
throw new IOException("Города с таким названием не нашлось\n");
}

String cityTitle = objectMapper.readTree(jsonBody).get(0).at("/LocalizedName").asText();
String countryTitle = objectMapper.readTree(jsonBody).get(0).at("/Country/LocalizedName").asText();

String cityKey = objectMapper.readTree(jsonBody).get(0).at("/Key").asText();
System.out.println("* * * * * * * * * *");

System.out.printf("Поиск завершен. Город %s в стране %s!\n", cityTitle, countryTitle);
System.out.println("* * * * * * * * * *");
AppGlobalState.getInstance().setCityName1(cityTitle);


AppGlobalState.getInstance().setCityKey(cityKey);

}


}
122 changes: 122 additions & 0 deletions src/main/java/HWLesson_8/model/AccuWeatherProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package HWLesson_8.model;

import HWLesson_8.AppGlobalState;
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.Date;

public class AccuWeatherProvider implements IWeatherProvider {

private static final String BASE_HOST = "dataservice.accuweather.com";
private static final String CONDITIONS_PATH = "currentconditions";
private static final String FORECASTS = "forecasts";
private static final String API_VERSION = "v1";
private static final String DAILY = "daily";
private static final String DAYS = "5day";
private static final String API_KEY = AppGlobalState.getInstance().getApiKey();

private final OkHttpClient client = new OkHttpClient();
private final ObjectMapper objectMapper = new ObjectMapper();


@Override
public Weather getCurrentWeather(String cityKey) throws IOException, ParseException {
//http://dataservice.accuweather.com/currentconditions/v1/27497?apikey={{accuweatherApiKey}}

HttpUrl getWeatherUrl = new HttpUrl.Builder()
.scheme("http")
.host(BASE_HOST)
.addPathSegment(CONDITIONS_PATH)
.addPathSegment(API_VERSION)
.addPathSegment(cityKey)
.addQueryParameter("apikey", API_KEY)
.build();
Request getWeatherRequest = new Request.Builder()
.addHeader("accept", "application/json")
.url(getWeatherUrl)
.build();

Response response = client.newCall(getWeatherRequest).execute();
if (!response.isSuccessful()) {
throw new IOException("Ошибка сети\n");
}

assert response.body() != null;
String jsonBody2 = response.body().string();

String OneDayCityName = AppGlobalState.getInstance().getCityName1();
String OneDay = objectMapper.readTree(jsonBody2).get(0).at("/LocalObservationDateTime").asText().substring(0,10);

SimpleDateFormat oldDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat newDateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = oldDateFormat.parse(OneDay);
String OneDayForecastDate = newDateFormat.format(date);

String OneDayDescription = objectMapper.readTree(jsonBody2).get(0).at("/WeatherText").asText().toLowerCase();
String OneDayTemperature = objectMapper.readTree(jsonBody2).get(0).at("/Temperature/Metric/Value").asText();


Weather weather = new Weather(OneDayForecastDate, OneDayCityName, OneDayTemperature, OneDayDescription);
return weather;
}

@Override
public void getWeatherForFiveDays(String cityKey) throws IOException, ParseException {
//http://dataservice.accuweather.com/forecasts/v1/daily/5day/295212?apikey=XYHQlFgxfVgXHA2ydmRCbLLAQacY1QbQ&language=ru&metric=true

HttpUrl getWeatherUrl = new HttpUrl.Builder()
.scheme("http")
.host(BASE_HOST)
.addPathSegment(FORECASTS)
.addPathSegment(API_VERSION)
.addPathSegment(DAILY)
.addPathSegment(DAYS)
.addPathSegment(cityKey)
.addQueryParameter("apikey", API_KEY)
.addQueryParameter("metric","true")
.build();

Request getWeatherRequest = new Request.Builder()
.addHeader("accept", "application/json")
.url(getWeatherUrl)
.build();

Response response = client.newCall(getWeatherRequest).execute();
if (!response.isSuccessful()) {
throw new IOException("Ошибка сети\n");
}
assert response.body() != null;
String jsonBody2 = response.body().string();

System.out.println(" ");

for (int i = 0; i < 5; i++) {

String firstDay = objectMapper.readTree(jsonBody2).at("/DailyForecasts/"+i+"/Date").asText().substring(0,10);
SimpleDateFormat oldDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat newDateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = oldDateFormat.parse(firstDay);
String dayForecastDate = newDateFormat.format(date);

String dayCityName = AppGlobalState.getInstance().getCityName1();

String dayTemperatureMin = objectMapper.readTree(jsonBody2).at("/DailyForecasts/"+i+"/Temperature/Minimum/Value").asText();
String dayTemperatureMax = objectMapper.readTree(jsonBody2).at("/DailyForecasts/"+i+"/Temperature/Maximum/Value").asText();

String dayDescriptionDay = objectMapper.readTree(jsonBody2).at("/DailyForecasts/"+i+"/Day/IconPhrase").asText().toLowerCase();
String dayDescriptionNight = objectMapper.readTree(jsonBody2).at("/DailyForecasts/"+i+"/Night/IconPhrase").asText().toLowerCase();

System.out.println("* * * * * * * * * *");
System.out.printf("На дату %s в городе %s погода днем %s, погода ночью %s, а температура от %sC до %sC\n", dayForecastDate, dayCityName, dayDescriptionDay,dayDescriptionNight, dayTemperatureMin, dayTemperatureMax);

}

}

}
7 changes: 7 additions & 0 deletions src/main/java/HWLesson_8/model/ICityCodeProvider.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package HWLesson_8.model;

import java.io.IOException;

public interface ICityCodeProvider {
void getCodeByCityName(String cityName) throws IOException;
}
Loading