87 Commits

Author SHA1 Message Date
Alexey Zinchenko 4cfa8ab843 2.1.0 version implementation. 2021-04-12 02:00:51 +03:00
Alexey Zinchenko 196f9ec289 Update README.md 2021-03-28 16:13:58 +03:00
Prominence 4998663298 Releasing 2.0.1 version. 2021-03-26 23:36:06 +03:00
Alexey Zinchenko f5d202aee3 Version 2.0.1 (#13)
* Added method for weather icon id retrieval. Small internal changes in models.

* Changed temperature unit signs.
2021-03-26 23:32:57 +03:00
Prominence 4c1b079e05 Releasing 2.0.0 version. 2021-03-26 02:20:19 +03:00
Alexey Zinchenko 7ad0f9d415 Merge pull request #4 from Prominence/dev
2.0.0 version implementation.
2021-03-26 02:14:53 +03:00
Prominence e9a5011c5c Fixed README library coordinates. 2021-03-26 01:05:07 +03:00
Prominence cba15e6420 Added logging on requests. 2021-03-26 00:56:19 +03:00
Prominence cd8209e677 Fixed documentation code snippet. 2021-03-26 00:50:37 +03:00
Prominence 64e02cd7a8 A lot of refactoring and documentation writing. 2021-03-26 00:48:39 +03:00
Prominence b301d93b39 Small docs improvement. 2021-03-25 00:59:23 +03:00
Prominence c68c6fd2b6 Wrote documentation. 2021-03-25 00:58:14 +03:00
Alexey Zinchenko cd263234bc Merge pull request #12 from Prominence/dependabot/maven/dev/org.apache.maven.plugins-maven-source-plugin-3.2.1
Bump maven-source-plugin from 2.2.1 to 3.2.1
2021-03-24 11:01:56 +03:00
Alexey Zinchenko bcee4135fc Merge pull request #11 from Prominence/dependabot/maven/dev/org.jacoco-jacoco-maven-plugin-0.8.6
Bump jacoco-maven-plugin from 0.8.4 to 0.8.6
2021-03-24 11:01:43 +03:00
Alexey Zinchenko 9b67c57d7e Merge pull request #10 from Prominence/dependabot/maven/dev/org.apache.maven.plugins-maven-jar-plugin-3.2.0
Bump maven-jar-plugin from 3.1.0 to 3.2.0
2021-03-24 10:59:53 +03:00
dependabot-preview[bot] 848b5397ac Bump maven-source-plugin from 2.2.1 to 3.2.1
Bumps [maven-source-plugin](https://github.com/apache/maven-source-plugin) from 2.2.1 to 3.2.1.
- [Release notes](https://github.com/apache/maven-source-plugin/releases)
- [Commits](https://github.com/apache/maven-source-plugin/compare/maven-source-plugin-2.2.1...maven-source-plugin-3.2.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-24 03:37:11 +00:00
dependabot-preview[bot] fd3ff3f133 Bump jacoco-maven-plugin from 0.8.4 to 0.8.6
Bumps [jacoco-maven-plugin](https://github.com/jacoco/jacoco) from 0.8.4 to 0.8.6.
- [Release notes](https://github.com/jacoco/jacoco/releases)
- [Commits](https://github.com/jacoco/jacoco/compare/v0.8.4...v0.8.6)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-24 03:36:42 +00:00
dependabot-preview[bot] d555eeaf32 Bump maven-jar-plugin from 3.1.0 to 3.2.0
Bumps [maven-jar-plugin](https://github.com/apache/maven-jar-plugin) from 3.1.0 to 3.2.0.
- [Release notes](https://github.com/apache/maven-jar-plugin/releases)
- [Commits](https://github.com/apache/maven-jar-plugin/compare/maven-jar-plugin-3.1.0...maven-jar-plugin-3.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-24 03:36:28 +00:00
Prominence cdc5a4b380 Added tests for forecast functionality. 2021-03-24 02:15:01 +03:00
Alexey Zinchenko 48d0c9479d Merge pull request #9 from Prominence/dependabot/maven/dev/com.fasterxml.jackson.core-jackson-databind-2.12.2
Bump jackson-databind from 2.10.0 to 2.12.2
2021-03-24 01:51:29 +03:00
Alexey Zinchenko 53af39f598 Merge pull request #8 from Prominence/dependabot/maven/dev/org.apache.maven.plugins-maven-gpg-plugin-1.6
Bump maven-gpg-plugin from 1.5 to 1.6
2021-03-24 01:51:15 +03:00
Alexey Zinchenko 02d42c0cd0 Merge pull request #7 from Prominence/dependabot/maven/dev/org.slf4j-slf4j-api-1.7.30
Bump slf4j-api from 1.7.26 to 1.7.30
2021-03-24 01:51:02 +03:00
Alexey Zinchenko c650ba2387 Merge pull request #6 from Prominence/dependabot/maven/dev/org.sonatype.plugins-nexus-staging-maven-plugin-1.6.8
Bump nexus-staging-maven-plugin from 1.6.7 to 1.6.8
2021-03-24 01:50:48 +03:00
Alexey Zinchenko c2138a4503 Merge pull request #5 from Prominence/dependabot/maven/dev/org.apache.maven.plugins-maven-javadoc-plugin-3.2.0
Bump maven-javadoc-plugin from 2.10.4 to 3.2.0
2021-03-24 01:50:25 +03:00
dependabot-preview[bot] 7d3c9ba358 Bump jackson-databind from 2.10.0 to 2.12.2
Bumps [jackson-databind](https://github.com/FasterXML/jackson) from 2.10.0 to 2.12.2.
- [Release notes](https://github.com/FasterXML/jackson/releases)
- [Commits](https://github.com/FasterXML/jackson/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-23 22:47:46 +00:00
dependabot-preview[bot] ba1a5a1016 Bump maven-gpg-plugin from 1.5 to 1.6
Bumps maven-gpg-plugin from 1.5 to 1.6.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-23 22:47:25 +00:00
dependabot-preview[bot] 48d631b747 Bump slf4j-api from 1.7.26 to 1.7.30
Bumps [slf4j-api](https://github.com/qos-ch/slf4j) from 1.7.26 to 1.7.30.
- [Release notes](https://github.com/qos-ch/slf4j/releases)
- [Commits](https://github.com/qos-ch/slf4j/compare/v_1.7.26...v_1.7.30)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-23 22:47:12 +00:00
dependabot-preview[bot] e9b8f00c5a Bump nexus-staging-maven-plugin from 1.6.7 to 1.6.8
Bumps nexus-staging-maven-plugin from 1.6.7 to 1.6.8.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-23 22:46:43 +00:00
dependabot-preview[bot] 4ce9548e7a Bump maven-javadoc-plugin from 2.10.4 to 3.2.0
Bumps [maven-javadoc-plugin](https://github.com/apache/maven-javadoc-plugin) from 2.10.4 to 3.2.0.
- [Release notes](https://github.com/apache/maven-javadoc-plugin/releases)
- [Commits](https://github.com/apache/maven-javadoc-plugin/compare/maven-javadoc-plugin-2.10.4...maven-javadoc-plugin-3.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2021-03-23 22:46:27 +00:00
Prominence a0e289cc2c Rechecked all tests. Fixed API customization possibilities. 2021-03-24 01:32:49 +03:00
Prominence ef138d3bfe Added unit tests. Removed obsolete API parameter. 2021-03-24 00:04:55 +03:00
Prominence ae082d41c1 Clarified version according to semver. 2021-03-23 21:28:20 +03:00
Alexey Zinchenko 6d44b2adec Create codeql-analysis.yml 2021-03-23 21:21:05 +03:00
Prominence 4c7b553b81 Added javadocs and refactoring. 2021-03-23 21:15:35 +03:00
Prominence 7003935869 Updated README. 2021-03-23 20:07:42 +03:00
Prominence 764b1b7189 Changed badge branches. 2021-03-23 11:33:16 +03:00
Prominence 599faf60cc Fixed tests. 2021-03-23 11:27:26 +03:00
Prominence 930776f5c2 Tests refactoring. Got rid of 'assert 'statement. 2021-03-23 01:56:08 +03:00
Prominence 5d6b8c4d97 Rechecked weather API response mapping. Refactoring. 2021-03-22 23:00:30 +03:00
Prominence f7741e1df6 Implemented free-plan weather forecast retrieving. 2021-03-22 01:46:44 +03:00
Prominence ea39441e83 Initial implementation of free-plan forecast retriever. Small refactoring. 2021-03-21 02:32:39 +03:00
Prominence d63de824b3 Refactoring. Checked old implementation. 2021-03-21 00:41:58 +03:00
Prominence 10ba59652b Package reorganizations. Small refactoring. 2021-03-20 23:48:57 +03:00
Alexey Zinchenko 83f3a8e63b Merge pull request #3 from Prominence/dependabot/maven/junit-junit-4.13.1
Bump junit from 4.12 to 4.13.1
2020-10-13 16:52:26 +03:00
dependabot[bot] 4d844a3f0a Bump junit from 4.12 to 4.13.1
Bumps [junit](https://github.com/junit-team/junit4) from 4.12 to 4.13.1.
- [Release notes](https://github.com/junit-team/junit4/releases)
- [Changelog](https://github.com/junit-team/junit4/blob/main/doc/ReleaseNotes4.12.md)
- [Commits](https://github.com/junit-team/junit4/compare/r4.12...r4.13.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-10-13 13:32:38 +00:00
Prominence 2c54375cfe Fixed vulnerability issue. 2019-11-23 22:04:37 +03:00
Prominence 3820409ce8 Fixed vulnerability issue. 2019-10-05 20:14:50 +03:00
Prominence 3845e41bcd Renamed exception. Documentation enhancements. Small refactoring for unit systems. 2019-06-26 20:35:56 +03:00
Prominence babc48bf6c Fixed docs. Removed 'annotations' dependency. 2019-06-25 23:08:51 +03:00
Prominence d3ca16472b Added draft unit tests for model to cover all lines. 2019-06-25 22:59:38 +03:00
Prominence dbc5b08f43 More tests were added. 2019-06-17 22:46:35 +03:00
Prominence 1101ec03db Replaced cobertura with jacoco plugin. 2019-06-17 22:31:16 +03:00
Prominence a9fd20b494 Test commit. 2019-06-17 21:42:56 +03:00
Prominence ba241cdd82 Test commit. 2019-06-17 21:36:29 +03:00
Prominence 42574d1111 Test commit. 2019-06-17 21:34:04 +03:00
Prominence 1e9a335240 Test commit. 2019-06-17 21:13:57 +03:00
Prominence f53dee6953 Test commit. 2019-06-17 21:05:26 +03:00
Prominence 9c4da76b8f Test commit. 2019-06-17 20:59:58 +03:00
Prominence d083a5a07b Added JDK 9, 10 for test purposes. 2019-06-17 20:54:49 +03:00
Prominence 3cb26b7d20 Added slf4j-api. Small refactoring. 2019-06-17 20:32:50 +03:00
Prominence 6e0ddc2a83 Added codecov support. 2019-06-16 14:42:42 +03:00
Prominence c44e97745f Fixed links. 2019-06-16 00:07:34 +03:00
Prominence 134424c21f Added build badge. 2019-06-16 00:05:29 +03:00
Prominence f7ffe3683b Fixed jadadoc plugin execution. 2019-06-16 00:00:24 +03:00
Prominence ef2ac57f32 Added gpg skip. 2019-06-14 23:50:38 +03:00
Prominence 6fb08153f4 Added deploy skip. 2019-06-14 23:47:48 +03:00
Prominence 3195c32f97 Added travis ci configuration. 2019-06-14 23:15:18 +03:00
Prominence 1812a39108 Removed debug output. Fixed async result retrieving in tests. 2019-06-14 21:32:54 +03:00
Prominence aed72a5ab5 Added new draft current weather retrieving implementation. 2019-06-13 23:48:05 +03:00
Prominence 44da350e3c Updated version. 2019-05-29 23:38:40 +03:00
Prominence 39ee5aa38c Updated documentation. 2019-05-29 23:36:29 +03:00
Prominence c6bbf7be90 Changed custom exceptions: now they are uncheked. Fixed several API issues. Added tests. 2019-05-29 22:50:07 +03:00
Prominence 340383afc8 Documentation was updated. 2018-08-04 19:20:15 +03:00
Prominence 6ffa524ce7 Documentation was updated. 2018-08-04 19:18:54 +03:00
Prominence 87fb040169 Shifted to SNAPSHOT version. 2018-08-04 19:17:10 +03:00
Prominence d4db442b63 Version was updated to 1.1. 2018-08-04 19:13:09 +03:00
Prominence 39d56b6782 Implemented Air Pollution retrieving. 2018-08-02 21:34:41 +03:00
Prominence 0487e0f2d0 'System' class was removed. 2018-08-01 21:02:42 +03:00
Prominence c288f71826 Useless imports were removed. 2018-08-01 21:00:11 +03:00
Prominence 157959e537 'System' class was removed. 2018-08-01 20:40:17 +03:00
Prominence 126bfc2d56 Updated documentation. Added useful method. 2018-07-31 23:53:45 +03:00
Prominence e5dee248b6 Implemented UltravioletIndex retrieving. Renamed JSON utulity class. 2018-07-29 18:55:05 +03:00
Prominence 20adced4d7 Typo was fixed. 2018-07-25 23:26:08 +03:00
Prominence 86b0d52586 Documentation was moved into separate files according to version. 2018-07-25 23:25:01 +03:00
Prominence d86b228c6e Implemented DailyForecast requesting. Added 'lombok' dependency. Some refactoring... 2018-07-25 00:19:43 +03:00
Prominence 61eea0b8f6 Switched to SNAPSHOT version. 2018-07-22 22:30:25 +03:00
Alexey Zinchenko d1ee732f91 Update README.md 2018-07-22 22:13:51 +03:00
172 changed files with 22074 additions and 2159 deletions
+67
View File
@@ -0,0 +1,67 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ master ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
schedule:
- cron: '27 20 * * 1'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'java' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
+1 -2
View File
@@ -21,5 +21,4 @@ hs_err_pid*
*.iml *.iml
.idea/ .idea/
target/ target/
**/ApplicationTest.java
+11
View File
@@ -0,0 +1,11 @@
language: java
jdk:
- openjdk8
- openjdk11
install: mvn install -DskipTests -Dgpg.skip -B
script: mvn test -Dmaven.skip.deploy=true -B
after_success:
- bash <(curl -s https://codecov.io/bash)
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2018 Alexey Zinchenko Copyright (c) 2021 Alexey Zinchenko
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+39 -249
View File
@@ -1,266 +1,56 @@
# OpenWeatherMap Java API # OpenWeatherMap Java API [![Build Status][ci-shield]][ci-link] [![codecov][codecov-shield]][codecov-link]
Java API for OpenWeatherMap services. Java API for OpenWeatherMap services.
### Implemented features: ### Implemented features:
Free:
* Current weather data * Current weather data
* 5 day / 3 hour forecast * 5 day / 3-hour forecast
* One Call API
### Will be implemented later: ### Will be implemented later:
* 16 day / daily forecast
* UV Index(beta) Free:
* Air pollution(beta) * Air pollution
* Geocoding API
* Weather Stations
* Weather Triggers
Paid:
* Daily Forecast 16 days
* Hourly Forecast 4 days
* probably others...
### Maven coordinates: ### Maven coordinates:
_Not available yet._ ```xml
<dependency>
### How to use: <groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
Firstly, you need to create the instance of `OpenWeatherMapManager` class: <version>2.1.0</version>
```java </dependency>
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently available methods:
* `getWeatherRequester()`
* `getForecastRequester()`
#### Current weather data
First step is retrieving `WeatherRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
WeatherRequester weatherRequester = openWeatherManager.getWeatherRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
Weather weatherResponse = weatherRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Minsk");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getBase()` | Returns `String` with some internal information. Example: `cmc stations` - from official documentation. |
| `getWeatherInfo()` | Returns `Weather.WeatherInfo` instance that contains information about temperature, pressure and humidity. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getDataCalculationTime()`| Returns `long` value that represents data calculation timestamp. |
| `getWeatherSystemInfo()` | Returns `Weather.WeatherSystemInfo` instance that contains internal information. There is also an information about country, sunrise and sunset time. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getWeatherSystemInfo().getCountry()`. |
| `getWeatherDescription()` | An alias for `getWeatherStates.get(0).getDescription()`. |
| `getDataCalculationDate()`| Returns data calculation time in `Date` representation. |
| `getTemperature()` | An alias for `getWeatherInfo().getTemperature()`. |
| `getTemperatureUnit()` | An alias for `getWeatherInfo().getTemperatureUnit()`. |
| `getPressure()` | An alias for `getWeatherInfo().getPressure()`. |
| `getPressureUnit()` | An alias for `getWeatherInfo().getPressureUnit()`. |
| `getHumidityPercentage()` | An alias for `getWeatherInfo().getHumidity()`. |
| `toString()` | Returns pretty string for the whole available weather information. |
`toString()` output example:
```
City: Minsk(625144). Coordinates: latitude=53.9, longitude=27.56
Country: BY
Sunrise: Sun Jul 15 04:58:27 MSK 2018
Sunset: Sun Jul 15 21:32:19 MSK 2018
Weather: light intensity shower rain
Temperature: 17.0 ℃. Minimum temparature: 17.0 ℃. Maximum temperature: 17.0 ℃
Humidity: 93%
Pressure: 1008 hPa
Wind: 2.0 meter/sec, 20 degrees
Cloudiness: 75%
Data calculation time: Mon Jul 16 00:00:00 MSK 2018
``` ```
#### 5 day / 3 hour forecast ### Gradle coordinates:
First step is retrieving `HourlyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
ForecastRequester forecastRequester = openWeatherManager.getForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
HourlyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests: ```groovy
* `getByCityId(String cityId)` compile('com.github.prominence:openweathermap-api:2.1.0')
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`HourlyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `HourlyForecast.CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `getAverageTemperature()` | Returns average temperature from forecasts. |
| `getMinimumTemperature()` | Returns minimum temperature from forecasts. |
| `getMaximumTemperature()` | Returns maximum temperature from forecasts. |
| `getByMinimumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is minimal. |
| `getByMaximumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is maximal. |
| `getAveragePressure()` | Returns average pressure from forecasts. |
| `getMinimumPressure()` | Returns minimum pressure from forecasts. |
| `getMaximumPressure()` | Returns maximum pressure from forecasts. |
| `getByMinimumPressure()` | Returns `HourlyForecast.Forecast` for the time where pressure is minimal. |
| `getByMaximumPressure()` | Returns `HourlyForecast.Forecast` for the time where pressure is maximal. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`toString()` output example:
```
City: Pruzhany(622997). Coordinates: latitude=52.5582, longitude=24.4567
Country: BY
Forecasts:
Time: Tue Jul 17 00:00:00 MSK 2018. Weather: light rain. Temperature: 16.24 ℃. Minimum temperature: 16.24 ℃. Maximum temperature: 17.36 ℃. Pressure: 997.38 hPa. Sea-level pressure: 1018.59 hPa. Ground-level pressure: 997.38 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 2.85 meter/sec, 324 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 03:00:00 MSK 2018. Weather: moderate rain. Temperature: 16.0 ℃. Minimum temperature: 16.0 ℃. Maximum temperature: 16.83 ℃. Pressure: 996.88 hPa. Sea-level pressure: 1017.86 hPa. Ground-level pressure: 996.88 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 1.86 meter/sec, 349 degrees. Rain(last 3 hrs): 3 mm
Time: Tue Jul 17 06:00:00 MSK 2018. Weather: light rain. Temperature: 15.76 ℃. Minimum temperature: 15.76 ℃. Maximum temperature: 16.31 ℃. Pressure: 996.7 hPa. Sea-level pressure: 1017.72 hPa. Ground-level pressure: 996.7 hPa. Humidity: 94%. Cloudiness: 76%. Wind: 1.62 meter/sec, 113 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 09:00:00 MSK 2018. Weather: light rain. Temperature: 18.23 ℃. Minimum temperature: 18.23 ℃. Maximum temperature: 18.51 ℃. Pressure: 997.17 hPa. Sea-level pressure: 1018.18 hPa. Ground-level pressure: 997.17 hPa. Humidity: 100%. Cloudiness: 76%. Wind: 2.11 meter/sec, 107 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 12:00:00 MSK 2018. Weather: light rain. Temperature: 21.0 ℃. Minimum temperature: 21.0 ℃. Maximum temperature: 21.0 ℃. Pressure: 997.6 hPa. Sea-level pressure: 1018.5 hPa. Ground-level pressure: 997.6 hPa. Humidity: 100%. Cloudiness: 68%. Wind: 2.51 meter/sec, 82 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 15:00:00 MSK 2018. Weather: light rain. Temperature: 21.78 ℃. Minimum temperature: 21.78 ℃. Maximum temperature: 21.78 ℃. Pressure: 997.73 hPa. Sea-level pressure: 1018.66 hPa. Ground-level pressure: 997.73 hPa. Humidity: 92%. Cloudiness: 88%. Wind: 4.05 meter/sec, 78 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 18:00:00 MSK 2018. Weather: light rain. Temperature: 22.9 ℃. Minimum temperature: 22.9 ℃. Maximum temperature: 22.9 ℃. Pressure: 997.66 hPa. Sea-level pressure: 1018.55 hPa. Ground-level pressure: 997.66 hPa. Humidity: 93%. Cloudiness: 68%. Wind: 3.06 meter/sec, 67 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 21:00:00 MSK 2018. Weather: light rain. Temperature: 23.04 ℃. Minimum temperature: 23.04 ℃. Maximum temperature: 23.04 ℃. Pressure: 996.89 hPa. Sea-level pressure: 1017.99 hPa. Ground-level pressure: 996.89 hPa. Humidity: 83%. Cloudiness: 88%. Wind: 3.17 meter/sec, 16 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 00:00:00 MSK 2018. Weather: moderate rain. Temperature: 18.5 ℃. Minimum temperature: 18.5 ℃. Maximum temperature: 18.5 ℃. Pressure: 997.33 hPa. Sea-level pressure: 1018.34 hPa. Ground-level pressure: 997.33 hPa. Humidity: 97%. Cloudiness: 44%. Wind: 3.56 meter/sec, 31 degrees. Rain(last 3 hrs): 7 mm
Time: Wed Jul 18 03:00:00 MSK 2018. Weather: few clouds. Temperature: 18.57 ℃. Minimum temperature: 18.57 ℃. Maximum temperature: 18.57 ℃. Pressure: 996.91 hPa. Sea-level pressure: 1017.87 hPa. Ground-level pressure: 996.91 hPa. Humidity: 95%. Cloudiness: 24%. Wind: 5.26 meter/sec, 44 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 06:00:00 MSK 2018. Weather: few clouds. Temperature: 18.94 ℃. Minimum temperature: 18.94 ℃. Maximum temperature: 18.94 ℃. Pressure: 997.07 hPa. Sea-level pressure: 1018.06 hPa. Ground-level pressure: 997.07 hPa. Humidity: 95%. Cloudiness: 20%. Wind: 4.8 meter/sec, 45 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 09:00:00 MSK 2018. Weather: light rain. Temperature: 20.6 ℃. Minimum temperature: 20.6 ℃. Maximum temperature: 20.6 ℃. Pressure: 997.8 hPa. Sea-level pressure: 1018.66 hPa. Ground-level pressure: 997.8 hPa. Humidity: 97%. Cloudiness: 48%. Wind: 5.56 meter/sec, 54 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 12:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.87 ℃. Minimum temperature: 23.87 ℃. Maximum temperature: 23.87 ℃. Pressure: 998.06 hPa. Sea-level pressure: 1019.05 hPa. Ground-level pressure: 998.06 hPa. Humidity: 88%. Cloudiness: 32%. Wind: 5.86 meter/sec, 52 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 24.67 ℃. Minimum temperature: 24.67 ℃. Maximum temperature: 24.67 ℃. Pressure: 998.51 hPa. Sea-level pressure: 1019.33 hPa. Ground-level pressure: 998.51 hPa. Humidity: 84%. Cloudiness: 36%. Wind: 5.63 meter/sec, 51 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.15 ℃. Minimum temperature: 25.15 ℃. Maximum temperature: 25.15 ℃. Pressure: 998.79 hPa. Sea-level pressure: 1019.64 hPa. Ground-level pressure: 998.79 hPa. Humidity: 78%. Cloudiness: 44%. Wind: 5.47 meter/sec, 38 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.23 ℃. Minimum temperature: 23.23 ℃. Maximum temperature: 23.23 ℃. Pressure: 999.08 hPa. Sea-level pressure: 1020.04 hPa. Ground-level pressure: 999.08 hPa. Humidity: 75%. Cloudiness: 48%. Wind: 4.62 meter/sec, 25 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 20.79 ℃. Minimum temperature: 20.79 ℃. Maximum temperature: 20.79 ℃. Pressure: 999.67 hPa. Sea-level pressure: 1020.68 hPa. Ground-level pressure: 999.67 hPa. Humidity: 76%. Cloudiness: 48%. Wind: 4.29 meter/sec, 13 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 03:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.45 ℃. Minimum temperature: 19.45 ℃. Maximum temperature: 19.45 ℃. Pressure: 999.95 hPa. Sea-level pressure: 1021.02 hPa. Ground-level pressure: 999.95 hPa. Humidity: 80%. Cloudiness: 48%. Wind: 4.22 meter/sec, 17 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 06:00:00 MSK 2018. Weather: light rain. Temperature: 18.9 ℃. Minimum temperature: 18.9 ℃. Maximum temperature: 18.9 ℃. Pressure: 1000.6 hPa. Sea-level pressure: 1021.62 hPa. Ground-level pressure: 1000.6 hPa. Humidity: 83%. Cloudiness: 92%. Wind: 4.43 meter/sec, 10 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 09:00:00 MSK 2018. Weather: light rain. Temperature: 21.37 ℃. Minimum temperature: 21.37 ℃. Maximum temperature: 21.37 ℃. Pressure: 1000.95 hPa. Sea-level pressure: 1022.01 hPa. Ground-level pressure: 1000.95 hPa. Humidity: 87%. Cloudiness: 0%. Wind: 4.36 meter/sec, 6 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.92 ℃. Minimum temperature: 23.92 ℃. Maximum temperature: 23.92 ℃. Pressure: 1001.5 hPa. Sea-level pressure: 1022.43 hPa. Ground-level pressure: 1001.5 hPa. Humidity: 77%. Cloudiness: 0%. Wind: 5.66 meter/sec, 12 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 15:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.7 ℃. Minimum temperature: 23.7 ℃. Maximum temperature: 23.7 ℃. Pressure: 1001.75 hPa. Sea-level pressure: 1022.72 hPa. Ground-level pressure: 1001.75 hPa. Humidity: 72%. Cloudiness: 56%. Wind: 5.87 meter/sec, 349 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 18:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.82 ℃. Minimum temperature: 23.82 ℃. Maximum temperature: 23.82 ℃. Pressure: 1001.55 hPa. Sea-level pressure: 1022.59 hPa. Ground-level pressure: 1001.55 hPa. Humidity: 72%. Cloudiness: 68%. Wind: 5.47 meter/sec, 340 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.22 ℃. Minimum temperature: 22.22 ℃. Maximum temperature: 22.22 ℃. Pressure: 1001.82 hPa. Sea-level pressure: 1022.93 hPa. Ground-level pressure: 1001.82 hPa. Humidity: 67%. Cloudiness: 76%. Wind: 4.12 meter/sec, 333 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.76 ℃. Minimum temperature: 19.76 ℃. Maximum temperature: 19.76 ℃. Pressure: 1001.98 hPa. Sea-level pressure: 1023.13 hPa. Ground-level pressure: 1001.98 hPa. Humidity: 76%. Cloudiness: 32%. Wind: 4.11 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 03:00:00 MSK 2018. Weather: clear sky. Temperature: 17.53 ℃. Minimum temperature: 17.53 ℃. Maximum temperature: 17.53 ℃. Pressure: 1001.93 hPa. Sea-level pressure: 1023.13 hPa. Ground-level pressure: 1001.93 hPa. Humidity: 87%. Cloudiness: 8%. Wind: 4.21 meter/sec, 309 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 16.83 ℃. Minimum temperature: 16.83 ℃. Maximum temperature: 16.83 ℃. Pressure: 1001.79 hPa. Sea-level pressure: 1022.99 hPa. Ground-level pressure: 1001.79 hPa. Humidity: 91%. Cloudiness: 44%. Wind: 3.65 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 09:00:00 MSK 2018. Weather: light rain. Temperature: 19.57 ℃. Minimum temperature: 19.57 ℃. Maximum temperature: 19.57 ℃. Pressure: 1001.34 hPa. Sea-level pressure: 1022.41 hPa. Ground-level pressure: 1001.34 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 4.38 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.5 ℃. Minimum temperature: 23.5 ℃. Maximum temperature: 23.5 ℃. Pressure: 1001.0 hPa. Sea-level pressure: 1021.99 hPa. Ground-level pressure: 1001.0 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 5.36 meter/sec, 299 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.14 ℃. Minimum temperature: 25.14 ℃. Maximum temperature: 25.14 ℃. Pressure: 1000.5 hPa. Sea-level pressure: 1021.51 hPa. Ground-level pressure: 1000.5 hPa. Humidity: 73%. Cloudiness: 32%. Wind: 6.72 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 18:00:00 MSK 2018. Weather: overcast clouds. Temperature: 23.56 ℃. Minimum temperature: 23.56 ℃. Maximum temperature: 23.56 ℃. Pressure: 1000.7 hPa. Sea-level pressure: 1021.58 hPa. Ground-level pressure: 1000.7 hPa. Humidity: 66%. Cloudiness: 88%. Wind: 6.57 meter/sec, 317 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.41 ℃. Minimum temperature: 22.41 ℃. Maximum temperature: 22.41 ℃. Pressure: 1000.64 hPa. Sea-level pressure: 1021.67 hPa. Ground-level pressure: 1000.64 hPa. Humidity: 68%. Cloudiness: 64%. Wind: 4.31 meter/sec, 326 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 00:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.92 ℃. Minimum temperature: 20.92 ℃. Maximum temperature: 20.92 ℃. Pressure: 1001.06 hPa. Sea-level pressure: 1022.14 hPa. Ground-level pressure: 1001.06 hPa. Humidity: 78%. Cloudiness: 68%. Wind: 3.42 meter/sec, 327 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 03:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.28 ℃. Minimum temperature: 20.28 ℃. Maximum temperature: 20.28 ℃. Pressure: 1001.04 hPa. Sea-level pressure: 1022.13 hPa. Ground-level pressure: 1001.04 hPa. Humidity: 78%. Cloudiness: 76%. Wind: 4.27 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.11 ℃. Minimum temperature: 19.11 ℃. Maximum temperature: 19.11 ℃. Pressure: 1001.13 hPa. Sea-level pressure: 1022.28 hPa. Ground-level pressure: 1001.13 hPa. Humidity: 74%. Cloudiness: 32%. Wind: 4.96 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 09:00:00 MSK 2018. Weather: few clouds. Temperature: 20.16 ℃. Minimum temperature: 20.16 ℃. Maximum temperature: 20.16 ℃. Pressure: 1001.43 hPa. Sea-level pressure: 1022.62 hPa. Ground-level pressure: 1001.43 hPa. Humidity: 86%. Cloudiness: 20%. Wind: 5.16 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 12:00:00 MSK 2018. Weather: few clouds. Temperature: 22.37 ℃. Minimum temperature: 22.37 ℃. Maximum temperature: 22.37 ℃. Pressure: 1001.53 hPa. Sea-level pressure: 1022.62 hPa. Ground-level pressure: 1001.53 hPa. Humidity: 88%. Cloudiness: 20%. Wind: 5.56 meter/sec, 307 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.85 ℃. Minimum temperature: 22.85 ℃. Maximum temperature: 22.85 ℃. Pressure: 1001.63 hPa. Sea-level pressure: 1022.65 hPa. Ground-level pressure: 1001.63 hPa. Humidity: 81%. Cloudiness: 44%. Wind: 5.46 meter/sec, 314 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.79 ℃. Minimum temperature: 23.79 ℃. Maximum temperature: 23.79 ℃. Pressure: 1001.53 hPa. Sea-level pressure: 1022.53 hPa. Ground-level pressure: 1001.53 hPa. Humidity: 72%. Cloudiness: 32%. Wind: 5.56 meter/sec, 313 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.56 ℃. Minimum temperature: 22.56 ℃. Maximum temperature: 22.56 ℃. Pressure: 1001.72 hPa. Sea-level pressure: 1022.7 hPa. Ground-level pressure: 1001.72 hPa. Humidity: 66%. Cloudiness: 48%. Wind: 3.96 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
``` ```
`Forecast`'s useful public methods(setters are not listed): ### Documentation
* [OpenWeatherMap Java API - 1.0](docs/Release_1.0.md)
| Method | Description | * [OpenWeatherMap Java API - 1.1](docs/Release_1.1.md)
|-----------------------------|------------------------------------------------------------------------------------------------------------------| * [OpenWeatherMap Java API - 1.2](docs/Release_1.2.md)
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. | * [OpenWeatherMap Java API - 2.0.0](docs/Release_2.0.0.md)
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. | * [OpenWeatherMap Java API - 2.0.1](docs/Release_2.0.1.md)
| `getWeatherInfo()` | Returns `HourlyForecast.WeatherInfo` instance that contains information about temperature, pressure and humidity.| * [OpenWeatherMap Java API - 2.1.0](docs/Release_2.1.0.md)
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. | * [OpenWeatherMap Java API - SNAPSHOT](docs/SNAPSHOT.md)
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSystemInfo()` | Returns `HourlyForecast.ForecastSystemInfo` instance with internal information. |
| `getDt_txt()` | Returns `String` value that represents data calculation time. |
| `toString()` | Returns pretty string for the whole available weather information. |
### Constants and options
#### Accuracy
| Constant | Description |
|--------------------|------------------|
| Accuracy.LIKE | Close result. |
| Accuracy.ACCURATE | Accurate result. |
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### System
| Constant | Description |
|-------------------------------|-----------------------|
|System.OPEN_WEATHER_API_URL | Basic API url. |
|System.OPEN_WEATHER_API_VERSION| Current API version. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow) |
### Dependencies
* com.alibaba:fastjson:1.2.44
### License ### License
MIT MIT
[ci-shield]: https://travis-ci.org/Prominence/openweathermap-java-api.svg?branch=master
[ci-link]: https://travis-ci.org/Prominence/openweathermap-java-api
[codecov-shield]: https://codecov.io/gh/Prominence/openweathermap-java-api/branch/master/graph/badge.svg
[codecov-link]: https://codecov.io/gh/Prominence/openweathermap-java-api
+267
View File
@@ -0,0 +1,267 @@
### Implemented features:
* Current weather data
* 5 day / 3 hour forecast
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>1.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:1.0')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapManager` class:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently available methods:
* `getWeatherRequester()`
* `getForecastRequester()`
#### Current weather data
First step is retrieving `WeatherRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
WeatherRequester weatherRequester = openWeatherManager.getWeatherRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
Weather weatherResponse = weatherRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Minsk");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getBase()` | Returns `String` with some internal information. Example: `cmc stations` - from official documentation. |
| `getWeatherInfo()` | Returns `Weather.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getDataCalculationTime()`| Returns `long` value that represents data calculation timestamp. |
| `getWeatherSystemInfo()` | Returns `Weather.WeatherSystemInfo` instance that contains internal information. There is also an information about country, sunrise and sunset time. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getWeatherSystemInfo().getCountry()`. |
| `getWeatherDescription()` | An alias for `getWeatherStates.get(0).getDescription()`. |
| `getDataCalculationDate()`| Returns data calculation time in `Date` representation. |
| `getTemperature()` | An alias for `getWeatherInfo().getTemperature()`. |
| `getTemperatureUnit()` | An alias for `getWeatherInfo().getTemperatureUnit()`. |
| `getPressure()` | An alias for `getWeatherInfo().getPressure()`. |
| `getPressureUnit()` | An alias for `getWeatherInfo().getPressureUnit()`. |
| `getHumidityPercentage()` | An alias for `getWeatherInfo().getHumidity()`. |
| `toString()` | Returns pretty string for the whole available weather information. |
`toString()` output example:
```
City: Minsk(625144). Coordinates: latitude=53.9, longitude=27.56
Country: BY
Sunrise: Sun Jul 15 04:58:27 MSK 2018
Sunset: Sun Jul 15 21:32:19 MSK 2018
Weather: light intensity shower rain
Temperature: 17.0 ℃. Minimum temparature: 17.0 ℃. Maximum temperature: 17.0 ℃
Humidity: 93%
Pressure: 1008 hPa
Wind: 2.0 meter/sec, 20 degrees
Cloudiness: 75%
Data calculation time: Mon Jul 16 00:00:00 MSK 2018
```
#### 5 day / 3 hour forecast
First step is retrieving `HourlyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
ForecastRequester forecastRequester = openWeatherManager.getForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
HourlyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`HourlyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `HourlyForecast.CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `getAverageTemperature()` | Returns average temperature from forecasts. |
| `getMinimumTemperature()` | Returns minimum temperature from forecasts. |
| `getMaximumTemperature()` | Returns maximum temperature from forecasts. |
| `getByMinimumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is minimal. |
| `getByMaximumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is maximal. |
| `getAveragePressure()` | Returns average atmosphericPressure from forecasts. |
| `getMinimumPressure()` | Returns minimum atmosphericPressure from forecasts. |
| `getMaximumPressure()` | Returns maximum atmosphericPressure from forecasts. |
| `getByMinimumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is minimal. |
| `getByMaximumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is maximal. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`toString()` output example:
```
City: Pruzhany(622997). Coordinates: latitude=52.5582, longitude=24.4567
Country: BY
Forecasts:
Time: Tue Jul 17 00:00:00 MSK 2018. Weather: light rain. Temperature: 16.24 ℃. Minimum temperature: 16.24 ℃. Maximum temperature: 17.36 ℃. Pressure: 997.38 hPa. Sea-level atmosphericPressure: 1018.59 hPa. Ground-level atmosphericPressure: 997.38 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 2.85 meter/sec, 324 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 03:00:00 MSK 2018. Weather: moderate rain. Temperature: 16.0 ℃. Minimum temperature: 16.0 ℃. Maximum temperature: 16.83 ℃. Pressure: 996.88 hPa. Sea-level atmosphericPressure: 1017.86 hPa. Ground-level atmosphericPressure: 996.88 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 1.86 meter/sec, 349 degrees. Rain(last 3 hrs): 3 mm
Time: Tue Jul 17 06:00:00 MSK 2018. Weather: light rain. Temperature: 15.76 ℃. Minimum temperature: 15.76 ℃. Maximum temperature: 16.31 ℃. Pressure: 996.7 hPa. Sea-level atmosphericPressure: 1017.72 hPa. Ground-level atmosphericPressure: 996.7 hPa. Humidity: 94%. Cloudiness: 76%. Wind: 1.62 meter/sec, 113 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 09:00:00 MSK 2018. Weather: light rain. Temperature: 18.23 ℃. Minimum temperature: 18.23 ℃. Maximum temperature: 18.51 ℃. Pressure: 997.17 hPa. Sea-level atmosphericPressure: 1018.18 hPa. Ground-level atmosphericPressure: 997.17 hPa. Humidity: 100%. Cloudiness: 76%. Wind: 2.11 meter/sec, 107 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 12:00:00 MSK 2018. Weather: light rain. Temperature: 21.0 ℃. Minimum temperature: 21.0 ℃. Maximum temperature: 21.0 ℃. Pressure: 997.6 hPa. Sea-level atmosphericPressure: 1018.5 hPa. Ground-level atmosphericPressure: 997.6 hPa. Humidity: 100%. Cloudiness: 68%. Wind: 2.51 meter/sec, 82 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 15:00:00 MSK 2018. Weather: light rain. Temperature: 21.78 ℃. Minimum temperature: 21.78 ℃. Maximum temperature: 21.78 ℃. Pressure: 997.73 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.73 hPa. Humidity: 92%. Cloudiness: 88%. Wind: 4.05 meter/sec, 78 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 18:00:00 MSK 2018. Weather: light rain. Temperature: 22.9 ℃. Minimum temperature: 22.9 ℃. Maximum temperature: 22.9 ℃. Pressure: 997.66 hPa. Sea-level atmosphericPressure: 1018.55 hPa. Ground-level atmosphericPressure: 997.66 hPa. Humidity: 93%. Cloudiness: 68%. Wind: 3.06 meter/sec, 67 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 21:00:00 MSK 2018. Weather: light rain. Temperature: 23.04 ℃. Minimum temperature: 23.04 ℃. Maximum temperature: 23.04 ℃. Pressure: 996.89 hPa. Sea-level atmosphericPressure: 1017.99 hPa. Ground-level atmosphericPressure: 996.89 hPa. Humidity: 83%. Cloudiness: 88%. Wind: 3.17 meter/sec, 16 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 00:00:00 MSK 2018. Weather: moderate rain. Temperature: 18.5 ℃. Minimum temperature: 18.5 ℃. Maximum temperature: 18.5 ℃. Pressure: 997.33 hPa. Sea-level atmosphericPressure: 1018.34 hPa. Ground-level atmosphericPressure: 997.33 hPa. Humidity: 97%. Cloudiness: 44%. Wind: 3.56 meter/sec, 31 degrees. Rain(last 3 hrs): 7 mm
Time: Wed Jul 18 03:00:00 MSK 2018. Weather: few clouds. Temperature: 18.57 ℃. Minimum temperature: 18.57 ℃. Maximum temperature: 18.57 ℃. Pressure: 996.91 hPa. Sea-level atmosphericPressure: 1017.87 hPa. Ground-level atmosphericPressure: 996.91 hPa. Humidity: 95%. Cloudiness: 24%. Wind: 5.26 meter/sec, 44 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 06:00:00 MSK 2018. Weather: few clouds. Temperature: 18.94 ℃. Minimum temperature: 18.94 ℃. Maximum temperature: 18.94 ℃. Pressure: 997.07 hPa. Sea-level atmosphericPressure: 1018.06 hPa. Ground-level atmosphericPressure: 997.07 hPa. Humidity: 95%. Cloudiness: 20%. Wind: 4.8 meter/sec, 45 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 09:00:00 MSK 2018. Weather: light rain. Temperature: 20.6 ℃. Minimum temperature: 20.6 ℃. Maximum temperature: 20.6 ℃. Pressure: 997.8 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.8 hPa. Humidity: 97%. Cloudiness: 48%. Wind: 5.56 meter/sec, 54 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 12:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.87 ℃. Minimum temperature: 23.87 ℃. Maximum temperature: 23.87 ℃. Pressure: 998.06 hPa. Sea-level atmosphericPressure: 1019.05 hPa. Ground-level atmosphericPressure: 998.06 hPa. Humidity: 88%. Cloudiness: 32%. Wind: 5.86 meter/sec, 52 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 24.67 ℃. Minimum temperature: 24.67 ℃. Maximum temperature: 24.67 ℃. Pressure: 998.51 hPa. Sea-level atmosphericPressure: 1019.33 hPa. Ground-level atmosphericPressure: 998.51 hPa. Humidity: 84%. Cloudiness: 36%. Wind: 5.63 meter/sec, 51 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.15 ℃. Minimum temperature: 25.15 ℃. Maximum temperature: 25.15 ℃. Pressure: 998.79 hPa. Sea-level atmosphericPressure: 1019.64 hPa. Ground-level atmosphericPressure: 998.79 hPa. Humidity: 78%. Cloudiness: 44%. Wind: 5.47 meter/sec, 38 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.23 ℃. Minimum temperature: 23.23 ℃. Maximum temperature: 23.23 ℃. Pressure: 999.08 hPa. Sea-level atmosphericPressure: 1020.04 hPa. Ground-level atmosphericPressure: 999.08 hPa. Humidity: 75%. Cloudiness: 48%. Wind: 4.62 meter/sec, 25 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 20.79 ℃. Minimum temperature: 20.79 ℃. Maximum temperature: 20.79 ℃. Pressure: 999.67 hPa. Sea-level atmosphericPressure: 1020.68 hPa. Ground-level atmosphericPressure: 999.67 hPa. Humidity: 76%. Cloudiness: 48%. Wind: 4.29 meter/sec, 13 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 03:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.45 ℃. Minimum temperature: 19.45 ℃. Maximum temperature: 19.45 ℃. Pressure: 999.95 hPa. Sea-level atmosphericPressure: 1021.02 hPa. Ground-level atmosphericPressure: 999.95 hPa. Humidity: 80%. Cloudiness: 48%. Wind: 4.22 meter/sec, 17 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 06:00:00 MSK 2018. Weather: light rain. Temperature: 18.9 ℃. Minimum temperature: 18.9 ℃. Maximum temperature: 18.9 ℃. Pressure: 1000.6 hPa. Sea-level atmosphericPressure: 1021.62 hPa. Ground-level atmosphericPressure: 1000.6 hPa. Humidity: 83%. Cloudiness: 92%. Wind: 4.43 meter/sec, 10 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 09:00:00 MSK 2018. Weather: light rain. Temperature: 21.37 ℃. Minimum temperature: 21.37 ℃. Maximum temperature: 21.37 ℃. Pressure: 1000.95 hPa. Sea-level atmosphericPressure: 1022.01 hPa. Ground-level atmosphericPressure: 1000.95 hPa. Humidity: 87%. Cloudiness: 0%. Wind: 4.36 meter/sec, 6 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.92 ℃. Minimum temperature: 23.92 ℃. Maximum temperature: 23.92 ℃. Pressure: 1001.5 hPa. Sea-level atmosphericPressure: 1022.43 hPa. Ground-level atmosphericPressure: 1001.5 hPa. Humidity: 77%. Cloudiness: 0%. Wind: 5.66 meter/sec, 12 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 15:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.7 ℃. Minimum temperature: 23.7 ℃. Maximum temperature: 23.7 ℃. Pressure: 1001.75 hPa. Sea-level atmosphericPressure: 1022.72 hPa. Ground-level atmosphericPressure: 1001.75 hPa. Humidity: 72%. Cloudiness: 56%. Wind: 5.87 meter/sec, 349 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 18:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.82 ℃. Minimum temperature: 23.82 ℃. Maximum temperature: 23.82 ℃. Pressure: 1001.55 hPa. Sea-level atmosphericPressure: 1022.59 hPa. Ground-level atmosphericPressure: 1001.55 hPa. Humidity: 72%. Cloudiness: 68%. Wind: 5.47 meter/sec, 340 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.22 ℃. Minimum temperature: 22.22 ℃. Maximum temperature: 22.22 ℃. Pressure: 1001.82 hPa. Sea-level atmosphericPressure: 1022.93 hPa. Ground-level atmosphericPressure: 1001.82 hPa. Humidity: 67%. Cloudiness: 76%. Wind: 4.12 meter/sec, 333 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.76 ℃. Minimum temperature: 19.76 ℃. Maximum temperature: 19.76 ℃. Pressure: 1001.98 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.98 hPa. Humidity: 76%. Cloudiness: 32%. Wind: 4.11 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 03:00:00 MSK 2018. Weather: clear sky. Temperature: 17.53 ℃. Minimum temperature: 17.53 ℃. Maximum temperature: 17.53 ℃. Pressure: 1001.93 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.93 hPa. Humidity: 87%. Cloudiness: 8%. Wind: 4.21 meter/sec, 309 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 16.83 ℃. Minimum temperature: 16.83 ℃. Maximum temperature: 16.83 ℃. Pressure: 1001.79 hPa. Sea-level atmosphericPressure: 1022.99 hPa. Ground-level atmosphericPressure: 1001.79 hPa. Humidity: 91%. Cloudiness: 44%. Wind: 3.65 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 09:00:00 MSK 2018. Weather: light rain. Temperature: 19.57 ℃. Minimum temperature: 19.57 ℃. Maximum temperature: 19.57 ℃. Pressure: 1001.34 hPa. Sea-level atmosphericPressure: 1022.41 hPa. Ground-level atmosphericPressure: 1001.34 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 4.38 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.5 ℃. Minimum temperature: 23.5 ℃. Maximum temperature: 23.5 ℃. Pressure: 1001.0 hPa. Sea-level atmosphericPressure: 1021.99 hPa. Ground-level atmosphericPressure: 1001.0 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 5.36 meter/sec, 299 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.14 ℃. Minimum temperature: 25.14 ℃. Maximum temperature: 25.14 ℃. Pressure: 1000.5 hPa. Sea-level atmosphericPressure: 1021.51 hPa. Ground-level atmosphericPressure: 1000.5 hPa. Humidity: 73%. Cloudiness: 32%. Wind: 6.72 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 18:00:00 MSK 2018. Weather: overcast clouds. Temperature: 23.56 ℃. Minimum temperature: 23.56 ℃. Maximum temperature: 23.56 ℃. Pressure: 1000.7 hPa. Sea-level atmosphericPressure: 1021.58 hPa. Ground-level atmosphericPressure: 1000.7 hPa. Humidity: 66%. Cloudiness: 88%. Wind: 6.57 meter/sec, 317 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.41 ℃. Minimum temperature: 22.41 ℃. Maximum temperature: 22.41 ℃. Pressure: 1000.64 hPa. Sea-level atmosphericPressure: 1021.67 hPa. Ground-level atmosphericPressure: 1000.64 hPa. Humidity: 68%. Cloudiness: 64%. Wind: 4.31 meter/sec, 326 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 00:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.92 ℃. Minimum temperature: 20.92 ℃. Maximum temperature: 20.92 ℃. Pressure: 1001.06 hPa. Sea-level atmosphericPressure: 1022.14 hPa. Ground-level atmosphericPressure: 1001.06 hPa. Humidity: 78%. Cloudiness: 68%. Wind: 3.42 meter/sec, 327 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 03:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.28 ℃. Minimum temperature: 20.28 ℃. Maximum temperature: 20.28 ℃. Pressure: 1001.04 hPa. Sea-level atmosphericPressure: 1022.13 hPa. Ground-level atmosphericPressure: 1001.04 hPa. Humidity: 78%. Cloudiness: 76%. Wind: 4.27 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.11 ℃. Minimum temperature: 19.11 ℃. Maximum temperature: 19.11 ℃. Pressure: 1001.13 hPa. Sea-level atmosphericPressure: 1022.28 hPa. Ground-level atmosphericPressure: 1001.13 hPa. Humidity: 74%. Cloudiness: 32%. Wind: 4.96 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 09:00:00 MSK 2018. Weather: few clouds. Temperature: 20.16 ℃. Minimum temperature: 20.16 ℃. Maximum temperature: 20.16 ℃. Pressure: 1001.43 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.43 hPa. Humidity: 86%. Cloudiness: 20%. Wind: 5.16 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 12:00:00 MSK 2018. Weather: few clouds. Temperature: 22.37 ℃. Minimum temperature: 22.37 ℃. Maximum temperature: 22.37 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 88%. Cloudiness: 20%. Wind: 5.56 meter/sec, 307 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.85 ℃. Minimum temperature: 22.85 ℃. Maximum temperature: 22.85 ℃. Pressure: 1001.63 hPa. Sea-level atmosphericPressure: 1022.65 hPa. Ground-level atmosphericPressure: 1001.63 hPa. Humidity: 81%. Cloudiness: 44%. Wind: 5.46 meter/sec, 314 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.79 ℃. Minimum temperature: 23.79 ℃. Maximum temperature: 23.79 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.53 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 72%. Cloudiness: 32%. Wind: 5.56 meter/sec, 313 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.56 ℃. Minimum temperature: 22.56 ℃. Maximum temperature: 22.56 ℃. Pressure: 1001.72 hPa. Sea-level atmosphericPressure: 1022.7 hPa. Ground-level atmosphericPressure: 1001.72 hPa. Humidity: 66%. Cloudiness: 48%. Wind: 3.96 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
```
`Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|------------------------------------------------------------------------------------------------------------------|
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. |
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. |
| `getWeatherInfo()` | Returns `HourlyForecast.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity.|
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSystemInfo()` | Returns `HourlyForecast.ForecastSystemInfo` instance with internal information. |
| `getDt_txt()` | Returns `String` value that represents data calculation time. |
| `toString()` | Returns pretty string for the whole available weather information. |
### Constants and options
#### Accuracy
| Constant | Description |
|--------------------|------------------|
| Accuracy.LIKE | Close result. |
| Accuracy.ACCURATE | Accurate result. |
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### System
| Constant | Description |
|-------------------------------|-----------------------|
|System.OPEN_WEATHER_API_URL | Basic API url. |
|System.OPEN_WEATHER_API_VERSION| Current API version. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow) |
### Dependencies
* com.alibaba:fastjson:1.2.44
+390
View File
@@ -0,0 +1,390 @@
### Implemented features:
* Current weather data
* 5 day / 3 hour forecast
* 16 day / daily forecast
* UV Index
* Air Pollution
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>1.1</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:1.1')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapManager` class:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently available methods:
* `getWeatherRequester()`
* `getHourlyForecastRequester()`
* `getDailyForecastRequester()`
* `getUltravioletIndexRequester()`
* `getAirPollutionRequester()`
#### Current weather data
First step is retrieving `WeatherRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
WeatherRequester weatherRequester = openWeatherManager.getWeatherRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
Weather weatherResponse = weatherRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Minsk");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getBase()` | Returns `String` with some internal information. Example: `cmc stations` - from official documentation. |
| `getWeatherInfo()` | Returns `Weather.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getDataCalculationTime()`| Returns `long` value that represents data calculation timestamp. |
| `getWeatherSystemInfo()` | Returns `Weather.WeatherSystemInfo` instance that contains internal information. There is also an information about country, sunrise and sunset time. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getWeatherSystemInfo().getCountry()`. |
| `getWeatherDescription()` | An alias for `getWeatherStates.get(0).getDescription()`. |
| `getDataCalculationDate()`| Returns data calculation time in `Date` representation. |
| `getTemperature()` | An alias for `getWeatherInfo().getTemperature()`. |
| `getTemperatureUnit()` | An alias for `getWeatherInfo().getTemperatureUnit()`. |
| `getPressure()` | An alias for `getWeatherInfo().getPressure()`. |
| `getPressureUnit()` | An alias for `getWeatherInfo().getPressureUnit()`. |
| `getHumidityPercentage()` | An alias for `getWeatherInfo().getHumidity()`. |
| `toString()` | Returns pretty string for the whole available weather information. |
`toString()` output example:
```
City: Minsk(625144). Coordinates: latitude=53.9, longitude=27.56
Country: BY
Sunrise: Sun Jul 15 04:58:27 MSK 2018
Sunset: Sun Jul 15 21:32:19 MSK 2018
Weather: light intensity shower rain
Temperature: 17.0 ℃. Minimum temparature: 17.0 ℃. Maximum temperature: 17.0 ℃
Humidity: 93%
Pressure: 1008 hPa
Wind: 2.0 meter/sec, 20 degrees
Cloudiness: 75%
Data calculation time: Mon Jul 16 00:00:00 MSK 2018
```
#### 5 day / 3 hour forecast
First step is retrieving `HourlyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
HourlyForecastRequester forecastRequester = openWeatherManager.getHourlyForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
HourlyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`HourlyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `getAverageTemperature()` | Returns average temperature from forecasts. |
| `getMinimumTemperature()` | Returns minimum temperature from forecasts. |
| `getMaximumTemperature()` | Returns maximum temperature from forecasts. |
| `getByMinimumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is minimal. |
| `getByMaximumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is maximal. |
| `getAveragePressure()` | Returns average atmosphericPressure from forecasts. |
| `getMinimumPressure()` | Returns minimum atmosphericPressure from forecasts. |
| `getMaximumPressure()` | Returns maximum atmosphericPressure from forecasts. |
| `getByMinimumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is minimal. |
| `getByMaximumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is maximal. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`toString()` output example:
```
City: Pruzhany(622997). Coordinates: latitude=52.5582, longitude=24.4567
Country: BY
Forecasts:
Time: Tue Jul 17 00:00:00 MSK 2018. Weather: light rain. Temperature: 16.24 ℃. Minimum temperature: 16.24 ℃. Maximum temperature: 17.36 ℃. Pressure: 997.38 hPa. Sea-level atmosphericPressure: 1018.59 hPa. Ground-level atmosphericPressure: 997.38 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 2.85 meter/sec, 324 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 03:00:00 MSK 2018. Weather: moderate rain. Temperature: 16.0 ℃. Minimum temperature: 16.0 ℃. Maximum temperature: 16.83 ℃. Pressure: 996.88 hPa. Sea-level atmosphericPressure: 1017.86 hPa. Ground-level atmosphericPressure: 996.88 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 1.86 meter/sec, 349 degrees. Rain(last 3 hrs): 3 mm
Time: Tue Jul 17 06:00:00 MSK 2018. Weather: light rain. Temperature: 15.76 ℃. Minimum temperature: 15.76 ℃. Maximum temperature: 16.31 ℃. Pressure: 996.7 hPa. Sea-level atmosphericPressure: 1017.72 hPa. Ground-level atmosphericPressure: 996.7 hPa. Humidity: 94%. Cloudiness: 76%. Wind: 1.62 meter/sec, 113 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 09:00:00 MSK 2018. Weather: light rain. Temperature: 18.23 ℃. Minimum temperature: 18.23 ℃. Maximum temperature: 18.51 ℃. Pressure: 997.17 hPa. Sea-level atmosphericPressure: 1018.18 hPa. Ground-level atmosphericPressure: 997.17 hPa. Humidity: 100%. Cloudiness: 76%. Wind: 2.11 meter/sec, 107 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 12:00:00 MSK 2018. Weather: light rain. Temperature: 21.0 ℃. Minimum temperature: 21.0 ℃. Maximum temperature: 21.0 ℃. Pressure: 997.6 hPa. Sea-level atmosphericPressure: 1018.5 hPa. Ground-level atmosphericPressure: 997.6 hPa. Humidity: 100%. Cloudiness: 68%. Wind: 2.51 meter/sec, 82 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 15:00:00 MSK 2018. Weather: light rain. Temperature: 21.78 ℃. Minimum temperature: 21.78 ℃. Maximum temperature: 21.78 ℃. Pressure: 997.73 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.73 hPa. Humidity: 92%. Cloudiness: 88%. Wind: 4.05 meter/sec, 78 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 18:00:00 MSK 2018. Weather: light rain. Temperature: 22.9 ℃. Minimum temperature: 22.9 ℃. Maximum temperature: 22.9 ℃. Pressure: 997.66 hPa. Sea-level atmosphericPressure: 1018.55 hPa. Ground-level atmosphericPressure: 997.66 hPa. Humidity: 93%. Cloudiness: 68%. Wind: 3.06 meter/sec, 67 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 21:00:00 MSK 2018. Weather: light rain. Temperature: 23.04 ℃. Minimum temperature: 23.04 ℃. Maximum temperature: 23.04 ℃. Pressure: 996.89 hPa. Sea-level atmosphericPressure: 1017.99 hPa. Ground-level atmosphericPressure: 996.89 hPa. Humidity: 83%. Cloudiness: 88%. Wind: 3.17 meter/sec, 16 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 00:00:00 MSK 2018. Weather: moderate rain. Temperature: 18.5 ℃. Minimum temperature: 18.5 ℃. Maximum temperature: 18.5 ℃. Pressure: 997.33 hPa. Sea-level atmosphericPressure: 1018.34 hPa. Ground-level atmosphericPressure: 997.33 hPa. Humidity: 97%. Cloudiness: 44%. Wind: 3.56 meter/sec, 31 degrees. Rain(last 3 hrs): 7 mm
Time: Wed Jul 18 03:00:00 MSK 2018. Weather: few clouds. Temperature: 18.57 ℃. Minimum temperature: 18.57 ℃. Maximum temperature: 18.57 ℃. Pressure: 996.91 hPa. Sea-level atmosphericPressure: 1017.87 hPa. Ground-level atmosphericPressure: 996.91 hPa. Humidity: 95%. Cloudiness: 24%. Wind: 5.26 meter/sec, 44 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 06:00:00 MSK 2018. Weather: few clouds. Temperature: 18.94 ℃. Minimum temperature: 18.94 ℃. Maximum temperature: 18.94 ℃. Pressure: 997.07 hPa. Sea-level atmosphericPressure: 1018.06 hPa. Ground-level atmosphericPressure: 997.07 hPa. Humidity: 95%. Cloudiness: 20%. Wind: 4.8 meter/sec, 45 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 09:00:00 MSK 2018. Weather: light rain. Temperature: 20.6 ℃. Minimum temperature: 20.6 ℃. Maximum temperature: 20.6 ℃. Pressure: 997.8 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.8 hPa. Humidity: 97%. Cloudiness: 48%. Wind: 5.56 meter/sec, 54 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 12:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.87 ℃. Minimum temperature: 23.87 ℃. Maximum temperature: 23.87 ℃. Pressure: 998.06 hPa. Sea-level atmosphericPressure: 1019.05 hPa. Ground-level atmosphericPressure: 998.06 hPa. Humidity: 88%. Cloudiness: 32%. Wind: 5.86 meter/sec, 52 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 24.67 ℃. Minimum temperature: 24.67 ℃. Maximum temperature: 24.67 ℃. Pressure: 998.51 hPa. Sea-level atmosphericPressure: 1019.33 hPa. Ground-level atmosphericPressure: 998.51 hPa. Humidity: 84%. Cloudiness: 36%. Wind: 5.63 meter/sec, 51 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.15 ℃. Minimum temperature: 25.15 ℃. Maximum temperature: 25.15 ℃. Pressure: 998.79 hPa. Sea-level atmosphericPressure: 1019.64 hPa. Ground-level atmosphericPressure: 998.79 hPa. Humidity: 78%. Cloudiness: 44%. Wind: 5.47 meter/sec, 38 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.23 ℃. Minimum temperature: 23.23 ℃. Maximum temperature: 23.23 ℃. Pressure: 999.08 hPa. Sea-level atmosphericPressure: 1020.04 hPa. Ground-level atmosphericPressure: 999.08 hPa. Humidity: 75%. Cloudiness: 48%. Wind: 4.62 meter/sec, 25 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 20.79 ℃. Minimum temperature: 20.79 ℃. Maximum temperature: 20.79 ℃. Pressure: 999.67 hPa. Sea-level atmosphericPressure: 1020.68 hPa. Ground-level atmosphericPressure: 999.67 hPa. Humidity: 76%. Cloudiness: 48%. Wind: 4.29 meter/sec, 13 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 03:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.45 ℃. Minimum temperature: 19.45 ℃. Maximum temperature: 19.45 ℃. Pressure: 999.95 hPa. Sea-level atmosphericPressure: 1021.02 hPa. Ground-level atmosphericPressure: 999.95 hPa. Humidity: 80%. Cloudiness: 48%. Wind: 4.22 meter/sec, 17 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 06:00:00 MSK 2018. Weather: light rain. Temperature: 18.9 ℃. Minimum temperature: 18.9 ℃. Maximum temperature: 18.9 ℃. Pressure: 1000.6 hPa. Sea-level atmosphericPressure: 1021.62 hPa. Ground-level atmosphericPressure: 1000.6 hPa. Humidity: 83%. Cloudiness: 92%. Wind: 4.43 meter/sec, 10 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 09:00:00 MSK 2018. Weather: light rain. Temperature: 21.37 ℃. Minimum temperature: 21.37 ℃. Maximum temperature: 21.37 ℃. Pressure: 1000.95 hPa. Sea-level atmosphericPressure: 1022.01 hPa. Ground-level atmosphericPressure: 1000.95 hPa. Humidity: 87%. Cloudiness: 0%. Wind: 4.36 meter/sec, 6 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.92 ℃. Minimum temperature: 23.92 ℃. Maximum temperature: 23.92 ℃. Pressure: 1001.5 hPa. Sea-level atmosphericPressure: 1022.43 hPa. Ground-level atmosphericPressure: 1001.5 hPa. Humidity: 77%. Cloudiness: 0%. Wind: 5.66 meter/sec, 12 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 15:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.7 ℃. Minimum temperature: 23.7 ℃. Maximum temperature: 23.7 ℃. Pressure: 1001.75 hPa. Sea-level atmosphericPressure: 1022.72 hPa. Ground-level atmosphericPressure: 1001.75 hPa. Humidity: 72%. Cloudiness: 56%. Wind: 5.87 meter/sec, 349 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 18:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.82 ℃. Minimum temperature: 23.82 ℃. Maximum temperature: 23.82 ℃. Pressure: 1001.55 hPa. Sea-level atmosphericPressure: 1022.59 hPa. Ground-level atmosphericPressure: 1001.55 hPa. Humidity: 72%. Cloudiness: 68%. Wind: 5.47 meter/sec, 340 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.22 ℃. Minimum temperature: 22.22 ℃. Maximum temperature: 22.22 ℃. Pressure: 1001.82 hPa. Sea-level atmosphericPressure: 1022.93 hPa. Ground-level atmosphericPressure: 1001.82 hPa. Humidity: 67%. Cloudiness: 76%. Wind: 4.12 meter/sec, 333 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.76 ℃. Minimum temperature: 19.76 ℃. Maximum temperature: 19.76 ℃. Pressure: 1001.98 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.98 hPa. Humidity: 76%. Cloudiness: 32%. Wind: 4.11 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 03:00:00 MSK 2018. Weather: clear sky. Temperature: 17.53 ℃. Minimum temperature: 17.53 ℃. Maximum temperature: 17.53 ℃. Pressure: 1001.93 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.93 hPa. Humidity: 87%. Cloudiness: 8%. Wind: 4.21 meter/sec, 309 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 16.83 ℃. Minimum temperature: 16.83 ℃. Maximum temperature: 16.83 ℃. Pressure: 1001.79 hPa. Sea-level atmosphericPressure: 1022.99 hPa. Ground-level atmosphericPressure: 1001.79 hPa. Humidity: 91%. Cloudiness: 44%. Wind: 3.65 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 09:00:00 MSK 2018. Weather: light rain. Temperature: 19.57 ℃. Minimum temperature: 19.57 ℃. Maximum temperature: 19.57 ℃. Pressure: 1001.34 hPa. Sea-level atmosphericPressure: 1022.41 hPa. Ground-level atmosphericPressure: 1001.34 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 4.38 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.5 ℃. Minimum temperature: 23.5 ℃. Maximum temperature: 23.5 ℃. Pressure: 1001.0 hPa. Sea-level atmosphericPressure: 1021.99 hPa. Ground-level atmosphericPressure: 1001.0 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 5.36 meter/sec, 299 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.14 ℃. Minimum temperature: 25.14 ℃. Maximum temperature: 25.14 ℃. Pressure: 1000.5 hPa. Sea-level atmosphericPressure: 1021.51 hPa. Ground-level atmosphericPressure: 1000.5 hPa. Humidity: 73%. Cloudiness: 32%. Wind: 6.72 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 18:00:00 MSK 2018. Weather: overcast clouds. Temperature: 23.56 ℃. Minimum temperature: 23.56 ℃. Maximum temperature: 23.56 ℃. Pressure: 1000.7 hPa. Sea-level atmosphericPressure: 1021.58 hPa. Ground-level atmosphericPressure: 1000.7 hPa. Humidity: 66%. Cloudiness: 88%. Wind: 6.57 meter/sec, 317 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.41 ℃. Minimum temperature: 22.41 ℃. Maximum temperature: 22.41 ℃. Pressure: 1000.64 hPa. Sea-level atmosphericPressure: 1021.67 hPa. Ground-level atmosphericPressure: 1000.64 hPa. Humidity: 68%. Cloudiness: 64%. Wind: 4.31 meter/sec, 326 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 00:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.92 ℃. Minimum temperature: 20.92 ℃. Maximum temperature: 20.92 ℃. Pressure: 1001.06 hPa. Sea-level atmosphericPressure: 1022.14 hPa. Ground-level atmosphericPressure: 1001.06 hPa. Humidity: 78%. Cloudiness: 68%. Wind: 3.42 meter/sec, 327 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 03:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.28 ℃. Minimum temperature: 20.28 ℃. Maximum temperature: 20.28 ℃. Pressure: 1001.04 hPa. Sea-level atmosphericPressure: 1022.13 hPa. Ground-level atmosphericPressure: 1001.04 hPa. Humidity: 78%. Cloudiness: 76%. Wind: 4.27 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.11 ℃. Minimum temperature: 19.11 ℃. Maximum temperature: 19.11 ℃. Pressure: 1001.13 hPa. Sea-level atmosphericPressure: 1022.28 hPa. Ground-level atmosphericPressure: 1001.13 hPa. Humidity: 74%. Cloudiness: 32%. Wind: 4.96 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 09:00:00 MSK 2018. Weather: few clouds. Temperature: 20.16 ℃. Minimum temperature: 20.16 ℃. Maximum temperature: 20.16 ℃. Pressure: 1001.43 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.43 hPa. Humidity: 86%. Cloudiness: 20%. Wind: 5.16 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 12:00:00 MSK 2018. Weather: few clouds. Temperature: 22.37 ℃. Minimum temperature: 22.37 ℃. Maximum temperature: 22.37 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 88%. Cloudiness: 20%. Wind: 5.56 meter/sec, 307 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.85 ℃. Minimum temperature: 22.85 ℃. Maximum temperature: 22.85 ℃. Pressure: 1001.63 hPa. Sea-level atmosphericPressure: 1022.65 hPa. Ground-level atmosphericPressure: 1001.63 hPa. Humidity: 81%. Cloudiness: 44%. Wind: 5.46 meter/sec, 314 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.79 ℃. Minimum temperature: 23.79 ℃. Maximum temperature: 23.79 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.53 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 72%. Cloudiness: 32%. Wind: 5.56 meter/sec, 313 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.56 ℃. Minimum temperature: 22.56 ℃. Maximum temperature: 22.56 ℃. Pressure: 1001.72 hPa. Sea-level atmosphericPressure: 1022.7 hPa. Ground-level atmosphericPressure: 1001.72 hPa. Humidity: 66%. Cloudiness: 48%. Wind: 3.96 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
```
`HourlyForecast.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|------------------------------------------------------------------------------------------------------------------|
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. |
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. |
| `getWeatherInfo()` | Returns `HourlyForecast.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity.|
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSystemInfo()` | Returns `HourlyForecast.ForecastSystemInfo` instance with internal information. |
| `getDt_txt()` | Returns `String` value that represents data calculation time. |
| `toString()` | Returns pretty string for the whole available forecast information. |
#### 16 day / daily forecast
First step is retrieving `DailyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
DailyForecastRequester forecastRequester = openWeatherManager.getDailyForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
DailyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`DailyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`DailyForecast.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|------------------------------------------------------------------------------------------------------------------|
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. |
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. |
| `getTemperature()` | Returns `DailyForecast.Forecast.Temperature` instance that contains information about temperature(avg, min, max).|
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getCloudiness()` | Returns *cloudiness* percentage information. |
| `getHumidity()` | Returns *humidity* percentage information. |
| `getWindSpeed()` | Returns wind's speed. |
| `getWindDegrees()` | Returns wind's degree. |
| `getWindUnit()` | Returns wind's unit. |
| `getPressure()` | Returns atmosphericPressure value. |
| `getPressureUnit()` | Returns atmosphericPressure's unit. |
| `toString()` | Returns pretty string for the whole available forecast information. |
#### UV Index
First step is retrieving `UltravioletIndexRequester` instance:
```java
OpenWeatherMapManager openWeatherMapManager = new OpenWeatherMapManager(API_TOKEN);
UltravioletIndexRequester requester = openWeatherMapManager.getUltravioletIndexRequester();
```
after you need to set coordinates and execute appropriate request:
```
UltravioletIndex uvResponse = requester
.setCoodrinates(55.33f, 24.27f)
.getCurrentUVIndex();
```
Available requests:
* `getCurrentUVIndex()`
* `getUVIndexForecast(int amountOfDays)`
* `getUVIndexByPeriod(Date from, Date to)`
`UltravioletIndex`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------|
| `getLatitude()` | Returns latitude. |
| `getLongitude()` | Returns longitude. |
| `getDateISO()` | Returns ISO date in String representation. |
| `getDateTimestamp()` | Returns date timestamp. |
| `getValue()` | Returns UV value. |
| `getCalculationDate()` | Returns date in Date representation`. |
| `toString()` | Returns pretty string for the whole available UV information. |
`toString()` output example:
```
Date: Tue Jul 31 15:00:00 MSK 2018, Ultraviolet value: 6.230000
```
#### Air pollution
First step is retrieving `AirPollutionRequester` instance:
```java
OpenWeatherMapManager openWeatherMapManager = new OpenWeatherMapManager(API_TOKEN);
AirPollutionRequester requester = openWeatherMapManager.getAirPollutionRequester();
```
after you need to set coordinates, time frame, date and execute appropriate request:
```
AirPollution airPollutionResponse = forecastRequester
.setCoordinates(0.0f, 10.0f)
.setTimeFrame(TimeFrame.YEAR)
.setDate(new Date())
.retrieve();
```
Available requests:
* `retrieve()`
`AirPollution`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------|
| `getCoordinates()` | Returns `Coordinates` instance. |
| `getLongitude()` | Returns longitude. |
| `airPollutionInfo()` | Returns list of `AirPollution.AirPollutionInfo` instances. |
| `toString()` | Returns pretty string for the whole available air pollution information. |
`toString()` output example:
```
AirPollution[Date: Tue Jul 24 01:04:40 MSK 2018; Coordinates: latitude=0.0, longitude=9.9955]
[Value: 8.0347114E-8, Value: 9.5041536E-8, Value: 7.7667146E-8, Value: 7.251491E-8, Value: 5.899763E-8, Value: 1.9186361E-8, Value: 1.729535E-8, Value: 1.25645805E-8, Value: 3.0852514E-9]
```
### Constants and options
#### Accuracy
| Constant | Description |
|--------------------|------------------|
| Accuracy.LIKE | Close result. |
| Accuracy.ACCURATE | Accurate result. |
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow) |
### Dependencies
* com.alibaba:fastjson:1.2.44
* org.projectlombok:lombok:1.18.0 (*provided*)
+402
View File
@@ -0,0 +1,402 @@
### Implemented features:
* Current weather data
* 5 day / 3 hour forecast
* 16 day / daily forecast
* UV Index
* Air Pollution
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>1.2</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:1.2')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapManager` class:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently available methods:
* `getWeatherRequester()`
* `getHourlyForecastRequester()`
* `getDailyForecastRequester()`
* `getUltravioletIndexRequester(...)`
* `getAirPollutionRequester(...)`
#### Current weather data
First step is retrieving `WeatherRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
WeatherRequester weatherRequester = openWeatherManager.getWeatherRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
Weather weatherResponse = weatherRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Minsk");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getBase()` | Returns `String` with some internal information. Example: `cmc stations` - from official documentation. |
| `getWeatherInfo()` | Returns `Weather.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getDataCalculationTime()`| Returns `long` value that represents data calculation timestamp. |
| `getWeatherSystemInfo()` | Returns `Weather.WeatherSystemInfo` instance that contains internal information. There is also an information about country, sunrise and sunset time. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getWeatherSystemInfo().getCountry()`. |
| `getWeatherDescription()` | An alias for `getWeatherStates.get(0).getDescription()`. |
| `getDataCalculationDate()`| Returns data calculation time in `Date` representation. |
| `getTemperature()` | An alias for `getWeatherInfo().getTemperature()`. |
| `getTemperatureUnit()` | An alias for `getWeatherInfo().getTemperatureUnit()`. |
| `getPressure()` | An alias for `getWeatherInfo().getPressure()`. |
| `getPressureUnit()` | An alias for `getWeatherInfo().getPressureUnit()`. |
| `getHumidityPercentage()` | An alias for `getWeatherInfo().getHumidity()`. |
| `toString()` | Returns pretty string for the whole available weather information. |
`toString()` output example:
```
City: Minsk(625144). Coordinates: latitude=53.9, longitude=27.56
Country: BY
Sunrise: Sun Jul 15 04:58:27 MSK 2018
Sunset: Sun Jul 15 21:32:19 MSK 2018
Weather: light intensity shower rain
Temperature: 17.0 ℃. Minimum temparature: 17.0 ℃. Maximum temperature: 17.0 ℃
Humidity: 93%
Pressure: 1008 hPa
Wind: 2.0 meter/sec, 20 degrees
Cloudiness: 75%
Data calculation time: Mon Jul 16 00:00:00 MSK 2018
```
#### 5 day / 3 hour forecast
First step is retrieving `HourlyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
HourlyForecastRequester forecastRequester = openWeatherManager.getHourlyForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
HourlyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`HourlyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `getAverageTemperature()` | Returns average temperature from forecasts. |
| `getMinimumTemperature()` | Returns minimum temperature from forecasts. |
| `getMaximumTemperature()` | Returns maximum temperature from forecasts. |
| `getByMinimumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is minimal. |
| `getByMaximumTemperature()` | Returns `HourlyForecast.Forecast` for the time where temperature is maximal. |
| `getAveragePressure()` | Returns average atmosphericPressure from forecasts. |
| `getMinimumPressure()` | Returns minimum atmosphericPressure from forecasts. |
| `getMaximumPressure()` | Returns maximum atmosphericPressure from forecasts. |
| `getByMinimumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is minimal. |
| `getByMaximumPressure()` | Returns `HourlyForecast.Forecast` for the time where atmosphericPressure is maximal. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`toString()` output example:
```
City: Pruzhany(622997). Coordinates: latitude=52.5582, longitude=24.4567
Country: BY
Forecasts:
Time: Tue Jul 17 00:00:00 MSK 2018. Weather: light rain. Temperature: 16.24 ℃. Minimum temperature: 16.24 ℃. Maximum temperature: 17.36 ℃. Pressure: 997.38 hPa. Sea-level atmosphericPressure: 1018.59 hPa. Ground-level atmosphericPressure: 997.38 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 2.85 meter/sec, 324 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 03:00:00 MSK 2018. Weather: moderate rain. Temperature: 16.0 ℃. Minimum temperature: 16.0 ℃. Maximum temperature: 16.83 ℃. Pressure: 996.88 hPa. Sea-level atmosphericPressure: 1017.86 hPa. Ground-level atmosphericPressure: 996.88 hPa. Humidity: 99%. Cloudiness: 80%. Wind: 1.86 meter/sec, 349 degrees. Rain(last 3 hrs): 3 mm
Time: Tue Jul 17 06:00:00 MSK 2018. Weather: light rain. Temperature: 15.76 ℃. Minimum temperature: 15.76 ℃. Maximum temperature: 16.31 ℃. Pressure: 996.7 hPa. Sea-level atmosphericPressure: 1017.72 hPa. Ground-level atmosphericPressure: 996.7 hPa. Humidity: 94%. Cloudiness: 76%. Wind: 1.62 meter/sec, 113 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 09:00:00 MSK 2018. Weather: light rain. Temperature: 18.23 ℃. Minimum temperature: 18.23 ℃. Maximum temperature: 18.51 ℃. Pressure: 997.17 hPa. Sea-level atmosphericPressure: 1018.18 hPa. Ground-level atmosphericPressure: 997.17 hPa. Humidity: 100%. Cloudiness: 76%. Wind: 2.11 meter/sec, 107 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 12:00:00 MSK 2018. Weather: light rain. Temperature: 21.0 ℃. Minimum temperature: 21.0 ℃. Maximum temperature: 21.0 ℃. Pressure: 997.6 hPa. Sea-level atmosphericPressure: 1018.5 hPa. Ground-level atmosphericPressure: 997.6 hPa. Humidity: 100%. Cloudiness: 68%. Wind: 2.51 meter/sec, 82 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 15:00:00 MSK 2018. Weather: light rain. Temperature: 21.78 ℃. Minimum temperature: 21.78 ℃. Maximum temperature: 21.78 ℃. Pressure: 997.73 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.73 hPa. Humidity: 92%. Cloudiness: 88%. Wind: 4.05 meter/sec, 78 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 18:00:00 MSK 2018. Weather: light rain. Temperature: 22.9 ℃. Minimum temperature: 22.9 ℃. Maximum temperature: 22.9 ℃. Pressure: 997.66 hPa. Sea-level atmosphericPressure: 1018.55 hPa. Ground-level atmosphericPressure: 997.66 hPa. Humidity: 93%. Cloudiness: 68%. Wind: 3.06 meter/sec, 67 degrees. Rain(last 3 hrs): 0 mm
Time: Tue Jul 17 21:00:00 MSK 2018. Weather: light rain. Temperature: 23.04 ℃. Minimum temperature: 23.04 ℃. Maximum temperature: 23.04 ℃. Pressure: 996.89 hPa. Sea-level atmosphericPressure: 1017.99 hPa. Ground-level atmosphericPressure: 996.89 hPa. Humidity: 83%. Cloudiness: 88%. Wind: 3.17 meter/sec, 16 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 00:00:00 MSK 2018. Weather: moderate rain. Temperature: 18.5 ℃. Minimum temperature: 18.5 ℃. Maximum temperature: 18.5 ℃. Pressure: 997.33 hPa. Sea-level atmosphericPressure: 1018.34 hPa. Ground-level atmosphericPressure: 997.33 hPa. Humidity: 97%. Cloudiness: 44%. Wind: 3.56 meter/sec, 31 degrees. Rain(last 3 hrs): 7 mm
Time: Wed Jul 18 03:00:00 MSK 2018. Weather: few clouds. Temperature: 18.57 ℃. Minimum temperature: 18.57 ℃. Maximum temperature: 18.57 ℃. Pressure: 996.91 hPa. Sea-level atmosphericPressure: 1017.87 hPa. Ground-level atmosphericPressure: 996.91 hPa. Humidity: 95%. Cloudiness: 24%. Wind: 5.26 meter/sec, 44 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 06:00:00 MSK 2018. Weather: few clouds. Temperature: 18.94 ℃. Minimum temperature: 18.94 ℃. Maximum temperature: 18.94 ℃. Pressure: 997.07 hPa. Sea-level atmosphericPressure: 1018.06 hPa. Ground-level atmosphericPressure: 997.07 hPa. Humidity: 95%. Cloudiness: 20%. Wind: 4.8 meter/sec, 45 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 09:00:00 MSK 2018. Weather: light rain. Temperature: 20.6 ℃. Minimum temperature: 20.6 ℃. Maximum temperature: 20.6 ℃. Pressure: 997.8 hPa. Sea-level atmosphericPressure: 1018.66 hPa. Ground-level atmosphericPressure: 997.8 hPa. Humidity: 97%. Cloudiness: 48%. Wind: 5.56 meter/sec, 54 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 12:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.87 ℃. Minimum temperature: 23.87 ℃. Maximum temperature: 23.87 ℃. Pressure: 998.06 hPa. Sea-level atmosphericPressure: 1019.05 hPa. Ground-level atmosphericPressure: 998.06 hPa. Humidity: 88%. Cloudiness: 32%. Wind: 5.86 meter/sec, 52 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 24.67 ℃. Minimum temperature: 24.67 ℃. Maximum temperature: 24.67 ℃. Pressure: 998.51 hPa. Sea-level atmosphericPressure: 1019.33 hPa. Ground-level atmosphericPressure: 998.51 hPa. Humidity: 84%. Cloudiness: 36%. Wind: 5.63 meter/sec, 51 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.15 ℃. Minimum temperature: 25.15 ℃. Maximum temperature: 25.15 ℃. Pressure: 998.79 hPa. Sea-level atmosphericPressure: 1019.64 hPa. Ground-level atmosphericPressure: 998.79 hPa. Humidity: 78%. Cloudiness: 44%. Wind: 5.47 meter/sec, 38 degrees. Rain(last 3 hrs): 0 mm
Time: Wed Jul 18 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.23 ℃. Minimum temperature: 23.23 ℃. Maximum temperature: 23.23 ℃. Pressure: 999.08 hPa. Sea-level atmosphericPressure: 1020.04 hPa. Ground-level atmosphericPressure: 999.08 hPa. Humidity: 75%. Cloudiness: 48%. Wind: 4.62 meter/sec, 25 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 20.79 ℃. Minimum temperature: 20.79 ℃. Maximum temperature: 20.79 ℃. Pressure: 999.67 hPa. Sea-level atmosphericPressure: 1020.68 hPa. Ground-level atmosphericPressure: 999.67 hPa. Humidity: 76%. Cloudiness: 48%. Wind: 4.29 meter/sec, 13 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 03:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.45 ℃. Minimum temperature: 19.45 ℃. Maximum temperature: 19.45 ℃. Pressure: 999.95 hPa. Sea-level atmosphericPressure: 1021.02 hPa. Ground-level atmosphericPressure: 999.95 hPa. Humidity: 80%. Cloudiness: 48%. Wind: 4.22 meter/sec, 17 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 06:00:00 MSK 2018. Weather: light rain. Temperature: 18.9 ℃. Minimum temperature: 18.9 ℃. Maximum temperature: 18.9 ℃. Pressure: 1000.6 hPa. Sea-level atmosphericPressure: 1021.62 hPa. Ground-level atmosphericPressure: 1000.6 hPa. Humidity: 83%. Cloudiness: 92%. Wind: 4.43 meter/sec, 10 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 09:00:00 MSK 2018. Weather: light rain. Temperature: 21.37 ℃. Minimum temperature: 21.37 ℃. Maximum temperature: 21.37 ℃. Pressure: 1000.95 hPa. Sea-level atmosphericPressure: 1022.01 hPa. Ground-level atmosphericPressure: 1000.95 hPa. Humidity: 87%. Cloudiness: 0%. Wind: 4.36 meter/sec, 6 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.92 ℃. Minimum temperature: 23.92 ℃. Maximum temperature: 23.92 ℃. Pressure: 1001.5 hPa. Sea-level atmosphericPressure: 1022.43 hPa. Ground-level atmosphericPressure: 1001.5 hPa. Humidity: 77%. Cloudiness: 0%. Wind: 5.66 meter/sec, 12 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 15:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.7 ℃. Minimum temperature: 23.7 ℃. Maximum temperature: 23.7 ℃. Pressure: 1001.75 hPa. Sea-level atmosphericPressure: 1022.72 hPa. Ground-level atmosphericPressure: 1001.75 hPa. Humidity: 72%. Cloudiness: 56%. Wind: 5.87 meter/sec, 349 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 18:00:00 MSK 2018. Weather: broken clouds. Temperature: 23.82 ℃. Minimum temperature: 23.82 ℃. Maximum temperature: 23.82 ℃. Pressure: 1001.55 hPa. Sea-level atmosphericPressure: 1022.59 hPa. Ground-level atmosphericPressure: 1001.55 hPa. Humidity: 72%. Cloudiness: 68%. Wind: 5.47 meter/sec, 340 degrees. Rain(last 3 hrs): 0 mm
Time: Thu Jul 19 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.22 ℃. Minimum temperature: 22.22 ℃. Maximum temperature: 22.22 ℃. Pressure: 1001.82 hPa. Sea-level atmosphericPressure: 1022.93 hPa. Ground-level atmosphericPressure: 1001.82 hPa. Humidity: 67%. Cloudiness: 76%. Wind: 4.12 meter/sec, 333 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 00:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.76 ℃. Minimum temperature: 19.76 ℃. Maximum temperature: 19.76 ℃. Pressure: 1001.98 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.98 hPa. Humidity: 76%. Cloudiness: 32%. Wind: 4.11 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 03:00:00 MSK 2018. Weather: clear sky. Temperature: 17.53 ℃. Minimum temperature: 17.53 ℃. Maximum temperature: 17.53 ℃. Pressure: 1001.93 hPa. Sea-level atmosphericPressure: 1023.13 hPa. Ground-level atmosphericPressure: 1001.93 hPa. Humidity: 87%. Cloudiness: 8%. Wind: 4.21 meter/sec, 309 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 16.83 ℃. Minimum temperature: 16.83 ℃. Maximum temperature: 16.83 ℃. Pressure: 1001.79 hPa. Sea-level atmosphericPressure: 1022.99 hPa. Ground-level atmosphericPressure: 1001.79 hPa. Humidity: 91%. Cloudiness: 44%. Wind: 3.65 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 09:00:00 MSK 2018. Weather: light rain. Temperature: 19.57 ℃. Minimum temperature: 19.57 ℃. Maximum temperature: 19.57 ℃. Pressure: 1001.34 hPa. Sea-level atmosphericPressure: 1022.41 hPa. Ground-level atmosphericPressure: 1001.34 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 4.38 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 12:00:00 MSK 2018. Weather: clear sky. Temperature: 23.5 ℃. Minimum temperature: 23.5 ℃. Maximum temperature: 23.5 ℃. Pressure: 1001.0 hPa. Sea-level atmosphericPressure: 1021.99 hPa. Ground-level atmosphericPressure: 1001.0 hPa. Humidity: 85%. Cloudiness: 8%. Wind: 5.36 meter/sec, 299 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 25.14 ℃. Minimum temperature: 25.14 ℃. Maximum temperature: 25.14 ℃. Pressure: 1000.5 hPa. Sea-level atmosphericPressure: 1021.51 hPa. Ground-level atmosphericPressure: 1000.5 hPa. Humidity: 73%. Cloudiness: 32%. Wind: 6.72 meter/sec, 305 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 18:00:00 MSK 2018. Weather: overcast clouds. Temperature: 23.56 ℃. Minimum temperature: 23.56 ℃. Maximum temperature: 23.56 ℃. Pressure: 1000.7 hPa. Sea-level atmosphericPressure: 1021.58 hPa. Ground-level atmosphericPressure: 1000.7 hPa. Humidity: 66%. Cloudiness: 88%. Wind: 6.57 meter/sec, 317 degrees. Rain(last 3 hrs): 0 mm
Time: Fri Jul 20 21:00:00 MSK 2018. Weather: broken clouds. Temperature: 22.41 ℃. Minimum temperature: 22.41 ℃. Maximum temperature: 22.41 ℃. Pressure: 1000.64 hPa. Sea-level atmosphericPressure: 1021.67 hPa. Ground-level atmosphericPressure: 1000.64 hPa. Humidity: 68%. Cloudiness: 64%. Wind: 4.31 meter/sec, 326 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 00:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.92 ℃. Minimum temperature: 20.92 ℃. Maximum temperature: 20.92 ℃. Pressure: 1001.06 hPa. Sea-level atmosphericPressure: 1022.14 hPa. Ground-level atmosphericPressure: 1001.06 hPa. Humidity: 78%. Cloudiness: 68%. Wind: 3.42 meter/sec, 327 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 03:00:00 MSK 2018. Weather: broken clouds. Temperature: 20.28 ℃. Minimum temperature: 20.28 ℃. Maximum temperature: 20.28 ℃. Pressure: 1001.04 hPa. Sea-level atmosphericPressure: 1022.13 hPa. Ground-level atmosphericPressure: 1001.04 hPa. Humidity: 78%. Cloudiness: 76%. Wind: 4.27 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 06:00:00 MSK 2018. Weather: scattered clouds. Temperature: 19.11 ℃. Minimum temperature: 19.11 ℃. Maximum temperature: 19.11 ℃. Pressure: 1001.13 hPa. Sea-level atmosphericPressure: 1022.28 hPa. Ground-level atmosphericPressure: 1001.13 hPa. Humidity: 74%. Cloudiness: 32%. Wind: 4.96 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 09:00:00 MSK 2018. Weather: few clouds. Temperature: 20.16 ℃. Minimum temperature: 20.16 ℃. Maximum temperature: 20.16 ℃. Pressure: 1001.43 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.43 hPa. Humidity: 86%. Cloudiness: 20%. Wind: 5.16 meter/sec, 308 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 12:00:00 MSK 2018. Weather: few clouds. Temperature: 22.37 ℃. Minimum temperature: 22.37 ℃. Maximum temperature: 22.37 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.62 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 88%. Cloudiness: 20%. Wind: 5.56 meter/sec, 307 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 15:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.85 ℃. Minimum temperature: 22.85 ℃. Maximum temperature: 22.85 ℃. Pressure: 1001.63 hPa. Sea-level atmosphericPressure: 1022.65 hPa. Ground-level atmosphericPressure: 1001.63 hPa. Humidity: 81%. Cloudiness: 44%. Wind: 5.46 meter/sec, 314 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 18:00:00 MSK 2018. Weather: scattered clouds. Temperature: 23.79 ℃. Minimum temperature: 23.79 ℃. Maximum temperature: 23.79 ℃. Pressure: 1001.53 hPa. Sea-level atmosphericPressure: 1022.53 hPa. Ground-level atmosphericPressure: 1001.53 hPa. Humidity: 72%. Cloudiness: 32%. Wind: 5.56 meter/sec, 313 degrees. Rain(last 3 hrs): 0 mm
Time: Sat Jul 21 21:00:00 MSK 2018. Weather: scattered clouds. Temperature: 22.56 ℃. Minimum temperature: 22.56 ℃. Maximum temperature: 22.56 ℃. Pressure: 1001.72 hPa. Sea-level atmosphericPressure: 1022.7 hPa. Ground-level atmosphericPressure: 1001.72 hPa. Humidity: 66%. Cloudiness: 48%. Wind: 3.96 meter/sec, 312 degrees. Rain(last 3 hrs): 0 mm
```
`HourlyForecast.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|------------------------------------------------------------------------------------------------------------------|
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. |
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. |
| `getWeatherInfo()` | Returns `HourlyForecast.WeatherInfo` instance that contains information about temperature, atmosphericPressure and humidity.|
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getClouds()` | Returns `Clouds` instance that contains *cloudiness* percentage information. |
| `getWind()` | Returns `Wind` instance that contains information about speed and degree. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. |
| `getSystemInfo()` | Returns `HourlyForecast.ForecastSystemInfo` instance with internal information. |
| `getDt_txt()` | Returns `String` value that represents data calculation time. |
| `toString()` | Returns pretty string for the whole available forecast information. |
#### 16 day / daily forecast
First step is retrieving `DailyForecastRequester` instance:
```java
OpenWeatherMapManager openWeatherManager = new OpenWeatherMapManager(API_TOKEN);
DailyForecastRequester forecastRequester = openWeatherManager.getDailyForecastRequester();
```
after you are able to set preferable options(via chain methods) and execute appropriate request:
```
DailyForecast forecastResponse = forecastRequester
.setLanguage(Language.ENGLISH)
.setUnitSystem(Unit.METRIC_SYSTEM)
.setAccuracy(Accuracy.ACCURATE)
.getByCityName("Pruzhany");
```
*Language*, *UnitSystem* and *Accuracy* settings will be described below.
Available requests:
* `getByCityId(String cityId)`
* `getByCityName(String cityName)`
* `getByCoordinates(double latitude, double longitude)`
* `getByCoordinates(Coordinates coordinates)`
* `getByZIPCode(String zipCode, String countryCode)`
`DailyForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|--------------------------------------------------------------------------------------------|
| `getCityId()` | Returns city ID. Example: `625144` for Minsk. |
| `getCityName()` | Returns city name. Example: `Minsk`. |
| `getCoordinates()` | Returns `Coordinates` instance that contains *latitude* and *longitude* information. |
| `getCityInfo()` | Returns `CityInfo` instance that contains information about city. |
| `getResponseCode()` | Returns OpenWeatherMap response code. Internal information. |
| `getCountry()` | An alias for `getCityInfo().getCountry()`. |
| `getForecasts()` | Returns `List<HourlyForecast.Forecast>` collection with all forecast information. |
| `toString()` | Returns pretty string for the whole available forecast information. |
`DailyForecast.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------|------------------------------------------------------------------------------------------------------------------|
| `getDataCalculationTime()` | Returns `long` value that represents data calculation timestamp. |
| `getDataCalculationDate()` | Returns data calculation time in `Date` representation. |
| `getTemperature()` | Returns `DailyForecast.Forecast.Temperature` instance that contains information about temperature(avg, min, max).|
| `getWeatherStates()` | Returns list of `WeatherState` instances with the only `getDescription` useful method. |
| `getCloudiness()` | Returns *cloudiness* percentage information. |
| `getHumidity()` | Returns *humidity* percentage information. |
| `getWindSpeed()` | Returns wind's speed. |
| `getWindDegrees()` | Returns wind's degree. |
| `getWindUnit()` | Returns wind's unit. |
| `getPressure()` | Returns atmosphericPressure value. |
| `getPressureUnit()` | Returns atmosphericPressure's unit. |
| `toString()` | Returns pretty string for the whole available forecast information. |
#### UV Index
First step is retrieving `UltravioletIndexRequester` instance:
```java
OpenWeatherMapManager openWeatherMapManager = new OpenWeatherMapManager(API_TOKEN);
UltravioletIndexRequester requester = openWeatherMapManager.getUltravioletIndexRequester(34.23f, -22.45f);
```
or
```java
OpenWeatherMapManager openWeatherMapManager = new OpenWeatherMapManager(API_TOKEN);
Coordinates coordinates = new Coordinates(34.23f, -22.45f);
UltravioletIndexRequester requester = openWeatherMapManager.getUltravioletIndexRequester(coordinates);
```
after you need to execute appropriate request:
```
UltravioletIndex uvResponse = requester.getCurrentUVIndex();
```
You can change required coordinates via: `requester.setCoordinates(Coordinates coordinates);` or `requester.setCoordinates(float latitude, float longitude);`
Available requests:
* `getCurrentUVIndex()`
* `getUVIndexForecast(int amountOfDays)`
* `getUVIndexByPeriod(Date from, Date to)`
`UltravioletIndex`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------|
| `getLatitude()` | Returns latitude. |
| `getLongitude()` | Returns longitude. |
| `getDateISO()` | Returns ISO date in String representation. |
| `getDateTimestamp()` | Returns date timestamp. |
| `getValue()` | Returns UV value. |
| `getCalculationDate()` | Returns date in Date representation`. |
| `toString()` | Returns pretty string for the whole available UV information. |
`toString()` output example:
```
Date: Tue Jul 31 15:00:00 MSK 2018, Ultraviolet value: 6.230000
```
#### Air pollution
First step is retrieving `AirPollutionRequester` instance:
```java
OpenWeatherMapManager openWeatherMapManager = new OpenWeatherMapManager(API_TOKEN);
AirPollutionRequester requester = openWeatherMapManager.getAirPollutionRequester(0f, 10f, new Date(), TimeFrame.DAY);
```
after you need to execute appropriate request:
```
AirPollution airPolutionResponse = requester.retrieve();
```
You can modify parameters anytime:
```java
requester.setCoordinates(Coordinates coordinates);
requester.setCoordinates(float latitude, float longitude);
requester.setTimeFrame(TimeFrame timeFrame);
requester.setDate(Date date);
```
Available requests:
* `retrieve()`
`AirPollution`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------|
| `getCoordinates()` | Returns `Coordinates` instance. |
| `getLongitude()` | Returns longitude. |
| `airPollutionInfo()` | Returns list of `AirPollution.AirPollutionInfo` instances. |
| `toString()` | Returns pretty string for the whole available air pollution information. |
`toString()` output example:
```
AirPollution[Date: Tue Jul 24 01:04:40 MSK 2018; Coordinates: latitude=0.0, longitude=9.9955]
[Value: 8.0347114E-8, Value: 9.5041536E-8, Value: 7.7667146E-8, Value: 7.251491E-8, Value: 5.899763E-8, Value: 1.9186361E-8, Value: 1.729535E-8, Value: 1.25645805E-8, Value: 3.0852514E-9]
```
### Constants and options
#### Accuracy
| Constant | Description |
|--------------------|------------------|
| Accuracy.LIKE | Close result. |
| Accuracy.ACCURATE | Accurate result. |
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow) |
### Dependencies
* com.alibaba:fastjson:1.2.44
* org.projectlombok:lombok:1.18.0 (*provided*)
* junit:junit:4.12 (*test*)
+253
View File
@@ -0,0 +1,253 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.0.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.0.0')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapClient` class:
```java
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently, available APIs are:
* `currentWeather()`
* `forecast5Day3HourStep()`
Default(more or less) customization points:
```java
...
// response language
.language(Language.RUSSIAN)
...
// response units of measure
.unitSystem(UnitSystem.IMPERIAL)
...
```
Available output forms:
* `asJava()`
* `asJSON()`
Additional output forms, available for several APIs:
* `asXML()`
* `asHTML()`
_All response forms can be in **sync** and **async** variants._
#### Current weather data
Examples:
```java
final String weatherJson = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJSON();
```
```java
final Weather weather = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJava();
```
```java
final CompletableFuture<String> weatherXmlFuture = openWeatherClient
.currentWeather()
.single()
.byZipCodeAndCountry("220015", "by")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.weather.Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `getCalculatedOn()` | Returns `LocalDateTime` object with data calculation time. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()`| Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset` and `coordinate`. |
| `toString()` | Returns informative string for the whole available weather information. |
`toString()` output example:
```
Location: Minsk(BY), Weather: clear sky, -4.22 ℃, 1020.0 hPa, Clouds: 0%
```
#### 5 day / 3-hour forecast
Examples:
```java
final Forecast forecast = openWeatherClient
.forecast5Day3HourStep()
.byCityName("Minsk")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieve()
.asJava();
```
```java
final String forecastJson = getClient()
.forecast5Day3HourStep()
.byCityName("New York", "NY", "US")
.language(Language.SPANISH)
.unitSystem(UnitSystem.IMPERIAL)
.count(15)
.retrieve()
.asJSON();
```
```java
CompletableFuture<String> forecastFuture = getClient()
.forecast5Day3HourStep()
.byCityId(350001514)
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieveAsync()
.asXML();
```
```java
final String forecastXml = getClient()
.forecast5Day3HourStep()
.byZipCodeInUSA("10005")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.request.forecast.free.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset`, `coordinate` and `population`. |
| `getWeatherForecasts()` | Returns list of `WeatherForecast` objects with forecast information. |
| `toString()` | Returns informative string for the whole available forecast information. |
`toString()` output example:
```
A forecast for Minsk with 15 timestamps.
```
`com.github.prominence.openweathermap.api.model.forecast.WeatherForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getForecastTimeISO()` | Returns String with time of data forecasted, ISO, UTC. |
| `getDayTime()` | Returns enumerations representing the part of day(day, night). |
| `toString()` | Returns informative string for the forecast of particular timestamp. |
### Constants and options
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow). |
### Dependencies
* com.fasterxml.jackson.core:jackson-databind:2.12.2
* org.slf4j:slf4j-api:1.7.30 (*compile*)
* junit:junit:4.13.1 (*test*)
+253
View File
@@ -0,0 +1,253 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.0.1</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.0.1')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapClient` class:
```java
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently, available APIs are:
* `currentWeather()`
* `forecast5Day3HourStep()`
Default(more or less) customization points:
```java
...
// response language
.language(Language.RUSSIAN)
...
// response units of measure
.unitSystem(UnitSystem.IMPERIAL)
...
```
Available output forms:
* `asJava()`
* `asJSON()`
Additional output forms, available for several APIs:
* `asXML()`
* `asHTML()`
_All response forms can be in **sync** and **async** variants._
#### Current weather data
Examples:
```java
final String weatherJson = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJSON();
```
```java
final Weather weather = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJava();
```
```java
final CompletableFuture<String> weatherXmlFuture = openWeatherClient
.currentWeather()
.single()
.byZipCodeAndCountry("220015", "by")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.weather.Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `getCalculatedOn()` | Returns `LocalDateTime` object with data calculation time. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()`| Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset` and `coordinate`. |
| `toString()` | Returns informative string for the whole available weather information. |
`toString()` output example:
```
Location: Minsk(BY), Weather: clear sky, -4.22 ℃, 1020.0 hPa, Clouds: 0%
```
#### 5 day / 3-hour forecast
Examples:
```java
final Forecast forecast = openWeatherClient
.forecast5Day3HourStep()
.byCityName("Minsk")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieve()
.asJava();
```
```java
final String forecastJson = getClient()
.forecast5Day3HourStep()
.byCityName("New York", "NY", "US")
.language(Language.SPANISH)
.unitSystem(UnitSystem.IMPERIAL)
.count(15)
.retrieve()
.asJSON();
```
```java
CompletableFuture<String> forecastFuture = getClient()
.forecast5Day3HourStep()
.byCityId(350001514)
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieveAsync()
.asXML();
```
```java
final String forecastXml = getClient()
.forecast5Day3HourStep()
.byZipCodeInUSA("10005")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.request.forecast.free.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset`, `coordinate` and `population`. |
| `getWeatherForecasts()` | Returns list of `WeatherForecast` objects with forecast information. |
| `toString()` | Returns informative string for the whole available forecast information. |
`toString()` output example:
```
A forecast for Minsk with 15 timestamps.
```
`com.github.prominence.openweathermap.api.model.forecast.WeatherForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getState()` | Returns short weather description. Example: `Clear`. |
| `getDescription()` | Returns weather description. Example: `clear sky`. |
| `getWeatherIconUrl()` | Returns a link to weather icon hosted on https://openweathermap.org website. |
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getForecastTimeISO()` | Returns String with time of data forecasted, ISO, UTC. |
| `getDayTime()` | Returns enumerations representing the part of day(day, night). |
| `toString()` | Returns informative string for the forecast of particular timestamp. |
### Constants and options
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.ARABIC | Arabic language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow). |
### Dependencies
* com.fasterxml.jackson.core:jackson-databind:2.12.2
* org.slf4j:slf4j-api:1.7.30 (*compile*)
* junit:junit:4.13.1 (*test*)
+484
View File
@@ -0,0 +1,484 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.1.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.1.0')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapClient` class:
```java
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently, available APIs are:
* `currentWeather()`
* `forecast5Day3HourStep()`
* `oneCall()`
Default(more or less) customization points:
```java
...
// response language
.language(Language.RUSSIAN)
...
// response units of measure
.unitSystem(UnitSystem.IMPERIAL)
...
```
Available output forms:
* `asJava()`
* `asJSON()`
Additional output forms, available for several APIs:
* `asXML()`
* `asHTML()`
_All response forms can be in **sync** and **async** variants._
#### Current weather data
Examples:
```java
final String weatherJson = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJSON();
```
```java
final Weather weather = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJava();
```
```java
final CompletableFuture<String> weatherXmlFuture = openWeatherClient
.currentWeather()
.single()
.byZipCodeAndCountry("220015", "by")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.weather.Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCalculationTime()` | Returns `LocalDateTime` object with data calculation time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()`| Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset` and `coordinate`. |
| `toString()` | Returns informative string for the whole available weather information. |
`toString()` output example:
```
Location: Minsk(BY), Weather: clear sky, -4.22 ℃, 1020.0 hPa, Clouds: 0%
```
#### 5 day / 3-hour forecast
Examples:
```java
final Forecast forecast = openWeatherClient
.forecast5Day3HourStep()
.byCityName("Minsk")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieve()
.asJava();
```
```java
final String forecastJson = getClient()
.forecast5Day3HourStep()
.byCityName("New York", "NY", "US")
.language(Language.SPANISH)
.unitSystem(UnitSystem.IMPERIAL)
.count(15)
.retrieve()
.asJSON();
```
```java
CompletableFuture<String> forecastFuture = getClient()
.forecast5Day3HourStep()
.byCityId(350001514)
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieveAsync()
.asXML();
```
```java
final String forecastXml = getClient()
.forecast5Day3HourStep()
.byZipCodeInUSA("10005")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.forecast.free.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset`, `coordinate` and `population`. |
| `getWeatherForecasts()` | Returns list of `WeatherForecast` objects with forecast information. |
| `toString()` | Returns informative string for the whole available forecast information. |
`toString()` output example:
```
A forecast for Minsk with 15 timestamps.
```
`com.github.prominence.openweathermap.api.model.forecast.WeatherForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getForecastTimeISO()` | Returns String with time of data forecasted, ISO, UTC. |
| `getDayTime()` | Returns enumerations representing the part of day(day, night). |
| `toString()` | Returns informative string for the forecast of particular timestamp. |
#### One Call API
Examples:
```java
final CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.exclude(OneCallResultOptions.CURRENT, OneCallResultOptions.MINUTELY)
.retrieve()
.asJava();
```
```java
final CompletableFuture<CurrentWeatherData> currentWeatherDataFuture = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJava();
```
```java
final String responseJson = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJSON();
```
```java
final HistoricalWeatherData historicalWeatherData = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final String responseJson = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJSON();
```
```java
final CompletableFuture<HistoricalWeatherData> historicalWeatherDataFuture = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJava();
```
```java
final CompletableFuture<String> responseJsonFuture = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJSON();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|--------------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getTimezone()` | Returns location timezone object. |
| `getTimezoneOffset()` | Returns zone offset. |
| `getCurrent()` | Returns `Current` object with current weather state if available. |
| `getMinutelyList()` | Returns list of `Minutely` objects if available. |
| `getHourlyList()` | Returns list of `Houlry` objects if available. |
| `getDailyList()` | Returns list of `Daily` objects if available. |
| `getAlerts()` | Returns list of `Alert` objects if available. |
`com.github.prominence.openweathermap.api.model.onecall.Current`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Minutely`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getPrecipitationVolume()` | Returns precipitation volume. |
`com.github.prominence.openweathermap.api.model.onecall.current.Hourly`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getProbabilityOfPrecipitation()` | Returns probability of precipitation(not percentage). |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Daily`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `DailyTemperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getProbabilityOfPrecipitation()` | Returns probability of precipitation(not percentage). |
| `getRain()` | Returns `DailyRain` object. Available fields: `value`. |
| `getSnow()` | Returns `DailySnow` object. Available fields: `value`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Alert`'s useful public methods(setters are not listed):
| Method | Description |
|------------------------------|--------------------------------------------------------|
| `getSenderName()` | Returns alert sender name. |
| `getEventName()` | Returns alert event name. |
| `getStartTime()` | Returns `LocalDateTime` when event should start. |
| `getEndTime()` | Returns `LocalDateTime` when event should end. |
| `getDescription()` | Returns alert description. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getTimezone()` | Returns location timezone object. |
| `getTimezoneOffset()` | Returns zone offset. |
| `getHistoricalWeather()` | Returns `HistoricalWeather` object with historical weather state. |
| `getHourlyList()` | Returns list of `HourlyHistorical` objects. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeather`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HourlyHistorical`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
### Constants and options
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.AFRIKAANS | Afrikaans language. |
| Language.ALBANIAN | ALBANIAN language. |
| Language.ARABIC | Arabic language. |
| Language.AZERBAIJANI | Azerbaijani language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.DANISH | Danish language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.BASQUE | Basque language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.HEBREW | Hebrew language. |
| Language.HINDI | Hindi language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.INDONESIAN | Indonesian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.NORWEGIAN | Norwegian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.PORTUGUES_BRAZIL | Português Brasil language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.SERBIAN | Serbian language. |
| Language.THAI | Thai language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
| Language.ZULU | Zulu language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow). |
### Dependencies
* com.fasterxml.jackson.core:jackson-databind:2.12.2
* org.slf4j:slf4j-api:1.7.30 (*compile*)
* org.junit.jupiter:junit-jupiter-engine:5.7.1 (*test*)
* org.junit.platform:junit-platform-runner:1.7.1 (*test*)
+484
View File
@@ -0,0 +1,484 @@
### Implemented features:
* Current weather data
* 5 day / 3-hour forecast
* One Call API
### Maven coordinates:
```xml
<dependency>
<groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId>
<version>2.1.0</version>
</dependency>
```
### Gradle coordinates:
```groovy
compile('com.github.prominence:openweathermap-api:2.1.0')
```
### How to use:
Firstly, you need to create the instance of `OpenWeatherMapClient` class:
```java
OpenWeatherMapClient openWeatherClient = new OpenWeatherMapClient(API_TOKEN);
```
where `API_TOKEN` is your token([you can get it here](https://home.openweathermap.org/api_keys)) as `String`.
Currently, available APIs are:
* `currentWeather()`
* `forecast5Day3HourStep()`
* `oneCall()`
Default(more or less) customization points:
```java
...
// response language
.language(Language.RUSSIAN)
...
// response units of measure
.unitSystem(UnitSystem.IMPERIAL)
...
```
Available output forms:
* `asJava()`
* `asJSON()`
Additional output forms, available for several APIs:
* `asXML()`
* `asHTML()`
_All response forms can be in **sync** and **async** variants._
#### Current weather data
Examples:
```java
final String weatherJson = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJSON();
```
```java
final Weather weather = openWeatherClient
.currentWeather()
.single()
.byCityName("Minsk")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final List<Weather> weatherList = openWeatherClient
.currentWeather()
.multiple()
.byCitiesInCycle(Coordinate.of(55.5, 37.5))
.language(Language.GERMAN)
.unitSystem(UnitSystem.IMPERIAL)
.retrieve()
.asJava();
```
```java
final CompletableFuture<String> weatherXmlFuture = openWeatherClient
.currentWeather()
.single()
.byZipCodeAndCountry("220015", "by")
.language(Language.RUSSIAN)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.weather.Weather`'s useful public methods(setters are not listed):
| Method | Description |
|---------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getCalculationTime()` | Returns `LocalDateTime` object with data calculation time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()`| Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last one hour and/or the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset` and `coordinate`. |
| `toString()` | Returns informative string for the whole available weather information. |
`toString()` output example:
```
Location: Minsk(BY), Weather: clear sky, -4.22 ℃, 1020.0 hPa, Clouds: 0%
```
#### 5 day / 3-hour forecast
Examples:
```java
final Forecast forecast = openWeatherClient
.forecast5Day3HourStep()
.byCityName("Minsk")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieve()
.asJava();
```
```java
final String forecastJson = getClient()
.forecast5Day3HourStep()
.byCityName("New York", "NY", "US")
.language(Language.SPANISH)
.unitSystem(UnitSystem.IMPERIAL)
.count(15)
.retrieve()
.asJSON();
```
```java
CompletableFuture<String> forecastFuture = getClient()
.forecast5Day3HourStep()
.byCityId(350001514)
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.count(15)
.retrieveAsync()
.asXML();
```
```java
final String forecastXml = getClient()
.forecast5Day3HourStep()
.byZipCodeInUSA("10005")
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asXML();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.forecast.free.Forecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getLocation()` | Returns `Location` object. Available fields: `id`, `name`, `countryCode`, `sunrise` and `sunset` time, `zoneOffset`, `coordinate` and `population`. |
| `getWeatherForecasts()` | Returns list of `WeatherForecast` objects with forecast information. |
| `toString()` | Returns informative string for the whole available forecast information. |
`toString()` output example:
```
A forecast for Minsk with 15 timestamps.
```
`com.github.prominence.openweathermap.api.model.forecast.WeatherForecast`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` instance that contains information about temperature. Available fields: `value`, `maxTemperature`, `minTemperature`, `feelsLike` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` instance that contains information about atmospheric pressure. Available fields: `value`, `seaLevelValue`, `groundLevelValue` and `unit`. |
| `getHumidity()` | Returns `Humidity` instance that contains humidity percentage information. |
| `getWind()` | Returns `Wind` instance that contains wind information: `speed`, `degrees` and `unit`. |
| `getRain()` | Returns `Rain` instance that contains information about rain volume for the last 3 hours. Can be absent in case of no data. |
| `getSnow()` | Returns `Snow` instance that contains information about snow volume for the last 3 hours. Can be absent in case of no data. |
| `getClouds()` | Returns `Clouds` instance that contains information about cloudiness percentage. |
| `getForecastTimeISO()` | Returns String with time of data forecasted, ISO, UTC. |
| `getDayTime()` | Returns enumerations representing the part of day(day, night). |
| `toString()` | Returns informative string for the forecast of particular timestamp. |
#### One Call API
Examples:
```java
final CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final CurrentWeatherData currentWeatherData = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.exclude(OneCallResultOptions.CURRENT, OneCallResultOptions.MINUTELY)
.retrieve()
.asJava();
```
```java
final CompletableFuture<CurrentWeatherData> currentWeatherDataFuture = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJava();
```
```java
final String responseJson = openWeatherClient
.oneCall()
.current()
.byCoordinate(Coordinate.of(53.54, 27.34))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJSON();
```
```java
final HistoricalWeatherData historicalWeatherData = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJava();
```
```java
final String responseJson = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieve()
.asJSON();
```
```java
final CompletableFuture<HistoricalWeatherData> historicalWeatherDataFuture = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJava();
```
```java
final CompletableFuture<String> responseJsonFuture = openWeatherClient
.oneCall()
.historical()
.byCoordinateAndTimestamp(Coordinate.of(60.99, 30.9), LocalDateTime.now().minusDays(5).toEpochSecond(ZoneOffset.UTC))
.language(Language.ENGLISH)
.unitSystem(UnitSystem.METRIC)
.retrieveAsync()
.asJSON();
```
You are able to set preferable options(via chain methods) and execute appropriate request.
`com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|--------------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getTimezone()` | Returns location timezone object. |
| `getTimezoneOffset()` | Returns zone offset. |
| `getCurrent()` | Returns `Current` object with current weather state if available. |
| `getMinutelyList()` | Returns list of `Minutely` objects if available. |
| `getHourlyList()` | Returns list of `Houlry` objects if available. |
| `getDailyList()` | Returns list of `Daily` objects if available. |
| `getAlerts()` | Returns list of `Alert` objects if available. |
`com.github.prominence.openweathermap.api.model.onecall.Current`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Minutely`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|---------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getPrecipitationVolume()` | Returns precipitation volume. |
`com.github.prominence.openweathermap.api.model.onecall.current.Hourly`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getProbabilityOfPrecipitation()` | Returns probability of precipitation(not percentage). |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Daily`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `DailyTemperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getProbabilityOfPrecipitation()` | Returns probability of precipitation(not percentage). |
| `getRain()` | Returns `DailyRain` object. Available fields: `value`. |
| `getSnow()` | Returns `DailySnow` object. Available fields: `value`. |
`com.github.prominence.openweathermap.api.model.onecall.current.Alert`'s useful public methods(setters are not listed):
| Method | Description |
|------------------------------|--------------------------------------------------------|
| `getSenderName()` | Returns alert sender name. |
| `getEventName()` | Returns alert event name. |
| `getStartTime()` | Returns `LocalDateTime` when event should start. |
| `getEndTime()` | Returns `LocalDateTime` when event should end. |
| `getDescription()` | Returns alert description. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------|
| `getCoordinate()` | Returns `Coordinate` object. Available fields: `latitude`, `longitude`. |
| `getTimezone()` | Returns location timezone object. |
| `getTimezoneOffset()` | Returns zone offset. |
| `getHistoricalWeather()` | Returns `HistoricalWeather` object with historical weather state. |
| `getHourlyList()` | Returns list of `HourlyHistorical` objects. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeather`'s useful public methods(setters are not listed):
| Method | Description |
|-------------------------------|-------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getSunriseTime()` | Returns `LocalDateTime` object with sunrise time. |
| `getSunsetTime()` | Returns `LocalDateTime` object with sunset time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getUvIndex()` | Returns UV index value. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
`com.github.prominence.openweathermap.api.model.onecall.historical.HourlyHistorical`'s useful public methods(setters are not listed):
| Method | Description |
|-----------------------------------|---------------------------------------------------------------------------------------------------|
| `getForecastTime()` | Returns `LocalDateTime` object with weather forecast time. |
| `getWeatherState()` | Returns `WeatherState` object with basic weather state information. |
| `getTemperature()` | Returns `Temperature` object. Available fields: `value`, `feelsLike`, `dewPoint` and `unit`. |
| `getAtmosphericPressure()` | Returns `AtmosphericPressure` object. Available fields: `seaLevelValue`. |
| `getHumidity()` | Returns `Humidity` object. Available fields: `value` and `unit`. |
| `getClouds()` | Returns `Clouds` object. Available fields: `value` and `unit`. |
| `getVisibilityInMetres()` | Returns visibility in metres. |
| `getWind()` | Returns `Wind` object. Available fields: `speed`, `degrees`, `gust` and `unit`. |
| `getRain()` | Returns `Rain` object. Available fields: `oneHourLevel` and `unit`. |
| `getSnow()` | Returns `Snow` object. Available fields: `oneHourLevel` and `unit`. |
### Constants and options
#### Language
| Constant | Description |
|-----------------------------------|-------------------------------|
| Language.AFRIKAANS | Afrikaans language. |
| Language.ALBANIAN | ALBANIAN language. |
| Language.ARABIC | Arabic language. |
| Language.AZERBAIJANI | Azerbaijani language. |
| Language.BULGARIAN | Bulgarian language. |
| Language.CATALAN | Catalan language. |
| Language.CZECH | Czech language. |
| Language.DANISH | Danish language. |
| Language.GERMAN | German language. |
| Language.GREEK | Greek language. |
| Language.ENGLISH | English language. |
| Language.BASQUE | Basque language. |
| Language.PERSIAN | Persian (Farsi) language. |
| Language.FINNISH | Finnish language. |
| Language.FRENCH | French language. |
| Language.GALICIAN | Galician language. |
| Language.HEBREW | Hebrew language. |
| Language.HINDI | Hindi language. |
| Language.CROATIAN | Croatian language. |
| Language.HUNGARIAN | Hungarian language. |
| Language.INDONESIAN | Indonesian language. |
| Language.ITALIAN | Italian language. |
| Language.JAPANESE | Japanese language. |
| Language.KOREAN | Korean language. |
| Language.LATVIAN | Latvian language. |
| Language.LITHUANIAN | Lithuanian language. |
| Language.MACEDONIAN | Macedonian language. |
| Language.NORWEGIAN | Norwegian language. |
| Language.DUTCH | Dutch language. |
| Language.POLISH | Polish language. |
| Language.PORTUGUESE | Portuguese language. |
| Language.PORTUGUES_BRAZIL | Português Brasil language. |
| Language.ROMANIAN | Romanian language. |
| Language.RUSSIAN | Russian language. |
| Language.SWEDISH | Swedish language. |
| Language.SLOVAK | Slovak language. |
| Language.SLOVENIAN | Slovenian language. |
| Language.SPANISH | Spanish language. |
| Language.SERBIAN | Serbian language. |
| Language.THAI | Thai language. |
| Language.TURKISH | Turkish language. |
| Language.UKRANIAN | Ukrainian language. |
| Language.VIETNAMESE | Vietnamese language. |
| Language.CHINESE_SIMPLIFIED | Chinese Simplified language. |
| Language.CHINESE_TRADITIONAL | Chinese Traditional language. |
| Language.ZULU | Zulu language. |
#### Unit
| Constant | Description |
|----------------------|------------------------------------------------|
| Unit.METRIC_SYSTEM | Celsius, meter/sec, hPa, mm(rain, snow). |
| Unit.IMPERIAL_SYSTEM | Fahrenheit, miles/hour, hPa, mm(rain, snow). |
| Unit.STANDARD_SYSTEM | Kelvin, meter/sec, hPa, mm(rain, snow). |
### Dependencies
* com.fasterxml.jackson.core:jackson-databind:2.12.2
* org.slf4j:slf4j-api:1.7.30 (*compile*)
* org.junit.jupiter:junit-jupiter-engine:5.7.1 (*test*)
* org.junit.platform:junit-platform-runner:1.7.1 (*test*)
+58 -12
View File
@@ -6,7 +6,7 @@
<groupId>com.github.prominence</groupId> <groupId>com.github.prominence</groupId>
<artifactId>openweathermap-api</artifactId> <artifactId>openweathermap-api</artifactId>
<version>1.0</version> <version>2.1.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Java OpenWeatherMap API</name> <name>Java OpenWeatherMap API</name>
@@ -27,7 +27,7 @@
<licenses> <licenses>
<license> <license>
<name>MIT License</name> <name>MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url> <url>https://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution> <distribution>repo</distribution>
</license> </license>
</licenses> </licenses>
@@ -61,6 +61,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration> <configuration>
<source>8</source> <source>8</source>
<target>8</target> <target>8</target>
@@ -69,17 +70,17 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version> <version>3.2.0</version>
<configuration> <configuration>
<excludes> <excludes>
<exclude>ApplicationTest.class</exclude> <exclude>**/test/*</exclude>
</excludes> </excludes>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.sonatype.plugins</groupId> <groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId> <artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.7</version> <version>1.6.8</version>
<extensions>true</extensions> <extensions>true</extensions>
<configuration> <configuration>
<serverId>ossrh</serverId> <serverId>ossrh</serverId>
@@ -90,7 +91,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId> <artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version> <version>3.2.1</version>
<executions> <executions>
<execution> <execution>
<id>attach-sources</id> <id>attach-sources</id>
@@ -103,7 +104,10 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>2.9.1</version> <version>3.2.0</version>
<configuration>
<source>8</source>
</configuration>
<executions> <executions>
<execution> <execution>
<id>attach-javadocs</id> <id>attach-javadocs</id>
@@ -116,7 +120,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId> <artifactId>maven-gpg-plugin</artifactId>
<version>1.5</version> <version>1.6</version>
<executions> <executions>
<execution> <execution>
<id>sign-artifacts</id> <id>sign-artifacts</id>
@@ -127,15 +131,57 @@
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.6</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
</plugins> </plugins>
</build> </build>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>fastjson</artifactId> <artifactId>jackson-databind</artifactId>
<version>1.2.44</version> <version>2.12.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.7.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.7.1</version>
</dependency> </dependency>
</dependencies> </dependencies>
</project> </project>
@@ -1,95 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api;
import com.github.prominence.openweathermap.api.constants.System;
import com.github.prominence.openweathermap.api.constants.Unit;
import com.github.prominence.openweathermap.api.exception.DataNotFoundException;
import com.github.prominence.openweathermap.api.exception.InvalidAuthTokenException;
import com.github.prominence.openweathermap.api.model.Coordinates;
import java.net.MalformedURLException;
import java.net.URL;
abstract class BasicRequester<T> extends AuthenticationTokenBasedRequester {
protected String language;
protected String unitSystem = Unit.STANDARD_SYSTEM;
protected String accuracy;
protected BasicRequester(String authToken) {
super(authToken);
}
public T getByCityId(String id) throws InvalidAuthTokenException, DataNotFoundException {
return executeRequest("?id=" + id);
}
public T getByCityName(String name) throws InvalidAuthTokenException, DataNotFoundException {
return executeRequest("?q=" + name);
}
public T getByCoordinates(double latitude, double longitude) throws InvalidAuthTokenException, DataNotFoundException {
return executeRequest("?lat=" + latitude + "&lon=" + longitude);
}
public T getByCoordinates(Coordinates coordinates) throws InvalidAuthTokenException, DataNotFoundException {
return getByCoordinates(coordinates.getLatitude(), coordinates.getLongitude());
}
public T getByZIPCode(String zipCode, String countryCode) throws InvalidAuthTokenException, DataNotFoundException {
return executeRequest("?zip=" + zipCode + "," + countryCode);
}
protected URL buildURL(String requestSpecificParameters) throws MalformedURLException {
StringBuilder urlBuilder = new StringBuilder(System.OPEN_WEATHER_API_URL);
urlBuilder.append(getRequestType());
urlBuilder.append(requestSpecificParameters);
urlBuilder.append("&appid=");
urlBuilder.append(authToken);
if (language != null) {
urlBuilder.append("&lang=");
urlBuilder.append(language);
}
if (!Unit.STANDARD_SYSTEM.equals(unitSystem)) {
urlBuilder.append("&units=");
urlBuilder.append(unitSystem);
}
if (accuracy != null) {
urlBuilder.append("&type=");
urlBuilder.append(accuracy);
}
return new URL(urlBuilder.toString());
}
protected abstract String getRequestType();
protected abstract T executeRequest(String requestSpecificParamsString) throws InvalidAuthTokenException, DataNotFoundException;
}
@@ -1,82 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api;
import com.github.prominence.openweathermap.api.constants.Unit;
import com.github.prominence.openweathermap.api.exception.DataNotFoundException;
import com.github.prominence.openweathermap.api.exception.InvalidAuthTokenException;
import com.github.prominence.openweathermap.api.model.response.HourlyForecast;
import com.github.prominence.openweathermap.api.utils.JsonUtils;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.io.IOException;
import java.io.InputStream;
public class HourlyForecastRequester extends BasicRequester<HourlyForecast> {
HourlyForecastRequester(String authToken) {
super(authToken);
}
public HourlyForecastRequester setLanguage(String language) {
this.language = language;
return this;
}
public HourlyForecastRequester setUnitSystem(String unitSystem) {
this.unitSystem = unitSystem;
return this;
}
public HourlyForecastRequester setAccuracy(String accuracy) {
this.accuracy = accuracy;
return this;
}
protected String getRequestType() {
return "forecast";
}
protected HourlyForecast executeRequest(String requestSpecificParameters) throws InvalidAuthTokenException, DataNotFoundException {
HourlyForecast forecastResponse = null;
try {
InputStream requestResult = RequestUtils.executeGetRequest(buildURL(requestSpecificParameters));
forecastResponse = (HourlyForecast)JsonUtils.parseJson(requestResult, HourlyForecast.class);
char temperatureUnit = Unit.getTemperatureUnit(unitSystem);
String windUnit = Unit.getWindUnit(unitSystem);
forecastResponse.getForecasts().forEach(forecastInfo -> {
forecastInfo.getWind().setUnit(windUnit);
forecastInfo.getWeatherInfo().setTemperatureUnit(temperatureUnit);
});
} catch (IOException ex) {
ex.printStackTrace();
}
return forecastResponse;
}
}
@@ -0,0 +1,77 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api;
import com.github.prominence.openweathermap.api.annotation.SubscriptionAvailability;
import com.github.prominence.openweathermap.api.request.forecast.free.FiveDayThreeHourStepForecastRequester;
import com.github.prominence.openweathermap.api.request.forecast.free.FiveDayThreeHourStepForecastRequesterImpl;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherRequester;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherRequesterImpl;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.weather.CurrentWeatherRequesterImpl;
import static com.github.prominence.openweathermap.api.enums.SubscriptionPlan.*;
/**
* The main public API client to communicate with OpenWeatherMap services.
* Requires API key for usage. More info on the website <a href="https://openweathermap.org/api">https://openweathermap.org/api</a>.
*/
public class OpenWeatherMapClient {
private final String apiKey;
/**
* Created OpenWeatherMap client object.
* @param apiKey API key obtained on <a href="https://home.openweathermap.org/api_keys">OpenWeatherMap site</a>.
*/
public OpenWeatherMapClient(String apiKey) {
this.apiKey = apiKey;
}
/**
* Current Weather <a href="https://openweathermap.org/current">API</a>.
* @return requester for retrieving current weather information.
*/
@SubscriptionAvailability(plans = ALL)
public CurrentWeatherRequester currentWeather() {
return new CurrentWeatherRequesterImpl(apiKey);
}
/**
* 5 Day / 3 Hour Forecast <a href="https://openweathermap.org/forecast5">API</a>.
* @return requester for retrieving 5 day/3-hour weather forecast information.
*/
@SubscriptionAvailability(plans = ALL)
public FiveDayThreeHourStepForecastRequester forecast5Day3HourStep() {
return new FiveDayThreeHourStepForecastRequesterImpl(apiKey);
}
/**
* One Call <a href="https://openweathermap.org/api/one-call-api">API</a>.
* To get information about current weather, minute forecast for 1 hour, hourly forecast for 48 hours, daily forecast for 7 days and government weather alerts.
* @return requester for retrieving one call weather information.
*/
@SubscriptionAvailability(plans = ALL)
public OneCallWeatherRequester oneCall() {
return new OneCallWeatherRequesterImpl(apiKey);
}
}
@@ -1,77 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api;
import com.github.prominence.openweathermap.api.constants.Unit;
import com.github.prominence.openweathermap.api.exception.DataNotFoundException;
import com.github.prominence.openweathermap.api.exception.InvalidAuthTokenException;
import com.github.prominence.openweathermap.api.model.response.Weather;
import com.github.prominence.openweathermap.api.utils.JsonUtils;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.io.IOException;
import java.io.InputStream;
public class WeatherRequester extends BasicRequester<Weather> {
WeatherRequester(String authToken) {
super(authToken);
}
public WeatherRequester setLanguage(String language) {
this.language = language;
return this;
}
public WeatherRequester setUnitSystem(String unitSystem) {
this.unitSystem = unitSystem;
return this;
}
public WeatherRequester setAccuracy(String accuracy) {
this.accuracy = accuracy;
return this;
}
protected String getRequestType() {
return "weather";
}
protected Weather executeRequest(String requestSpecificParameters) throws InvalidAuthTokenException, DataNotFoundException {
Weather weather = null;
try {
InputStream requestResult = RequestUtils.executeGetRequest(buildURL(requestSpecificParameters));
weather = (Weather)JsonUtils.parseJson(requestResult, Weather.class);
weather.getWind().setUnit(Unit.getWindUnit(unitSystem));
weather.getWeatherInfo().setTemperatureUnit(Unit.getTemperatureUnit(unitSystem));
} catch (IOException ex) {
ex.printStackTrace();
}
return weather;
}
}
@@ -0,0 +1,43 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.annotation;
import com.github.prominence.openweathermap.api.enums.SubscriptionPlan;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker-type annotation to specify what type of license it needs to have to use API method.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface SubscriptionAvailability {
/**
* Marks method with subscription plan it needs to have to use the method.
* @return subscription plan.
*/
SubscriptionPlan[] plans();
}
@@ -1,63 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.constants;
public final class Language {
private Language() {}
public static final String ARABIC = "ar";
public static final String BULGARIAN = "bg";
public static final String CATALAN = "ca";
public static final String CZECH = "cz";
public static final String GERMAN = "de";
public static final String GREEK = "el";
public static final String ENGLISH = "en";
public static final String PERSIAN = "fa";
public static final String FINNISH = "fi";
public static final String FRENCH = "fr";
public static final String GALICIAN = "gl";
public static final String CROATIAN = "hr";
public static final String HUNGARIAN = "hu";
public static final String ITALIAN = "it";
public static final String JAPANESE = "ja";
public static final String KOREAN = "kr";
public static final String LATVIAN = "la";
public static final String LITHUANIAN = "lt";
public static final String MACEDONIAN = "mk";
public static final String DUTCH = "nl";
public static final String POLISH = "pl";
public static final String PORTUGUESE = "pt";
public static final String ROMANIAN ="ro";
public static final String RUSSIAN = "ru";
public static final String SWEDISH = "se";
public static final String SLOVAK = "sk";
public static final String SLOVENIAN = "sl";
public static final String SPANISH = "en";
public static final String TURKISH = "tr";
public static final String UKRANIAN = "uk";
public static final String VIETNAMESE = "vi";
public static final String CHINESE_SIMPLIFIED = "zh_cn";
public static final String CHINESE_TRADITIONAL = "zh_tw";
}
@@ -0,0 +1,273 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.enums;
/**
* An enumeration which lists all available languages for API usage.
* Usually it could be specified to get response with some fields translated into desired language.
*/
public enum Language {
/**
* Afrikaans language.
*/
AFRIKAANS("af"),
/**
* Albanian language.
*/
ALBANIAN("al"),
/**
* Arabic language.
*/
ARABIC("ar"),
/**
* Azerbaijani language.
*/
AZERBAIJANI("az"),
/**
* Bulgarian language.
*/
BULGARIAN("bg"),
/**
* Catalan language.
*/
CATALAN("ca"),
/**
* Czech language.
*/
CZECH("cz"),
/**
* Danish language
*/
DANISH("da"),
/**
* German language.
*/
GERMAN("de"),
/**
* Greek language.
*/
GREEK("el"),
/**
* English language.
*/
ENGLISH("en"),
/**
* Basque language.
*/
BASQUE("eu"),
/**
* Persian language.
*/
PERSIAN("fa"),
/**
* Finnish language.
*/
FINNISH("fi"),
/**
* French language.
*/
FRENCH("fr"),
/**
* Galician language.
*/
GALICIAN("gl"),
/**
* Hebrew language.
*/
HEBREW("he"),
/**
* Hindi language.
*/
HINDI("hi"),
/**
* Croatian language.
*/
CROATIAN("hr"),
/**
* Hungarian language.
*/
HUNGARIAN("hu"),
/**
* Indonesian language.
*/
INDONESIAN("id"),
/**
* Italian language.
*/
ITALIAN("it"),
/**
* Japanese language.
*/
JAPANESE("ja"),
/**
* Korean language.
*/
KOREAN("kr"),
/**
* Latvian language.
*/
LATVIAN("la"),
/**
* Lithuanian language.
*/
LITHUANIAN("lt"),
/**
* Macedonian language.
*/
MACEDONIAN("mk"),
/**
* Norwegian language.
*/
NORWEGIAN("no"),
/**
* Dutch language.
*/
DUTCH("nl"),
/**
* Polish language.
*/
POLISH("pl"),
/**
* Portuguese language.
*/
PORTUGUESE("pt"),
/**
* Português Brasil language.
*/
PORTUGUES_BRAZIL("pt_br"),
/**
* Romanian language.
*/
ROMANIAN ("ro"),
/**
* Russian language.
*/
RUSSIAN("ru"),
/**
* Swedish language.
*/
SWEDISH("se"),
/**
* Slovak language.
*/
SLOVAK("sk"),
/**
* Slovenian language.
*/
SLOVENIAN("sl"),
/**
* Spanish language.
*/
SPANISH("es"),
/**
* Serbian language.
*/
SERBIAN("sr"),
/**
* Thai language.
*/
THAI("th"),
/**
* Turkish language.
*/
TURKISH("tr"),
/**
* Ukranian language.
*/
UKRANIAN("uk"),
/**
* Vietnamese language.
*/
VIETNAMESE("vi"),
/**
* Chinese simplified language.
*/
CHINESE_SIMPLIFIED("zh_cn"),
/**
* Chinese traditional language.
*/
CHINESE_TRADITIONAL("zh_tw"),
/**
* Zulu language.
*/
ZULU("zu");
private final String value;
Language(String value) {
this.value = value;
}
/**
* Returns language's value.
* @return value.
*/
public String getValue() {
return value;
}
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.enums;
/**
* The enum One call result options.
*/
public enum OneCallResultOptions {
/**
* Current one call result options.
*/
CURRENT("current"),
/**
* Minutely one call result options.
*/
MINUTELY("minutely"),
/**
* Hourly one call result options.
*/
HOURLY("hourly"),
/**
* Daily one call result options.
*/
DAILY("daily"),
/**
* Alerts one call result options.
*/
ALERTS("alerts");
private final String value;
OneCallResultOptions(String value) {
this.value = value;
}
/**
* Gets value.
*
* @return the value
*/
public String getValue() {
return value;
}
}
@@ -0,0 +1,59 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.enums;
/**
* An enumeration with all available subscription plans.
* More information <a href="https://openweathermap.org/price">at official website</a>.
*/
public enum SubscriptionPlan {
/**
* Free subscription plan.
*/
FREE,
/**
* Startup subscription plan.
*/
STARTUP,
/**
* Developer subscription plan.
*/
DEVELOPER,
/**
* Professional subscription plan.
*/
PROFESSIONAL,
/**
* Enterprise subscription plan.
*/
ENTERPRISE,
/**
* All existing subscription plans.
*/
ALL,
}
@@ -0,0 +1,88 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.enums;
/**
* An enumeration for supported unit systems with helper methods.
*/
public enum UnitSystem {
/**
* Metric units: Celsius, meter/sec, hPa, mm(rain, snow).
*/
METRIC("metric"),
/**
* Imperial units: Fahrenheit, miles/hour, hPa, mm(rain, snow).
*/
IMPERIAL("imperial"),
/**
* OpenWeatherMap standard units: Kelvin, meter/sec, hPa, mm(rain, snow).
*/
STANDARD("standard");
private final String value;
UnitSystem(String value) {
this.value = value;
}
/**
* Returns wind unit for current unit system.
* @return wind unit.
*/
public String getWindUnit() {
switch (this) {
case IMPERIAL:
return "miles/hour";
case STANDARD:
case METRIC:
default:
return "meter/sec";
}
}
/**
* Returns temperature unit for current unit system.
* @return temperature unit.
*/
public String getTemperatureUnit() {
switch (this) {
case METRIC:
return "°C";
case IMPERIAL:
return "°F";
case STANDARD:
default:
return "";
}
}
/**
* Returns unit system value.
* @return value unit system.
*/
public String getValue() {
return value;
}
}
@@ -0,0 +1,375 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.enums;
import java.util.Arrays;
import java.util.Optional;
/**
* Represents weather condition and related information.
* More details <a href="https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2">here</a>.
*/
public enum WeatherCondition {
// Group 2xx: Thunderstorm
/**
* The thunderstorm with light rain.
*/
THUNDERSTORM_LIGHT_RAIN(200, "Thunderstorm", "thunderstorm with light rain", "11"),
/**
* The thunderstorm with rain.
*/
THUNDERSTORM_RAIN(201, "Thunderstorm", "thunderstorm with rain", "11"),
/**
* The thunderstorm with heavy rain.
*/
THUNDERSTORM_HEAVY_RAIN(202, "Thunderstorm", "thunderstorm with heavy rain", "11"),
/**
* The light thunderstorm.
*/
THUNDERSTORM_LIGHT(210, "Thunderstorm", "light thunderstorm", "11"),
/**
* The thunderstorm.
*/
THUNDERSTORM(211, "Thunderstorm", "thunderstorm", "11"),
/**
* The heavy thunderstorm.
*/
THUNDERSTORM_HEAVY(212, "Thunderstorm", "heavy thunderstorm", "11"),
/**
* The ragged thunderstorm.
*/
THUNDERSTORM_RAGGED(221, "Thunderstorm", "ragged thunderstorm", "11"),
/**
* The thunderstorm with light drizzle.
*/
THUNDERSTORM_LIGHT_DRIZZLE(230, "Thunderstorm", "thunderstorm with light drizzle", "11"),
/**
* The thunderstorm with drizzle.
*/
THUNDERSTORM_DRIZZLE(231, "Thunderstorm", "thunderstorm with drizzle", "11"),
/**
* The thunderstorm with heavy drizzle.
*/
THUNDERSTORM_HEAVY_DRIZZLE(232, "Thunderstorm", "thunderstorm with heavy drizzle", "11"),
// Group 3xx: Drizzle
/**
* The light intensity drizzle.
*/
DRIZZLE_LIGHT(300, "Drizzle", "light intensity drizzle", "09"),
/**
* The drizzle.
*/
DRIZZLE(301, "Drizzle", "drizzle", "09"),
/**
* The heavy intensity drizzle.
*/
DRIZZLE_HEAVY(302, "Drizzle", "heavy intensity drizzle", "09"),
/**
* The light intensity drizzle rain.
*/
DRIZZLE_LIGHT_RAIN(310, "Drizzle", "light intensity drizzle rain", "09"),
/**
* The drizzle rain.
*/
DRIZZLE_RAIN(311, "Drizzle", "drizzle rain", "09"),
/**
* The heavy intensity drizzle rain.
*/
DRIZZLE_HEAVY_RAIN(312, "Drizzle", "heavy intensity drizzle rain", "09"),
/**
* The shower rain and drizzle.
*/
DRIZZLE_SHOWER_RAIN(313, "Drizzle", "shower rain and drizzle", "09"),
/**
* The heavy shower rain and drizzle.
*/
DRIZZLE_HEAVY_SHOWER_RAIN(314, "Drizzle", "heavy shower rain and drizzle", "09"),
/**
* The shower drizzle.
*/
DRIZZLE_SHOWER(321, "Drizzle", "shower drizzle", "09"),
// Group 5xx: Rain
/**
* The light rain.
*/
RAIN_LIGHT(500, "Rain", "light rain", "10"),
/**
* The moderate rain.
*/
RAIN_MODERATE(501, "Rain", "moderate rain", "10"),
/**
* The heavy intensity rain.
*/
RAIN_HEAVY(502, "Rain", "heavy intensity rain", "10"),
/**
* The very heavy rain.
*/
RAIN_VERY_HEAVY(503, "Rain", "very heavy rain", "10"),
/**
* The very heavy rain.
*/
RAIN_EXTREME(504, "Rain", "very heavy rain", "10"),
/**
* The freezing rain.
*/
RAIN_FREEZING(511, "Rain", "freezing rain", "10"),
/**
* The light intensity shower rain.
*/
RAIN_LIGHT_SHOWER(520, "Rain", "light intensity shower rain", "10"),
/**
* The shower rain.
*/
RAIN_SHOWER(521, "Rain", "shower rain", "10"),
/**
* The heavy intensity shower rain.
*/
RAIN_HEAVY_SHOWER(522, "Rain", "heavy intensity shower rain", "10"),
/**
* The ragged shower rain.
*/
RAIN_RAGGED_SHOWER(531, "Rain", "ragged shower rain", "10"),
// Group 6xx: Snow
/**
* The light snow.
*/
SNOW_LIGHT(600, "Snow", "light snow", "13"),
/**
* The snow.
*/
SNOW(601, "Snow", "snow", "13"),
/**
* The heavy snow.
*/
SNOW_HEAVY(602, "Snow", "heavy snow", "13"),
/**
* The sleet.
*/
SNOW_SLEET(611, "Snow", "sleet", "13"),
/**
* The light shower sleet.
*/
SNOW_LIGHT_SHOWER_SLEET(612, "Snow", "light shower sleet", "13"),
/**
* The shower sleet.
*/
SNOW_SHOWER_SLEET(613, "Snow", "shower sleet", "13"),
/**
* The light rain and snow.
*/
SNOW_LIGHT_RAIN_AND_SNOW(615, "Snow", "light rain and snow", "13"),
/**
* The rain and snow.
*/
SNOW_RAIN_AND_SNOW(616, "Snow", "rain and snow", "13"),
/**
* The light shower snow.
*/
SNOW_LIGHT_SHOWER_SNOW(620, "Snow", "light shower snow", "13"),
/**
* The shower snow.
*/
SNOW_SHOWER_SNOW(621, "Snow", "shower snow", "13"),
/**
* The heavy shower snow.
*/
SNOW_HEAVY_SHOWER_SNOW(622, "Snow", "heavy shower snow", "13"),
// Group 7xx: Atmosphere
/**
* The mist.
*/
MIST(701, "Mist", "mist", "50"),
/**
* The smoke.
*/
SMOKE(711, "Smoke", "smoke", "50"),
/**
* The haze.
*/
HAZE(721, "Haze", "haze", "50"),
/**
* The sand/dust whirls.
*/
DUST_WHIRLS(731, "Dust", "sand/dust whirls", "50"),
/**
* The fog.
*/
FOG(741, "Fog", "fog", "50"),
/**
* The sand.
*/
SAND(751, "Sand", "sand", "50"),
/**
* The dust.
*/
DUST(761, "Dust", "dust", "50"),
/**
* The volcanic ash.
*/
ASH(762, "Ash", "volcanic ash", "50"),
/**
* The squall.
*/
SQUALL(771, "Squall", "squalls", "50"),
/**
* The tornado.
*/
TORNADO(781, "Tornado", "tornado", "50"),
// Group 800: Clear
/**
* The clear sky.
*/
CLEAR(800, "Clear", "clear sky", "01"),
// Group 80x: Clouds
/**
* A few clouds: 11-25%.
*/
CLOUDS_FEW(801, "Clouds", "few clouds: 11-25%", "02"),
/**
* A scattered clouds: 25-50%.
*/
CLOUDS_SCATTERED(802, "Clouds", "scattered clouds: 25-50%", "03"),
/**
* A broken clouds: 51-84%.
*/
CLOUDS_BROKEN(803, "Clouds", "broken clouds: 51-84%", "04"),
/**
* An overcast clouds: 85-100%.
*/
CLOUDS_OVERCAST(804, "Clouds", "overcast clouds: 85-100%", "04");
private final int id;
private final String name;
private final String description;
private final String iconId;
private WeatherCondition(int id, String name, String description, String iconId) {
this.id = id;
this.name = name;
this.description = description;
this.iconId = iconId;
}
/**
* Gets id.
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Gets name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Gets day icon id.
*
* @return the day icon id
*/
public String getDayIconId() {
return iconId + 'd';
}
/**
* Gets night icon id.
*
* @return the night icon id
*/
public String getNightIconId() {
return iconId + 'n';
}
/**
* Gets day icon url.
*
* @return the day icon url
*/
public String getDayIconUrl() {
return getIconUrl(getDayIconId());
}
/**
* Gets night icon url.
*
* @return the night icon url
*/
public String getNightIconUrl() {
return getIconUrl(getNightIconId());
}
/**
* Gets icon url.
*
* @param iconId the icon id
* @return the icon url
*/
public static String getIconUrl(String iconId) {
return "http://openweathermap.org/img/w/" + iconId + ".png";
}
/**
* Gets {@link WeatherCondition} by id.
*
* @param id the id
* @return the by id
*/
public static WeatherCondition getById(int id) {
final Optional<WeatherCondition> optionalWeatherCondition = Arrays.stream(values()).filter(weatherCondition -> weatherCondition.getId() == id).findFirst();
return optionalWeatherCondition.orElse(null);
}
@Override
public String toString() {
return "Weather condition(" + id + "): " + name + '(' + description + ')';
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -22,10 +22,16 @@
package com.github.prominence.openweathermap.api.exception; package com.github.prominence.openweathermap.api.exception;
public class InvalidAuthTokenException extends Exception { /**
* An exception that could be thrown in case of your API key is invalid or your subscription plan does not cover requested functionality.
* Subscription plans information you can find <a href="https://openweathermap.org/price">here</a>.
* API Keys could be checked in <a href="https://home.openweathermap.org/api_keys/">your profile</a>.
*/
public class InvalidAuthTokenException extends RuntimeException {
/**
* Creates {@link InvalidAuthTokenException} exception with default message.
*/
public InvalidAuthTokenException() { public InvalidAuthTokenException() {
super("Check you authentication token! You can get it here: https://home.openweathermap.org/api_keys/."); super("Authentication token wasn't set or requested functionality is not permitted for your subscription plan. Please, check https://home.openweathermap.org/api_keys/ and https://openweathermap.org/price.");
} }
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,37 +20,29 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api.constants; package com.github.prominence.openweathermap.api.exception;
public final class Unit { /**
* An exception that could be thrown in several cases:
private Unit() {} * <ul>
* <li>There is no data found for your query(wrong coordinates somewhere in the sea, some distant place, etc.);</li>
public static final String METRIC_SYSTEM = "metric"; * <li>Request is malformed. An occasion to report an <a href="https://github.com/Prominence/openweathermap-java-api/issues">issue</a>;</li>
public static final String IMPERIAL_SYSTEM = "imperial"; * <li>Any other unpredictable problems.</li>
public static final String STANDARD_SYSTEM = "standard"; * </ul>
*/
public static String getWindUnit(String type) { public class NoDataFoundException extends RuntimeException {
switch (type) { /**
case IMPERIAL_SYSTEM: * Creates {@link NoDataFoundException} with default message.
return "miles/hour"; */
case STANDARD_SYSTEM: public NoDataFoundException() {
case METRIC_SYSTEM: super("Data for provided parameters wasn't found. Please, check requested location.");
default:
return "meter/sec";
}
} }
public static char getTemperatureUnit(String type) { /**
switch (type) { * Creates {@link NoDataFoundException} with message from another throwable.
case METRIC_SYSTEM: * @param throwable source throwable.
return '℃'; */
case IMPERIAL_SYSTEM: public NoDataFoundException(Throwable throwable) {
return '℉'; super(throwable.getMessage(), throwable.getCause());
case STANDARD_SYSTEM:
default:
return '';
}
} }
} }
@@ -0,0 +1,155 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import java.util.Objects;
/**
* The AtmosphericPressure type represents atmospheric pressure value.
* Its value can only be a double in [0, +∞) range.
*/
public class AtmosphericPressure {
private static final String DEFAULT_UNIT = "hPa";
private double value;
private Double seaLevelValue;
private Double groundLevelValue;
/**
* Instantiates a new Pressure.
*
* @param value the value representing pressure value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
private AtmosphericPressure(double value) {
this.value = value;
}
/**
* Static method for {@link AtmosphericPressure} creation with value checking.
* @param value atmospheric pressure value.
* @return instantiated {@link AtmosphericPressure} object.
*/
public static AtmosphericPressure withValue(double value) {
if (value < 0) {
throw new IllegalArgumentException("Atmospheric pressure value must be in [0, +∞) range.");
}
return new AtmosphericPressure(value);
}
/**
* Returns pressure value.
*
* @return pressure value.
*/
public double getValue() {
return value;
}
/**
* Sets pressure value.
*
* @param value new pressure value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setValue(double value) {
if (value < 0) {
throw new IllegalArgumentException("Atmospheric pressure value must be in [0, +∞) range.");
}
this.value = value;
}
/**
* Gets sea level value.
*
* @return the sea level value.
*/
public Double getSeaLevelValue() {
return seaLevelValue;
}
/**
* Sets sea level value.
*
* @param seaLevelValue the sea level value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setSeaLevelValue(double seaLevelValue) {
if (seaLevelValue < 0) {
throw new IllegalArgumentException("Atmospheric pressure value must be in [0, +∞) range.");
}
this.seaLevelValue = seaLevelValue;
}
/**
* Gets ground level value.
*
* @return the ground level value.
*/
public Double getGroundLevelValue() {
return groundLevelValue;
}
/**
* Sets ground level value.
*
* @param groundLevelValue the ground level value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setGroundLevelValue(double groundLevelValue) {
if (groundLevelValue < 0) {
throw new IllegalArgumentException("Atmospheric pressure value must be in [0, +∞) range.");
}
this.groundLevelValue = groundLevelValue;
}
/**
* Returns pressure unitSystem. Constantly equals to 'hPa'.
*
* @return the pressure unitSystem.
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AtmosphericPressure)) return false;
AtmosphericPressure atmosphericPressure = (AtmosphericPressure) o;
return Double.compare(atmosphericPressure.value, value) == 0 &&
Objects.equals(seaLevelValue, atmosphericPressure.seaLevelValue) &&
Objects.equals(groundLevelValue, atmosphericPressure.groundLevelValue);
}
@Override
public int hashCode() {
return Objects.hash(value, seaLevelValue, groundLevelValue);
}
@Override
public String toString() {
return "Pressure: " + value + ' ' + getUnit();
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -22,40 +22,85 @@
package com.github.prominence.openweathermap.api.model; package com.github.prominence.openweathermap.api.model;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Objects; import java.util.Objects;
/**
* The Clouds type represents cloudiness value percentage.
* Its value can only be an integer in [0, 100] range.
*/
public class Clouds { public class Clouds {
private static final String DEFAULT_UNIT = "%";
@JSONField(name = "all") private byte value;
// Cloudiness, %
private byte cloudiness;
public byte getCloudiness() { /**
return cloudiness; * Instantiates a new Clouds.
*
* @param value the value representing cloudiness percentage.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
private Clouds(byte value) {
this.value = value;
} }
public void setCloudiness(byte cloudiness) { /**
this.cloudiness = cloudiness; * Static method for {@link Clouds} creation with value checking.
* @param value clouds percentage value.
* @return instantiated {@link Clouds} object.
*/
public static Clouds withValue(byte value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Cloudiness value must be in [0, 100] range.");
}
return new Clouds(value);
} }
@Override /**
public String toString() { * Returns cloudiness percentage value.
return "Cloudiness: " + cloudiness + "%"; *
* @return cloudiness percentage.
*/
public byte getValue() {
return value;
}
/**
* Sets cloudiness percentage value.
*
* @param value new cloudiness value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setValue(byte value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Cloudiness value must be in [0, 100] range.");
}
this.value = value;
}
/**
* Returns cloudiness unitSystem. Constantly equals to '%'.
*
* @return the cloudiness unitSystem.
*/
public String getUnit() {
return DEFAULT_UNIT;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (!(o instanceof Clouds)) return false;
Clouds clouds = (Clouds) o; Clouds clouds = (Clouds) o;
return cloudiness == clouds.cloudiness; return value == clouds.value;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(value);
}
return Objects.hash(cloudiness); @Override
public String toString() {
return "Clouds: " + value + getUnit();
} }
} }
@@ -0,0 +1,117 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import java.util.Objects;
/**
* Represents some location by its latitude and longitude.
*/
public class Coordinate {
private double latitude;
private double longitude;
private Coordinate() {
}
/**
* Method for {@link Coordinate} creation with correctness check.
* @param latitude latitude
* @param longitude longitude
* @return coordinate object.
*/
public static Coordinate of(double latitude, double longitude) {
final Coordinate coordinate = new Coordinate();
coordinate.setLatitude(latitude);
coordinate.setLongitude(longitude);
return coordinate;
}
/**
* Sets latitude with checks.
* @param latitude latitude value
*/
public void setLatitude(double latitude) {
if (latitude < -90 || latitude > 90) {
throw new IllegalArgumentException("Latitude value must be in the next range: [-90.0; 90.0].");
}
this.latitude = latitude;
}
/**
* Sets longitude with checks.
* @param longitude longitude value
*/
public void setLongitude(double longitude) {
if (longitude < -180 || longitude > 180) {
throw new IllegalArgumentException("Longitude value must be in the next range: [-180.0; 180.0].");
}
this.longitude = longitude;
}
/**
* Returns latitude.
* @return latitude
*/
public double getLatitude() {
return latitude;
}
/**
* Returns longitude.
* @return longitude
*/
public double getLongitude() {
return longitude;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Coordinate)) return false;
Coordinate that = (Coordinate) o;
return Double.compare(that.latitude, latitude) == 0 &&
Double.compare(that.longitude, longitude) == 0;
}
@Override
public int hashCode() {
return Objects.hash(latitude, longitude);
}
@Override
public String toString() {
return formatAsDegree(latitude) +
", " + formatAsDegree(longitude);
}
private String formatAsDegree(double value) {
int degrees = (int) value;
double secondsDouble = value % 1 * 60;
int minutes = (int) secondsDouble;
int seconds = (int) (secondsDouble % 1 * 60);
return String.format("%s° %s %s″", degrees, minutes, seconds);
}
}
@@ -0,0 +1,200 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import java.util.Objects;
/**
* Represents coordinate rectangle by its bottom-left and top-right coordinates.
*/
public class CoordinateRectangle {
private final double longitudeLeft;
private final double latitudeBottom;
private final double longitudeRight;
private final double latitudeTop;
private CoordinateRectangle(double longitudeLeft, double latitudeBottom, double longitudeRight, double latitudeTop) {
this.longitudeLeft = longitudeLeft;
this.latitudeBottom = latitudeBottom;
this.longitudeRight = longitudeRight;
this.latitudeTop = latitudeTop;
}
/**
* Method for {@link CoordinateRectangle} creation with correctness check.
* @param longitudeLeft left longitude
* @param latitudeBottom bottom latitude
* @param longitudeRight right longitude
* @param latitudeTop tip latitude
* @return coordinate rectangle object.
*/
public static CoordinateRectangle withValues(double longitudeLeft, double latitudeBottom, double longitudeRight, double latitudeTop) {
if (latitudeBottom < -90 || latitudeTop < -90 || latitudeBottom > 90 || latitudeTop > 90) {
throw new IllegalArgumentException("Latitude value must be in the next range: [-90.0; 90.0].");
}
if (longitudeLeft < -180 || longitudeRight < -180 || longitudeLeft > 180 || longitudeRight > 180) {
throw new IllegalArgumentException("Longitude value must be in the next range: [-180.0; 180.0].");
}
return new CoordinateRectangle(longitudeLeft, latitudeBottom, longitudeRight, latitudeTop);
}
/**
* Returns left longitude value.
* @return left longitude
*/
public double getLongitudeLeft() {
return longitudeLeft;
}
/**
* Returns bottom latitude value.
* @return bottom latitude
*/
public double getLatitudeBottom() {
return latitudeBottom;
}
/**
* Returns right longitude value.
* @return right longitude
*/
public double getLongitudeRight() {
return longitudeRight;
}
/**
* Returns top latitude value.
* @return top latitude
*/
public double getLatitudeTop() {
return latitudeTop;
}
/**
* Formatted coordinate rectangle string.
* @return formatted string
*/
public String getFormattedRequestString() {
return longitudeLeft + "," + latitudeBottom + "," + longitudeRight + "," + latitudeTop;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CoordinateRectangle)) return false;
CoordinateRectangle rectangle = (CoordinateRectangle) o;
return Double.compare(rectangle.longitudeLeft, longitudeLeft) == 0 &&
Double.compare(rectangle.latitudeBottom, latitudeBottom) == 0 &&
Double.compare(rectangle.longitudeRight, longitudeRight) == 0 &&
Double.compare(rectangle.latitudeTop, latitudeTop) == 0;
}
@Override
public int hashCode() {
return Objects.hash(longitudeLeft, latitudeBottom, longitudeRight, latitudeTop);
}
@Override
public String toString() {
return "Rectangle: " + getFormattedRequestString();
}
/**
* Builder for CoordinateRectangle class.
*/
public static class Builder {
private Double longitudeLeft;
private Double latitudeBottom;
private Double longitudeRight;
private Double latitudeTop;
/**
* Creates Builder object.
*/
public Builder() {
}
/**
* Sets left longitude with correctness check.
* @param longitudeLeft left longitude
* @return builder object
*/
public Builder setLongitudeLeft(double longitudeLeft) {
if (longitudeLeft < -180 || longitudeLeft > 180) {
throw new IllegalArgumentException("Longitude value must be in the next range: [-180.0; 180.0].");
}
this.longitudeLeft = longitudeLeft;
return this;
}
/**
* Sets bottom latitude with correctness check.
* @param latitudeBottom bottom latitude
* @return builder object
*/
public Builder setLatitudeBottom(double latitudeBottom) {
if (latitudeBottom < -90 || latitudeBottom > 90) {
throw new IllegalArgumentException("Latitude value must be in the next range: [-90.0; 90.0].");
}
this.latitudeBottom = latitudeBottom;
return this;
}
/**
* Sets right longitude with correctness check.
* @param longitudeRight right longitude
* @return builder object
*/
public Builder setLongitudeRight(double longitudeRight) {
if (longitudeRight < -180 || longitudeRight > 180) {
throw new IllegalArgumentException("Longitude value must be in the next range: [-180.0; 180.0].");
}
this.longitudeRight = longitudeRight;
return this;
}
/**
* Sets top latitude with correctness check.
* @param latitudeTop top latitude
* @return builder object
*/
public Builder setLatitudeTop(double latitudeTop) {
if (latitudeTop < -90 || latitudeTop > 90) {
throw new IllegalArgumentException("Latitude value must be in the next range: [-90.0; 90.0].");
}
this.latitudeTop = latitudeTop;
return this;
}
/**
* Builds {@link CoordinateRectangle} object with correctness check.
* @return {@link CoordinateRectangle} built object.
*/
public CoordinateRectangle build() {
if (longitudeLeft == null || latitudeBottom == null || longitudeRight == null || latitudeTop == null) {
throw new IllegalStateException("Not all fields were set.");
}
return new CoordinateRectangle(longitudeLeft, latitudeBottom, longitudeRight, latitudeTop);
}
}
}
@@ -1,77 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Objects;
public class Coordinates {
@JSONField(name = "lat")
// City geo location, latitude
private float latitude;
@JSONField(name = "lon")
// City geo location, longitude
private float longitude;
public Coordinates(float latitude, float longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
@Override
public String toString() {
return "latitude=" + latitude + ", longitude=" + longitude;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordinates that = (Coordinates) o;
return Double.compare(that.latitude, latitude) == 0 &&
Double.compare(that.longitude, longitude) == 0;
}
@Override
public int hashCode() {
return Objects.hash(latitude, longitude);
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
/**
* Enumeration for time of a day representation.
*/
public enum DayTime {
/**
* Day value.
*/
DAY("d"),
/**
* Night value.
*/
NIGHT("n");
private final String value;
DayTime(String value) {
this.value = value;
}
/**
* Returns time of a day value.
* @return string value
*/
public String getValue() {
return value;
}
}
@@ -0,0 +1,106 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import java.util.Objects;
/**
* The Humidity type represents humidity value percentage.
* Its value can only be an integer in [0, 100] range.
*/
public class Humidity {
private static final String DEFAULT_UNIT = "%";
private int value;
/**
* Instantiates a new Humidity.
*
* @param value the value representing humidity percentage.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
private Humidity(byte value) {
this.value = value;
}
/**
* Creates {@link Humidity} object with correctness check.
* @param value humidity
* @return created {@link Humidity} object
*/
public static Humidity withValue(byte value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Humidity value must be in [0, 100] range.");
}
return new Humidity(value);
}
/**
* Returns humidity percentage value.
*
* @return humidity percentage.
*/
public int getValue() {
return value;
}
/**
* Sets humidity percentage value.
*
* @param value new humidity value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setValue(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("Humidity value must be in [0, 100] range.");
}
this.value = value;
}
/**
* Returns humidity unitSystem. Constantly equals to '%'.
*
* @return the humidity unitSystem.
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Humidity)) return false;
Humidity humidity = (Humidity) o;
return value == humidity.value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return "Humidity: " + value + getUnit();
}
}
@@ -1,65 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Objects;
public class Rain {
@JSONField(name = "3h")
// Rain volume for the last 3 hours
private byte rainVolumeLast3Hrs;
public byte getRainVolumeLast3Hrs() {
return rainVolumeLast3Hrs;
}
public void setRainVolumeLast3Hrs(byte rainVolumeLast3Hrs) {
this.rainVolumeLast3Hrs = rainVolumeLast3Hrs;
}
public String getUnit() {
return "mm";
}
@Override
public String toString() {
return "Rain(last 3 hrs): " + rainVolumeLast3Hrs + ' ' + getUnit();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rain rain = (Rain) o;
return rainVolumeLast3Hrs == rain.rainVolumeLast3Hrs;
}
@Override
public int hashCode() {
return Objects.hash(rainVolumeLast3Hrs);
}
}
@@ -0,0 +1,183 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import java.util.Objects;
/**
* Represents temperature values and unit.
*/
public class Temperature {
private double value;
private Double maxTemperature;
private Double minTemperature;
private Double feelsLike;
private String unit;
private Temperature(double value, String unit) {
this.value = value;
this.unit = unit;
}
/**
* Creates {@link Temperature} object with correctness check.
* @param value temperature value
* @param unit temperature unit
* @return temperature object
*/
public static Temperature withValue(double value, String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
return new Temperature(value, unit);
}
/**
* Returns temperature value.
* @return value
*/
public double getValue() {
return value;
}
/**
* Sets temperature value.
* @param value temperature
*/
public void setValue(double value) {
this.value = value;
}
/**
* Returns maximal temperature value.
* @return maximal temperature value
*/
public Double getMaxTemperature() {
return maxTemperature;
}
/**
* Sets maximal temperature value.
* @param maxTemperature maximal temperature
*/
public void setMaxTemperature(Double maxTemperature) {
this.maxTemperature = maxTemperature;
}
/**
* Returns minimal temperature value.
* @return minimal temperature value
*/
public Double getMinTemperature() {
return minTemperature;
}
/**
* Sets minimal temperature value.
* @param minTemperature minimal temperature
*/
public void setMinTemperature(Double minTemperature) {
this.minTemperature = minTemperature;
}
/**
* Returns 'feels like' temperature value.
* @return 'feels like' temperature value
*/
public Double getFeelsLike() {
return feelsLike;
}
/**
* Sets 'feels like' temperature value.
* @param feelsLike 'feels like' temperature
*/
public void setFeelsLike(Double feelsLike) {
this.feelsLike = feelsLike;
}
/**
* Returns temperature unit.
* @return unit
*/
public String getUnit() {
return unit;
}
/**
* Sets temperature unit with correctness check.
* @param unit temperature unit
*/
public void setUnit(String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Temperature)) return false;
Temperature that = (Temperature) o;
return Double.compare(that.value, value) == 0 &&
Objects.equals(maxTemperature, that.maxTemperature) &&
Objects.equals(minTemperature, that.minTemperature) &&
Objects.equals(feelsLike, that.feelsLike) &&
Objects.equals(unit, that.unit);
}
@Override
public int hashCode() {
return Objects.hash(value, maxTemperature, minTemperature, feelsLike, unit);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Temperature: ");
stringBuilder.append(value);
stringBuilder.append(' ');
stringBuilder.append(unit);
if (maxTemperature != null) {
stringBuilder.append(", Maximum value: ");
stringBuilder.append(maxTemperature);
stringBuilder.append(' ');
stringBuilder.append(unit);
}
if (minTemperature != null) {
stringBuilder.append(", Minimum value: ");
stringBuilder.append(minTemperature);
stringBuilder.append(' ');
stringBuilder.append(unit);
}
if (feelsLike != null) {
stringBuilder.append(", Feels like: ");
stringBuilder.append(feelsLike);
stringBuilder.append(' ');
stringBuilder.append(unit);
}
return stringBuilder.toString();
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -22,91 +22,115 @@
package com.github.prominence.openweathermap.api.model; package com.github.prominence.openweathermap.api.model;
import com.alibaba.fastjson.annotation.JSONField; import com.github.prominence.openweathermap.api.enums.WeatherCondition;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects; import java.util.Objects;
/**
* The type Weather state.
*/
public class WeatherState { public class WeatherState {
private final int id;
private final String name;
private final String description;
private String iconId;
private final WeatherCondition weatherConditionEnum;
@JSONField(name = "id") public WeatherState(Integer id, String name, String description) {
// Weather condition id this.id = id;
long conditionId; this.name = name;
this.description = description;
@JSONField(name = "main") this.weatherConditionEnum = WeatherCondition.getById(id);
// Group of weather parameters (Rain, Snow, Extreme etc.)
String weatherGroup;
@JSONField(name = "description")
// Weather condition within the group
String description;
@JSONField(name = "icon")
// Weather icon id
String iconId;
public long getConditionId() {
return conditionId;
} }
public void setConditionId(long conditionId) { /**
this.conditionId = conditionId; * Gets id.
*
* @return the id
*/
public int getId() {
return id;
} }
public String getWeatherGroup() { /**
return weatherGroup; * Gets name.
} *
* @return the name
public void setWeatherGroup(String weatherGroup) { */
this.weatherGroup = weatherGroup; public String getName() {
return name;
} }
/**
* Gets description.
*
* @return the description
*/
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { /**
this.description = description; * Gets icon id.
} *
* @return the icon id
*/
public String getIconId() { public String getIconId() {
return iconId; return iconId;
} }
/**
* Sets icon id.
*
* @param iconId the icon id
*/
public void setIconId(String iconId) { public void setIconId(String iconId) {
this.iconId = iconId; this.iconId = iconId;
} }
public URL getWeatherIconUrl() { /**
URL iconUrl = null; * Gets weather condition enum.
try { *
iconUrl = new URL("http://openweathermap.org/img/w/" + iconId + ".png"); * @return the weather condition enum
} catch (MalformedURLException e) { */
e.printStackTrace(); public WeatherCondition getWeatherConditionEnum() {
} return weatherConditionEnum;
return iconUrl;
} }
@Override /**
public String toString() { * Gets weather icon url.
return "Weather: " + description; *
* @return the weather icon url
*/
public String getWeatherIconUrl() {
if (iconId != null) {
return WeatherCondition.getIconUrl(iconId);
}
if (weatherConditionEnum != null) {
// return the default one for the current weather condition
return weatherConditionEnum.getDayIconUrl();
}
return null;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
WeatherState weatherState = (WeatherState) o; WeatherState that = (WeatherState) o;
return conditionId == weatherState.conditionId && return Objects.equals(id, that.id) &&
Objects.equals(weatherGroup, weatherState.weatherGroup) && Objects.equals(name, that.name) &&
Objects.equals(description, weatherState.description) && Objects.equals(description, that.description) &&
Objects.equals(iconId, weatherState.iconId); Objects.equals(iconId, that.iconId);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, name, description, iconId, weatherConditionEnum);
}
return Objects.hash(conditionId, weatherGroup, description, iconId); @Override
public String toString() {
return "Weather state: " + name + "(" + description + ").";
} }
} }
@@ -1,84 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model;
import com.alibaba.fastjson.annotation.JSONField;
import java.util.Objects;
public class Wind {
@JSONField(name = "speed")
// Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.
private float speed;
private String unit;
@JSONField(name = "deg")
// Wind direction, degrees (meteorological)
private short degrees;
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public short getDegrees() {
return degrees;
}
public void setDegrees(short degrees) {
this.degrees = degrees;
}
@Override
public String toString() {
return "Wind: " + speed + ' ' + unit + ", " + degrees + " degrees";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Wind wind = (Wind) o;
return Float.compare(wind.speed, speed) == 0 &&
degrees == wind.degrees;
}
@Override
public int hashCode() {
return Objects.hash(speed, degrees);
}
}
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import java.util.List;
import java.util.Objects;
/**
* Represents information about forecast for different timestamps.
*/
public class Forecast {
private Location location;
private List<WeatherForecast> weatherForecasts;
/**
* Returns location information.
* @return location
*/
public Location getLocation() {
return location;
}
/**
* Sets forecast location.
* @param location forecast location
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Returns list of weather forecasts for different timestamps.
* @return list of forecast-per-timestamp information.
*/
public List<WeatherForecast> getWeatherForecasts() {
return weatherForecasts;
}
/**
* Sets list of weather forecasts for different timestamps.
* @param weatherForecasts list of forecast information
*/
public void setWeatherForecasts(List<WeatherForecast> weatherForecasts) {
this.weatherForecasts = weatherForecasts;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Forecast forecast = (Forecast) o;
return Objects.equals(location, forecast.location) && Objects.equals(weatherForecasts, forecast.weatherForecasts);
}
@Override
public int hashCode() {
return Objects.hash(location, weatherForecasts);
}
@Override
public String toString() {
return "A forecast for " + location.getName() + " with " + weatherForecasts.size() + " timestamps.";
}
}
@@ -0,0 +1,235 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import com.github.prominence.openweathermap.api.model.Coordinate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;
/**
* Represents location information.
*/
public class Location {
private int id;
private String name;
private String countryCode;
private LocalDateTime sunriseTime;
private LocalDateTime sunsetTime;
private ZoneOffset zoneOffset;
private Coordinate coordinate;
private Long population;
private Location(int id, String name) {
this.id = id;
this.name = name;
}
/**
* Creates {@link Location} object with correctness check.
* @param id location id
* @param name location name
* @return location object
*/
public static Location withValues(int id, String name) {
if (name == null) {
throw new IllegalArgumentException("Name must be set.");
}
return new Location(id, name);
}
/**
* Returns ID.
* @return location ID
*/
public int getId() {
return id;
}
/**
* Sets location ID.
* @param id location id
*/
public void setId(int id) {
this.id = id;
}
/**
* Returns location name.
* @return location name
*/
public String getName() {
return name;
}
/**
* Sets location name.
* @param name location name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns country code.
* @return location country code
*/
public String getCountryCode() {
return countryCode;
}
/**
* Sets location country code.
* @param countryCode location country code
*/
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
/**
* Returns location sunrise time.
* @return sunrise time
*/
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets location sunrise time.
* @param sunriseTime sunrise time
*/
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Returns location sunset time.
* @return sunset time
*/
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets location sunset time.
* @param sunsetTime sunset time
*/
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
* Returns location timezone offset.
* @return timezone offset
*/
public ZoneOffset getZoneOffset() {
return zoneOffset;
}
/**
* Sets location timezone offset.
* @param zoneOffset timezone offset
*/
public void setZoneOffset(ZoneOffset zoneOffset) {
this.zoneOffset = zoneOffset;
}
/**
* Returns location coordinates.
* @return location coordinates.
*/
public Coordinate getCoordinate() {
return coordinate;
}
/**
* Sets location coordinates.
* @param coordinate location coordinates
*/
public void setCoordinate(Coordinate coordinate) {
this.coordinate = coordinate;
}
/**
* Sets location population.
* @return location population
*/
public Long getPopulation() {
return population;
}
/**
* Sets location population.
* @param population location population
*/
public void setPopulation(Long population) {
this.population = population;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Location)) return false;
Location location = (Location) o;
return id == location.id &&
Objects.equals(name, location.name) &&
Objects.equals(countryCode, location.countryCode) &&
Objects.equals(sunriseTime, location.sunriseTime) &&
Objects.equals(sunsetTime, location.sunsetTime) &&
Objects.equals(zoneOffset, location.zoneOffset) &&
Objects.equals(coordinate, location.coordinate) &&
Objects.equals(population, location.population);
}
@Override
public int hashCode() {
return Objects.hash(id, name, countryCode, sunriseTime, sunsetTime, zoneOffset, coordinate, population);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
if (coordinate != null) {
stringBuilder.append(coordinate.toString());
stringBuilder.append(". ");
}
stringBuilder.append("ID: ");
stringBuilder.append(id);
stringBuilder.append(", Name: ");
stringBuilder.append(name);
if (countryCode != null) {
stringBuilder.append('(');
stringBuilder.append(countryCode);
stringBuilder.append(')');
}
if (population != null) {
stringBuilder.append(", Population: ");
stringBuilder.append(population);
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import java.util.Objects;
/**
* Represents rain information.
*/
public class Rain {
private static final String DEFAULT_UNIT = "mm";
private double threeHourLevel;
private Rain(double threeHourLevel) {
this.threeHourLevel = threeHourLevel;
}
/**
* Creates {@link Rain} object with correctness check.
* @param threeHourLevel 3-hour rain level value
* @return rain object.
*/
public static Rain withThreeHourLevelValue(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
return new Rain(threeHourLevel);
}
/**
* Returns 3-hour rain level value.
* @return 3-hour rain level value
*/
public double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets 3-hour rain level value with correctness check.
* @param threeHourLevel 3-hour rain level value
*/
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.threeHourLevel = threeHourLevel;
}
/**
* Returns rain level unit of measure. Currently is constant.
* @return rain level unit of measure
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Rain rain = (Rain) o;
return Double.compare(rain.threeHourLevel, threeHourLevel) == 0;
}
@Override
public int hashCode() {
return Objects.hash(threeHourLevel);
}
@Override
public String toString() {
return "3-hour rain level: " +
threeHourLevel + ' ' +
getUnit();
}
}
@@ -0,0 +1,97 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import java.util.Objects;
/**
* Represents snow information.
*/
public class Snow {
private static final String DEFAULT_UNIT = "mm";
private double threeHourLevel;
private Snow(double threeHourLevel) {
this.threeHourLevel = threeHourLevel;
}
/**
* Creates {@link Snow} object with correctness check.
* @param threeHourLevel 3-hour snow level value
* @return snow object.
*/
public static Snow withThreeHourLevelValue(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
return new Snow(threeHourLevel);
}
/**
* Returns 3-hour snow level value.
* @return 3-hour snow level value
*/
public double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets 3-hour snow level value with correctness check.
* @param threeHourLevel 3-hour snow level value
*/
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.threeHourLevel = threeHourLevel;
}
/**
* Returns snow level unit of measure. Currently is constant.
* @return snow level unit of measure
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Snow snow = (Snow) o;
return Double.compare(snow.threeHourLevel, threeHourLevel) == 0;
}
@Override
public int hashCode() {
return Objects.hash(threeHourLevel);
}
@Override
public String toString() {
return "3-hour snow level: " +
threeHourLevel + ' ' +
getUnit();
}
}
@@ -0,0 +1,309 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import com.github.prominence.openweathermap.api.model.*;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* Represents weather forecast information for a particular timestamp.
*/
public class WeatherForecast {
private LocalDateTime forecastTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
private Wind wind;
private Rain rain;
private Snow snow;
private Clouds clouds;
private String forecastTimeISO;
private DayTime dayTime;
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
/**
* Sets forecast time.
*
* @param forecastTime the forecast time
*/
public void setForecastTime(LocalDateTime forecastTime) {
this.forecastTime = forecastTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public Temperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(Temperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets rain.
*
* @return the rain
*/
public Rain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(Rain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public Snow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(Snow snow) {
this.snow = snow;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets forecast time iso.
*
* @return the forecast time iso
*/
public String getForecastTimeISO() {
return forecastTimeISO;
}
/**
* Sets forecast time iso.
*
* @param forecastTimeISO the forecast time iso
*/
public void setForecastTimeISO(String forecastTimeISO) {
this.forecastTimeISO = forecastTimeISO;
}
/**
* Gets day time.
*
* @return the day time
*/
public DayTime getDayTime() {
return dayTime;
}
/**
* Sets day time.
*
* @param dayTime the day time
*/
public void setDayTime(DayTime dayTime) {
this.dayTime = dayTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherForecast that = (WeatherForecast) o;
return Objects.equals(forecastTime, that.forecastTime) &&
Objects.equals(weatherState, that.weatherState) &&
Objects.equals(temperature, that.temperature) &&
Objects.equals(atmosphericPressure, that.atmosphericPressure) &&
Objects.equals(humidity, that.humidity) &&
Objects.equals(wind, that.wind) &&
Objects.equals(rain, that.rain) &&
Objects.equals(snow, that.snow) &&
Objects.equals(clouds, that.clouds) &&
Objects.equals(forecastTimeISO, that.forecastTimeISO) &&
dayTime == that.dayTime;
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, weatherState, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, forecastTimeISO, dayTime);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Timestamp: ");
stringBuilder.append(forecastTimeISO);
if (weatherState != null) {
stringBuilder.append(", Weather: ");
stringBuilder.append(weatherState.getDescription());
}
if (temperature != null) {
stringBuilder.append(", ");
stringBuilder.append(temperature.getValue());
stringBuilder.append(' ');
stringBuilder.append(temperature.getUnit());
}
if (atmosphericPressure != null) {
stringBuilder.append(", ");
stringBuilder.append(atmosphericPressure.getValue());
stringBuilder.append(' ');
stringBuilder.append(atmosphericPressure.getUnit());
}
if (clouds != null) {
stringBuilder.append(", ");
stringBuilder.append(clouds.toString());
}
if (rain != null) {
stringBuilder.append(", Rain: ");
stringBuilder.append(rain.getThreeHourLevel());
stringBuilder.append(' ');
stringBuilder.append(rain.getUnit());
}
if (snow != null) {
stringBuilder.append(", Snow: ");
stringBuilder.append(snow.getThreeHourLevel());
stringBuilder.append(' ');
stringBuilder.append(snow.getUnit());
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,145 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.forecast;
import java.util.Objects;
/**
* Represents wind information.
*/
public class Wind {
private double speed;
private Double degrees;
private String unit;
/**
* Instantiates a new Wind.
*
* @param speed the speed
* @param unit the unitSystem
*/
private Wind(double speed, String unit) {
this.speed = speed;
this.unit = unit;
}
/**
* Creates {@link Wind} object with correctness check
* @param speed the wind
* @param unit the unitSystem
* @return created wind object
*/
public static Wind withValue(double speed, String unit) {
if (speed < 0) {
throw new IllegalArgumentException("Wind speed value must be in positive or zero.");
}
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
return new Wind(speed, unit);
}
/**
* Gets speed.
*
* @return the speed
*/
public double getSpeed() {
return speed;
}
/**
* Sets speed.
*
* @param speed the speed
*/
public void setSpeed(double speed) {
if (speed < 0) {
throw new IllegalArgumentException("Wind speed value must be in positive or zero.");
}
this.speed = speed;
}
/**
* Gets degrees.
*
* @return the degrees
*/
public Double getDegrees() {
return degrees;
}
/**
* Sets degrees.
*
* @param degrees the degrees
*/
public void setDegrees(double degrees) {
if (degrees < 0 || degrees > 360) {
throw new IllegalArgumentException("Wind direction value must be in [0, 360] range.");
}
this.degrees = degrees;
}
/**
* Gets unitSystem.
*
* @return the unitSystem
*/
public String getUnit() {
return unit;
}
/**
* Sets unitSystem.
*
* @param unit the unitSystem
*/
public void setUnit(String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Wind)) return false;
Wind wind = (Wind) o;
return Double.compare(wind.speed, speed) == 0 &&
Objects.equals(degrees, wind.degrees) &&
Objects.equals(unit, wind.unit);
}
@Override
public int hashCode() {
return Objects.hash(speed, degrees, unit);
}
@Override
public String toString() {
return "Wind speed: " + speed + " " + unit +
", degrees: " + degrees;
}
}
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import java.util.Objects;
/**
* The AtmosphericPressure type represents atmospheric pressure value.
* Its value can only be a double in [0, +∞) range.
*/
public class AtmosphericPressure {
private static final String DEFAULT_UNIT = "hPa";
private double seaLevelValue;
private AtmosphericPressure() {
}
/**
* Static method for {@link AtmosphericPressure} creation with value checking.
* @param seaLevelValue atmospheric pressure value.
* @return instantiated {@link AtmosphericPressure} object.
*/
public static AtmosphericPressure withValue(double seaLevelValue) {
final AtmosphericPressure atmosphericPressure = new AtmosphericPressure();
atmosphericPressure.setSeaLevelValue(seaLevelValue);
return atmosphericPressure;
}
/**
* Gets sea level value.
*
* @return the sea level value.
*/
public Double getSeaLevelValue() {
return seaLevelValue;
}
/**
* Sets sea level value.
*
* @param seaLevelValue the sea level value.
* @throws IllegalArgumentException in case if provided value isn't in allowed range.
*/
public void setSeaLevelValue(double seaLevelValue) {
if (seaLevelValue < 0) {
throw new IllegalArgumentException("Atmospheric pressure value must be in [0, +∞) range.");
}
this.seaLevelValue = seaLevelValue;
}
/**
* Returns pressure unitSystem. Constantly equals to 'hPa'.
*
* @return the pressure unitSystem.
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AtmosphericPressure that = (AtmosphericPressure) o;
return Double.compare(that.seaLevelValue, seaLevelValue) == 0;
}
@Override
public int hashCode() {
return Objects.hash(seaLevelValue);
}
@Override
public String toString() {
return "Pressure: " + seaLevelValue + ' ' + getUnit();
}
}
@@ -0,0 +1,320 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import com.github.prominence.openweathermap.api.model.Clouds;
import com.github.prominence.openweathermap.api.model.Humidity;
import com.github.prominence.openweathermap.api.model.WeatherState;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Current.
*/
public class Current {
protected LocalDateTime forecastTime;
protected LocalDateTime sunriseTime;
protected LocalDateTime sunsetTime;
protected WeatherState weatherState;
protected Temperature temperature;
protected AtmosphericPressure atmosphericPressure;
protected Humidity humidity;
protected Clouds clouds;
protected Double uvIndex;
protected Double visibilityInMetres;
protected Wind wind;
protected Rain rain;
protected Snow snow;
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
/**
* Sets forecast time.
*
* @param forecastTime the forecast time
*/
public void setForecastTime(LocalDateTime forecastTime) {
this.forecastTime = forecastTime;
}
/**
* Gets sunrise time.
*
* @return the sunrise time
*/
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets sunrise time.
*
* @param sunriseTime the sunrise time
*/
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Gets sunset time.
*
* @return the sunset time
*/
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets sunset time.
*
* @param sunsetTime the sunset time
*/
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public Temperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(Temperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets uv index.
*
* @return the uv index
*/
public Double getUvIndex() {
return uvIndex;
}
/**
* Sets uv index.
*
* @param uvIndex the uv index
*/
public void setUvIndex(Double uvIndex) {
if (uvIndex != null && uvIndex < 0) {
throw new IllegalArgumentException("UV index must not be negative.");
}
this.uvIndex = uvIndex;
}
/**
* Gets visibility in metres.
*
* @return the visibility in metres
*/
public Double getVisibilityInMetres() {
return visibilityInMetres;
}
/**
* Sets visibility in metres.
*
* @param visibilityInMetres the visibility in metres
*/
public void setVisibilityInMetres(Double visibilityInMetres) {
if (visibilityInMetres != null && visibilityInMetres < 0) {
throw new IllegalArgumentException("Visibility must not be negative.");
}
this.visibilityInMetres = visibilityInMetres;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets rain.
*
* @return the rain
*/
public Rain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(Rain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public Snow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(Snow snow) {
this.snow = snow;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Current current = (Current) o;
return Objects.equals(forecastTime, current.forecastTime) &&
Objects.equals(sunriseTime, current.sunriseTime) &&
Objects.equals(sunsetTime, current.sunsetTime) &&
Objects.equals(weatherState, current.weatherState) &&
Objects.equals(temperature, current.temperature) &&
Objects.equals(atmosphericPressure, current.atmosphericPressure) &&
Objects.equals(humidity, current.humidity) &&
Objects.equals(clouds, current.clouds) &&
Objects.equals(uvIndex, current.uvIndex) &&
Objects.equals(visibilityInMetres, current.visibilityInMetres) &&
Objects.equals(wind, current.wind) &&
Objects.equals(rain, current.rain) &&
Objects.equals(snow, current.snow);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, sunriseTime, sunsetTime, weatherState, temperature, atmosphericPressure, humidity, clouds, uvIndex, visibilityInMetres, wind, rain, snow);
}
@Override
public String toString() {
return "Current weather information forecasted for " + forecastTime + ".";
}
}
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import java.util.Objects;
/**
* Represents rain information.
*/
public class Rain {
private static final String DEFAULT_UNIT = "mm";
private double oneHourLevel;
private Rain() {
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param oneHourLevel 1-hour rain level value
* @return rain object.
*/
public static Rain withOneHourLevelValue(double oneHourLevel) {
final Rain rain = new Rain();
rain.setOneHourLevel(oneHourLevel);
return rain;
}
/**
* Gets one hour rain level.
*
* @return the one hour rain level
*/
public double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour rain level.
*
* @param oneHourLevel the one hour rain level
*/
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.oneHourLevel = oneHourLevel;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Rain)) return false;
Rain rain = (Rain) o;
return Objects.equals(oneHourLevel, rain.oneHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourLevel);
}
@Override
public String toString() {
return "1-hour rain level: " +
oneHourLevel + ' ' +
getUnit();
}
}
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import java.util.Objects;
/**
* Represents snow information.
*/
public class Snow {
private static final String DEFAULT_UNIT = "mm";
private double oneHourLevel;
private Snow() {
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param oneHourLevel 1-hour snow level value
* @return snow object.
*/
public static Snow withOneHourLevelValue(double oneHourLevel) {
final Snow snow = new Snow();
snow.setOneHourLevel(oneHourLevel);
return snow;
}
/**
* Gets one hour snow level.
*
* @return the one hour snow level
*/
public double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour snow level.
*
* @param oneHourLevel the one hour snow level
*/
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.oneHourLevel = oneHourLevel;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Snow)) return false;
Snow snow = (Snow) o;
return Objects.equals(oneHourLevel, snow.oneHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourLevel);
}
@Override
public String toString() {
return "1-hour snow level: " +
oneHourLevel + ' ' +
getUnit();
}
}
@@ -0,0 +1,143 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import java.util.Objects;
/**
* Represents temperature values and unit.
*/
public class Temperature {
private double value;
private Double feelsLike;
private Double dewPoint;
private String unit;
private Temperature() {
}
/**
* Creates {@link Temperature} object with correctness check.
* @param value temperature value
* @param unit temperature unit
* @return temperature object
*/
public static Temperature withValue(double value, String unit) {
final Temperature temperature = new Temperature();
temperature.setValue(value);
temperature.setUnit(unit);
return temperature;
}
/**
* Returns temperature value.
* @return value
*/
public double getValue() {
return value;
}
/**
* Sets temperature value.
* @param value temperature
*/
public void setValue(double value) {
this.value = value;
}
/**
* Returns 'feels like' temperature value.
* @return 'feels like' temperature value
*/
public Double getFeelsLike() {
return feelsLike;
}
/**
* Sets 'feels like' temperature value.
* @param feelsLike 'feels like' temperature
*/
public void setFeelsLike(Double feelsLike) {
this.feelsLike = feelsLike;
}
public Double getDewPoint() {
return dewPoint;
}
public void setDewPoint(Double dewPoint) {
this.dewPoint = dewPoint;
}
/**
* Returns temperature unit.
* @return unit
*/
public String getUnit() {
return unit;
}
/**
* Sets temperature unit with correctness check.
* @param unit temperature unit
*/
public void setUnit(String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Temperature)) return false;
Temperature that = (Temperature) o;
return Double.compare(that.value, value) == 0 &&
Objects.equals(feelsLike, that.feelsLike) &&
Objects.equals(dewPoint, that.dewPoint) &&
Objects.equals(unit, that.unit);
}
@Override
public int hashCode() {
return Objects.hash(value, feelsLike, dewPoint, unit);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Temperature: ");
stringBuilder.append(value);
stringBuilder.append(' ');
stringBuilder.append(unit);
if (feelsLike != null) {
stringBuilder.append(", Feels like: ");
stringBuilder.append(feelsLike);
stringBuilder.append(' ');
stringBuilder.append(unit);
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,159 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall;
import java.util.Objects;
/**
* The type Wind.
*/
public class Wind {
private double speed;
private Double degrees;
private Double gust;
private String unit;
private Wind() {
}
/**
* Creates {@link Wind} object with correctness check.
* @param speed the speed
* @param unit the unitSystem
* @return wind object
*/
public static Wind withValue(double speed, String unit) {
final Wind wind = new Wind();
wind.setSpeed(speed);
wind.setUnit(unit);
return wind;
}
/**
* Gets speed.
*
* @return the speed
*/
public double getSpeed() {
return speed;
}
/**
* Sets speed.
*
* @param speed the speed
*/
public void setSpeed(double speed) {
if (speed < 0) {
throw new IllegalArgumentException("Wind speed value must be in positive or zero.");
}
this.speed = speed;
}
/**
* Gets gust value.
* @return the gust
*/
public Double getGust() {
return gust;
}
/**
* Sets gust value.
* @param gust the gust.
*/
public void setGust(double gust) {
if (gust < 0) {
throw new IllegalArgumentException("Gust value must be positive or zero.");
}
this.gust = gust;
}
/**
* Gets degrees.
*
* @return the degrees
*/
public Double getDegrees() {
return degrees;
}
/**
* Sets degrees.
*
* @param degrees the degrees
*/
public void setDegrees(double degrees) {
if (degrees < 0 || degrees > 360) {
throw new IllegalArgumentException("Wind direction value must be in [0, 360] range.");
}
this.degrees = degrees;
}
/**
* Gets unitSystem.
*
* @return the unitSystem
*/
public String getUnit() {
return unit;
}
/**
* Sets unitSystem.
*
* @param unit the unitSystem
*/
public void setUnit(String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Wind)) return false;
Wind wind = (Wind) o;
return Double.compare(wind.speed, speed) == 0 &&
Objects.equals(degrees, wind.degrees) &&
Objects.equals(gust, wind.gust) &&
Objects.equals(unit, wind.unit);
}
@Override
public int hashCode() {
return Objects.hash(speed, degrees, gust, unit);
}
@Override
public String toString() {
String output = "Wind speed: " + speed + " " + unit +
", degrees: " + degrees;
if (gust != null) {
output += ", Gust: " + gust + " " + unit;
}
return output;
}
}
@@ -0,0 +1,172 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Alert.
*/
public class Alert {
private String senderName;
private String eventName;
private LocalDateTime startTime;
private LocalDateTime endTime;
private String description;
/**
* Instantiates a new Alert.
*/
public Alert() {
}
/**
* Instantiates a new Alert.
*
* @param senderName the sender name
* @param eventName the event name
* @param startTime the start time
* @param endTime the end time
* @param description the description
*/
public Alert(String senderName, String eventName, LocalDateTime startTime, LocalDateTime endTime, String description) {
this.senderName = senderName;
this.eventName = eventName;
this.startTime = startTime;
this.endTime = endTime;
this.description = description;
}
/**
* Gets sender name.
*
* @return the sender name
*/
public String getSenderName() {
return senderName;
}
/**
* Sets sender name.
*
* @param senderName the sender name
*/
public void setSenderName(String senderName) {
this.senderName = senderName;
}
/**
* Gets event name.
*
* @return the event name
*/
public String getEventName() {
return eventName;
}
/**
* Sets event name.
*
* @param eventName the event name
*/
public void setEventName(String eventName) {
this.eventName = eventName;
}
/**
* Gets start time.
*
* @return the start time
*/
public LocalDateTime getStartTime() {
return startTime;
}
/**
* Sets start time.
*
* @param startTime the start time
*/
public void setStartTime(LocalDateTime startTime) {
this.startTime = startTime;
}
/**
* Gets end time.
*
* @return the end time
*/
public LocalDateTime getEndTime() {
return endTime;
}
/**
* Sets end time.
*
* @param endTime the end time
*/
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
/**
* Gets description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets description.
*
* @param description the description
*/
public void setDescription(String description) {
this.description = description;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Alert alert = (Alert) o;
return Objects.equals(senderName, alert.senderName) &&
Objects.equals(eventName, alert.eventName) &&
Objects.equals(startTime, alert.startTime) &&
Objects.equals(endTime, alert.endTime) &&
Objects.equals(description, alert.description);
}
@Override
public int hashCode() {
return Objects.hash(senderName, eventName, startTime, endTime, description);
}
@Override
public String toString() {
return senderName + " - " + eventName + "(" + startTime + " - " + endTime + "): " + description;
}
}
@@ -0,0 +1,215 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.onecall.Current;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Objects;
/**
* The type Current weather data.
*/
public class CurrentWeatherData {
private Coordinate coordinate;
private ZoneId timezone;
private ZoneOffset timezoneOffset;
private Current current;
private List<Minutely> minutelyList;
private List<Hourly> hourlyList;
private List<Daily> dailyList;
private List<Alert> alerts;
/**
* Gets coordinate.
*
* @return the coordinate
*/
public Coordinate getCoordinate() {
return coordinate;
}
/**
* Sets coordinate.
*
* @param coordinate the coordinate
*/
public void setCoordinate(Coordinate coordinate) {
this.coordinate = coordinate;
}
/**
* Gets timezone.
*
* @return the timezone
*/
public ZoneId getTimezone() {
return timezone;
}
/**
* Sets timezone.
*
* @param timezone the timezone
*/
public void setTimezone(ZoneId timezone) {
this.timezone = timezone;
}
/**
* Gets timezone offset.
*
* @return the timezone offset
*/
public ZoneOffset getTimezoneOffset() {
return timezoneOffset;
}
/**
* Sets timezone offset.
*
* @param timezoneOffset the timezone offset
*/
public void setTimezoneOffset(ZoneOffset timezoneOffset) {
this.timezoneOffset = timezoneOffset;
}
/**
* Gets current.
*
* @return the current
*/
public Current getCurrent() {
return current;
}
/**
* Sets current.
*
* @param current the current
*/
public void setCurrent(Current current) {
this.current = current;
}
/**
* Gets minutely list.
*
* @return the minutely list
*/
public List<Minutely> getMinutelyList() {
return minutelyList;
}
/**
* Sets minutely list.
*
* @param minutelyList the minutely list
*/
public void setMinutelyList(List<Minutely> minutelyList) {
this.minutelyList = minutelyList;
}
/**
* Gets hourly list.
*
* @return the hourly list
*/
public List<Hourly> getHourlyList() {
return hourlyList;
}
/**
* Sets hourly list.
*
* @param hourlyList the hourly list
*/
public void setHourlyList(List<Hourly> hourlyList) {
this.hourlyList = hourlyList;
}
/**
* Gets daily list.
*
* @return the daily list
*/
public List<Daily> getDailyList() {
return dailyList;
}
/**
* Sets daily list.
*
* @param dailyList the daily list
*/
public void setDailyList(List<Daily> dailyList) {
this.dailyList = dailyList;
}
/**
* Gets alerts.
*
* @return the alerts
*/
public List<Alert> getAlerts() {
return alerts;
}
/**
* Sets alerts.
*
* @param alerts the alerts
*/
public void setAlerts(List<Alert> alerts) {
this.alerts = alerts;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CurrentWeatherData that = (CurrentWeatherData) o;
return Objects.equals(coordinate, that.coordinate) &&
Objects.equals(timezone, that.timezone) &&
Objects.equals(timezoneOffset, that.timezoneOffset) &&
Objects.equals(current, that.current) &&
Objects.equals(minutelyList, that.minutelyList) &&
Objects.equals(hourlyList, that.hourlyList) &&
Objects.equals(dailyList, that.dailyList) &&
Objects.equals(alerts, that.alerts);
}
@Override
public int hashCode() {
return Objects.hash(coordinate, timezone, timezoneOffset, current, minutelyList, hourlyList, dailyList, alerts);
}
@Override
public String toString() {
return "Current weather data for " + coordinate + ".";
}
}
@@ -0,0 +1,364 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import com.github.prominence.openweathermap.api.model.Clouds;
import com.github.prominence.openweathermap.api.model.Humidity;
import com.github.prominence.openweathermap.api.model.WeatherState;
import com.github.prominence.openweathermap.api.model.onecall.AtmosphericPressure;
import com.github.prominence.openweathermap.api.model.onecall.Wind;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Daily.
*/
public class Daily {
private LocalDateTime forecastTime;
private LocalDateTime sunriseTime;
private LocalDateTime sunsetTime;
private WeatherState weatherState;
private DailyTemperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
private Wind wind;
private Clouds clouds;
private Double uvIndex;
private Double probabilityOfPrecipitation;
private DailyRain rain;
private DailySnow snow;
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
/**
* Sets forecast time.
*
* @param forecastTime the forecast time
*/
public void setForecastTime(LocalDateTime forecastTime) {
this.forecastTime = forecastTime;
}
/**
* Gets sunrise time.
*
* @return the sunrise time
*/
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets sunrise time.
*
* @param sunriseTime the sunrise time
*/
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Gets sunset time.
*
* @return the sunset time
*/
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets sunset time.
*
* @param sunsetTime the sunset time
*/
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public DailyTemperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(DailyTemperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets uv index.
*
* @return the uv index
*/
public Double getUvIndex() {
return uvIndex;
}
/**
* Sets uv index.
*
* @param uvIndex the uv index
*/
public void setUvIndex(Double uvIndex) {
if (uvIndex != null && uvIndex < 0) {
throw new IllegalArgumentException("UV index must not be negative.");
}
this.uvIndex = uvIndex;
}
/**
* Gets probability of precipitation.
*
* @return the probability of precipitation
*/
public Double getProbabilityOfPrecipitation() {
return probabilityOfPrecipitation;
}
/**
* Sets probability of precipitation.
*
* @param probabilityOfPrecipitation the probability of precipitation
*/
public void setProbabilityOfPrecipitation(Double probabilityOfPrecipitation) {
if (probabilityOfPrecipitation != null && (probabilityOfPrecipitation < 0 || probabilityOfPrecipitation > 100)) {
throw new IllegalArgumentException("Probability of precipitation value must be in [0, 100] range.");
}
this.probabilityOfPrecipitation = probabilityOfPrecipitation;
}
/**
* Gets rain.
*
* @return the rain
*/
public DailyRain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(DailyRain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public DailySnow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(DailySnow snow) {
this.snow = snow;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Daily daily = (Daily) o;
return Objects.equals(forecastTime, daily.forecastTime) &&
Objects.equals(sunriseTime, daily.sunriseTime) &&
Objects.equals(sunsetTime, daily.sunsetTime) &&
Objects.equals(weatherState, daily.weatherState) &&
Objects.equals(temperature, daily.temperature) &&
Objects.equals(atmosphericPressure, daily.atmosphericPressure) &&
Objects.equals(humidity, daily.humidity) &&
Objects.equals(wind, daily.wind) &&
Objects.equals(clouds, daily.clouds) &&
Objects.equals(uvIndex, daily.uvIndex) &&
Objects.equals(probabilityOfPrecipitation, daily.probabilityOfPrecipitation) &&
Objects.equals(rain, daily.rain) &&
Objects.equals(snow, daily.snow);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, sunriseTime, sunsetTime, weatherState, temperature, atmosphericPressure, humidity, wind, clouds, uvIndex, probabilityOfPrecipitation, rain, snow);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Weather on ");
stringBuilder.append(forecastTime);
stringBuilder.append(".");
if (weatherState != null) {
stringBuilder.append(" Weather: ");
stringBuilder.append(weatherState.getDescription());
stringBuilder.append('.');
}
if (temperature != null) {
stringBuilder.append(" Temperature(day): ");
stringBuilder.append(temperature.getDay());
stringBuilder.append(' ');
stringBuilder.append(temperature.getUnit());
stringBuilder.append('.');
}
if (atmosphericPressure != null) {
stringBuilder.append(" Atmospheric pressure: ");
stringBuilder.append(atmosphericPressure.getSeaLevelValue());
stringBuilder.append(' ');
stringBuilder.append(atmosphericPressure.getUnit());
stringBuilder.append('.');
}
if (clouds != null) {
stringBuilder.append(" Clouds: ");
stringBuilder.append(clouds.toString());
stringBuilder.append('.');
}
if (rain != null) {
stringBuilder.append(" Rain: ");
stringBuilder.append(rain.getValue());
stringBuilder.append(' ');
stringBuilder.append(rain.getUnit());
stringBuilder.append('.');
}
if (snow != null) {
stringBuilder.append(". Snow: ");
stringBuilder.append(snow.getValue());
stringBuilder.append(' ');
stringBuilder.append(snow.getUnit());
stringBuilder.append('.');
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import java.util.Objects;
/**
* Represents rain information.
*/
public class DailyRain {
private static final String DEFAULT_UNIT = "mm";
private double value;
private DailyRain() {
}
/**
* Creates {@link DailyRain} object with correctness check.
*
* @param value 1-hour rain level value
* @return rain object.
*/
public static DailyRain withValue(double value) {
final DailyRain rain = new DailyRain();
rain.setValue(value);
return rain;
}
/**
* Gets one hour rain level.
*
* @return the one hour rain level
*/
public double getValue() {
return value;
}
/**
* Sets one hour rain level.
*
* @param value the one hour rain level
*/
public void setValue(double value) {
if (value < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.value = value;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DailyRain)) return false;
DailyRain rain = (DailyRain) o;
return Objects.equals(value, rain.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return "Rain level: " +
value +
getUnit();
}
}
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import java.util.Objects;
/**
* Represents snow information.
*/
public class DailySnow {
private static final String DEFAULT_UNIT = "mm";
private double value;
private DailySnow() {
}
/**
* Creates {@link DailySnow} object with correctness check.
*
* @param value 1-hour snow level value
* @return snow object.
*/
public static DailySnow withValue(double value) {
final DailySnow snow = new DailySnow();
snow.setValue(value);
return snow;
}
/**
* Gets one hour snow level.
*
* @return the one hour snow level
*/
public double getValue() {
return value;
}
/**
* Sets one hour snow level.
*
* @param value the one hour snow level
*/
public void setValue(double value) {
if (value < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.value = value;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DailySnow)) return false;
DailySnow snow = (DailySnow) o;
return Objects.equals(value, snow.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return "Snow level: " +
value +
getUnit();
}
}
@@ -0,0 +1,283 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import java.util.Objects;
/**
* The type Daily temperature.
*/
public class DailyTemperature {
private Double morning;
private Double morningFeelsLike;
private Double day;
private Double dayFeelsLike;
private Double eve;
private Double eveFeelsLike;
private Double night;
private Double nightFeelsLike;
private Double min;
private Double max;
private Double dewPoint;
private String unit;
/**
* Gets morning temperature.
*
* @return the morning
*/
public Double getMorning() {
return morning;
}
/**
* Sets morning temperature.
*
* @param morning the morning
*/
public void setMorning(Double morning) {
this.morning = morning;
}
/**
* Gets morning feels like temperature.
*
* @return the morning feels like temperature
*/
public Double getMorningFeelsLike() {
return morningFeelsLike;
}
/**
* Sets morning feels like temperature.
*
* @param morningFeelsLike the morning feels like temperature
*/
public void setMorningFeelsLike(Double morningFeelsLike) {
this.morningFeelsLike = morningFeelsLike;
}
/**
* Gets day temperature.
*
* @return the day temperature
*/
public Double getDay() {
return day;
}
/**
* Sets day temperature.
*
* @param day the day temperature
*/
public void setDay(Double day) {
this.day = day;
}
/**
* Gets day feels like temperature.
*
* @return the day feels like temperature
*/
public Double getDayFeelsLike() {
return dayFeelsLike;
}
/**
* Sets day feels like temperature.
*
* @param dayFeelsLike the day feels like temperature
*/
public void setDayFeelsLike(Double dayFeelsLike) {
this.dayFeelsLike = dayFeelsLike;
}
/**
* Gets eve temperature.
*
* @return the eve temperature
*/
public Double getEve() {
return eve;
}
/**
* Sets eve temperature.
*
* @param eve the eve temperature
*/
public void setEve(Double eve) {
this.eve = eve;
}
/**
* Gets eve feels like temperature.
*
* @return the eve feels like temperature
*/
public Double getEveFeelsLike() {
return eveFeelsLike;
}
/**
* Sets eve feels like temperature.
*
* @param eveFeelsLike the eve feels like temperature
*/
public void setEveFeelsLike(Double eveFeelsLike) {
this.eveFeelsLike = eveFeelsLike;
}
/**
* Gets night temperature.
*
* @return the night temperature
*/
public Double getNight() {
return night;
}
/**
* Sets night temperature.
*
* @param night the night temperature
*/
public void setNight(Double night) {
this.night = night;
}
/**
* Gets night feels like temperature.
*
* @return the night feels like temperature
*/
public Double getNightFeelsLike() {
return nightFeelsLike;
}
/**
* Sets night feels like temperature.
*
* @param nightFeelsLike the night feels like temperature
*/
public void setNightFeelsLike(Double nightFeelsLike) {
this.nightFeelsLike = nightFeelsLike;
}
/**
* Gets min temperature.
*
* @return the min temperature
*/
public Double getMin() {
return min;
}
/**
* Sets min temperature.
*
* @param min the min temperature
*/
public void setMin(Double min) {
this.min = min;
}
/**
* Gets max temperature.
*
* @return the max temperature
*/
public Double getMax() {
return max;
}
/**
* Sets max temperature.
*
* @param max the max temperature
*/
public void setMax(Double max) {
this.max = max;
}
/**
* Gets dew point temperature.
*
* @return the dew point temperature
*/
public Double getDewPoint() {
return dewPoint;
}
/**
* Sets dew point temperature.
*
* @param dewPoint the dew point temperature
*/
public void setDewPoint(Double dewPoint) {
this.dewPoint = dewPoint;
}
/**
* Gets unit temperature.
*
* @return the unit temperature
*/
public String getUnit() {
return unit;
}
/**
* Sets unit temperature.
*
* @param unit the unit temperature
*/
public void setUnit(String unit) {
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DailyTemperature that = (DailyTemperature) o;
return Objects.equals(that.dewPoint, dewPoint) &&
Objects.equals(morning, that.morning) &&
Objects.equals(morningFeelsLike, that.morningFeelsLike) &&
Objects.equals(day, that.day) &&
Objects.equals(dayFeelsLike, that.dayFeelsLike) &&
Objects.equals(eve, that.eve) &&
Objects.equals(eveFeelsLike, that.eveFeelsLike) &&
Objects.equals(night, that.night) &&
Objects.equals(nightFeelsLike, that.nightFeelsLike) &&
Objects.equals(min, that.min) &&
Objects.equals(max, that.max) &&
Objects.equals(unit, that.unit);
}
@Override
public int hashCode() {
return Objects.hash(morning, morningFeelsLike, day, dayFeelsLike, eve, eveFeelsLike, night, nightFeelsLike, min, max, dewPoint, unit);
}
}
@@ -0,0 +1,295 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import com.github.prominence.openweathermap.api.model.Clouds;
import com.github.prominence.openweathermap.api.model.Humidity;
import com.github.prominence.openweathermap.api.model.WeatherState;
import com.github.prominence.openweathermap.api.model.onecall.*;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Hourly.
*/
public class Hourly {
private LocalDateTime forecastTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
private Double uvIndex;
private Clouds clouds;
private Double visibilityInMetres;
private Wind wind;
private Double probabilityOfPrecipitation;
private Rain rain;
private Snow snow;
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
/**
* Sets forecast time.
*
* @param forecastTime the forecast time
*/
public void setForecastTime(LocalDateTime forecastTime) {
this.forecastTime = forecastTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public Temperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(Temperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets uv index.
*
* @return the uv index
*/
public Double getUvIndex() {
return uvIndex;
}
/**
* Sets uv index.
*
* @param uvIndex the uv index
*/
public void setUvIndex(Double uvIndex) {
this.uvIndex = uvIndex;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets visibility in metres.
*
* @return the visibility in metres
*/
public Double getVisibilityInMetres() {
return visibilityInMetres;
}
/**
* Sets visibility in metres.
*
* @param visibilityInMetres the visibility in metres
*/
public void setVisibilityInMetres(Double visibilityInMetres) {
this.visibilityInMetres = visibilityInMetres;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets probability of precipitation.
*
* @return the probability of precipitation
*/
public Double getProbabilityOfPrecipitation() {
return probabilityOfPrecipitation;
}
/**
* Sets probability of precipitation.
*
* @param probabilityOfPrecipitation the probability of precipitation
*/
public void setProbabilityOfPrecipitation(Double probabilityOfPrecipitation) {
this.probabilityOfPrecipitation = probabilityOfPrecipitation;
}
/**
* Gets rain.
*
* @return the rain
*/
public Rain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(Rain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public Snow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(Snow snow) {
this.snow = snow;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Hourly hourly = (Hourly) o;
return Objects.equals(forecastTime, hourly.forecastTime) &&
Objects.equals(weatherState, hourly.weatherState) &&
Objects.equals(temperature, hourly.temperature) &&
Objects.equals(atmosphericPressure, hourly.atmosphericPressure) &&
Objects.equals(humidity, hourly.humidity) &&
Objects.equals(uvIndex, hourly.uvIndex) &&
Objects.equals(clouds, hourly.clouds) &&
Objects.equals(visibilityInMetres, hourly.visibilityInMetres) &&
Objects.equals(wind, hourly.wind) &&
Objects.equals(probabilityOfPrecipitation, hourly.probabilityOfPrecipitation) &&
Objects.equals(rain, hourly.rain) &&
Objects.equals(snow, hourly.snow);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, weatherState, temperature, atmosphericPressure, humidity, uvIndex, clouds, visibilityInMetres, wind, probabilityOfPrecipitation, rain, snow);
}
@Override
public String toString() {
return "Hourly weather information forecasted for " + forecastTime + ".";
}
}
@@ -0,0 +1,100 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.current;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Minutely.
*/
public class Minutely {
private LocalDateTime forecastTime;
private double precipitationVolume;
private Minutely() {
}
/**
* With value minutely.
*
* @param forecastTime the forecast time
* @param precipitationVolume the precipitation volume
* @return the minutely
*/
public static Minutely withValue(LocalDateTime forecastTime, double precipitationVolume) {
final Minutely minutely = new Minutely();
minutely.setForecastTime(forecastTime);
minutely.setPrecipitationVolume(precipitationVolume);
return minutely;
}
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
private void setForecastTime(LocalDateTime forecastTime) {
Objects.requireNonNull(forecastTime);
this.forecastTime = forecastTime;
}
/**
* Gets precipitation volume.
*
* @return the precipitation volume
*/
public double getPrecipitationVolume() {
return precipitationVolume;
}
private void setPrecipitationVolume(double precipitationVolume) {
if (precipitationVolume < 0) {
throw new IllegalArgumentException("Precipitation volume cannot be negative.");
}
this.precipitationVolume = precipitationVolume;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Minutely minutely = (Minutely) o;
return Double.compare(minutely.precipitationVolume, precipitationVolume) == 0 && Objects.equals(forecastTime, minutely.forecastTime);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, precipitationVolume);
}
@Override
public String toString() {
return "Time: " + forecastTime + ", precipitation volume: " + precipitationVolume;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,12 +20,16 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api.exception; package com.github.prominence.openweathermap.api.model.onecall.historical;
public class DataNotFoundException extends Exception { import com.github.prominence.openweathermap.api.model.onecall.*;
public DataNotFoundException() { /**
super("Data for provided parameters wasn't found. Please, check your request."); * The type Historical weather.
*/
public class HistoricalWeather extends Current {
@Override
public String toString() {
return "Historical weather information forecasted for " + forecastTime + ".";
} }
} }
@@ -0,0 +1,154 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.historical;
import com.github.prominence.openweathermap.api.model.Coordinate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Objects;
/**
* The type Historical weather data.
*/
public class HistoricalWeatherData {
private Coordinate coordinate;
private ZoneId timezone;
private ZoneOffset timezoneOffset;
private HistoricalWeather historicalWeather;
private List<HourlyHistorical> hourlyList;
/**
* Gets coordinate.
*
* @return the coordinate
*/
public Coordinate getCoordinate() {
return coordinate;
}
/**
* Sets coordinate.
*
* @param coordinate the coordinate
*/
public void setCoordinate(Coordinate coordinate) {
this.coordinate = coordinate;
}
/**
* Gets timezone.
*
* @return the timezone
*/
public ZoneId getTimezone() {
return timezone;
}
/**
* Sets timezone.
*
* @param timezone the timezone
*/
public void setTimezone(ZoneId timezone) {
this.timezone = timezone;
}
/**
* Gets timezone offset.
*
* @return the timezone offset
*/
public ZoneOffset getTimezoneOffset() {
return timezoneOffset;
}
/**
* Sets timezone offset.
*
* @param timezoneOffset the timezone offset
*/
public void setTimezoneOffset(ZoneOffset timezoneOffset) {
this.timezoneOffset = timezoneOffset;
}
/**
* Gets historical weather.
*
* @return the historical weather
*/
public HistoricalWeather getHistoricalWeather() {
return historicalWeather;
}
/**
* Sets historical weather.
*
* @param historicalWeather the historical weather
*/
public void setHistoricalWeather(HistoricalWeather historicalWeather) {
this.historicalWeather = historicalWeather;
}
/**
* Gets hourly list.
*
* @return the hourly list
*/
public List<HourlyHistorical> getHourlyList() {
return hourlyList;
}
/**
* Sets hourly list.
*
* @param hourlyList the hourly list
*/
public void setHourlyList(List<HourlyHistorical> hourlyList) {
this.hourlyList = hourlyList;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HistoricalWeatherData that = (HistoricalWeatherData) o;
return Objects.equals(coordinate, that.coordinate) &&
Objects.equals(timezone, that.timezone) &&
Objects.equals(timezoneOffset, that.timezoneOffset) &&
Objects.equals(historicalWeather, that.historicalWeather) &&
Objects.equals(hourlyList, that.hourlyList);
}
@Override
public int hashCode() {
return Objects.hash(coordinate, timezone, timezoneOffset, historicalWeather, hourlyList);
}
@Override
public String toString() {
return "Historical weather data for " + coordinate + ".";
}
}
@@ -0,0 +1,255 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.onecall.historical;
import com.github.prominence.openweathermap.api.model.Clouds;
import com.github.prominence.openweathermap.api.model.Humidity;
import com.github.prominence.openweathermap.api.model.WeatherState;
import com.github.prominence.openweathermap.api.model.onecall.*;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* The type Hourly historical.
*/
public class HourlyHistorical {
private LocalDateTime forecastTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
private Clouds clouds;
private Double visibilityInMetres;
private Wind wind;
private Rain rain;
private Snow snow;
/**
* Gets forecast time.
*
* @return the forecast time
*/
public LocalDateTime getForecastTime() {
return forecastTime;
}
/**
* Sets forecast time.
*
* @param forecastTime the forecast time
*/
public void setForecastTime(LocalDateTime forecastTime) {
this.forecastTime = forecastTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public Temperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(Temperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets visibility in metres.
*
* @return the visibility in metres
*/
public Double getVisibilityInMetres() {
return visibilityInMetres;
}
/**
* Sets visibility in metres.
*
* @param visibilityInMetres the visibility in metres
*/
public void setVisibilityInMetres(Double visibilityInMetres) {
this.visibilityInMetres = visibilityInMetres;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets rain.
*
* @return the rain
*/
public Rain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(Rain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public Snow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(Snow snow) {
this.snow = snow;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HourlyHistorical that = (HourlyHistorical) o;
return Objects.equals(forecastTime, that.forecastTime) &&
Objects.equals(weatherState, that.weatherState) &&
Objects.equals(temperature, that.temperature) &&
Objects.equals(atmosphericPressure, that.atmosphericPressure) &&
Objects.equals(humidity, that.humidity) &&
Objects.equals(clouds, that.clouds) &&
Objects.equals(visibilityInMetres, that.visibilityInMetres) &&
Objects.equals(wind, that.wind) &&
Objects.equals(rain, that.rain) &&
Objects.equals(snow, that.snow);
}
@Override
public int hashCode() {
return Objects.hash(forecastTime, weatherState, temperature, atmosphericPressure, humidity, clouds, visibilityInMetres, wind, rain, snow);
}
@Override
public String toString() {
return "Historical hourly information forecasted for " + forecastTime + ".";
}
}
@@ -1,609 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.response;
import com.alibaba.fastjson.annotation.JSONField;
import com.github.prominence.openweathermap.api.model.*;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class HourlyForecast implements OpenWeatherResponse {
@JSONField(name = "cod")
private short responseCode;
private double message;
// Number of lines returned by this API call
private short cnt;
@JSONField(name = "list")
private List<Forecast> forecasts;
@JSONField(name = "city")
private CityInfo cityInfo;
public short getResponseCode() {
return responseCode;
}
public void setResponseCode(short responseCode) {
this.responseCode = responseCode;
}
public double getMessage() {
return message;
}
public void setMessage(double message) {
this.message = message;
}
public short getCnt() {
return cnt;
}
public void setCnt(short cnt) {
this.cnt = cnt;
}
public List<Forecast> getForecasts() {
return forecasts;
}
public void setForecasts(List<Forecast> forecasts) {
this.forecasts = forecasts;
}
public CityInfo getCityInfo() {
return cityInfo;
}
public void setCityInfo(CityInfo cityInfo) {
this.cityInfo = cityInfo;
}
public String getCityName() {
return cityInfo.name;
}
public long getCityId() {
return cityInfo.id;
}
public String getCountry() {
return cityInfo.country;
}
public Coordinates getCoordinates() {
return cityInfo.coordinates;
}
public float getAverageTemperature() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.temperature).average().orElse(0f);
}
public float getMinimumTemperature() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.temperature).min().orElse(0f);
}
public float getMaximumTemperature() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.temperature).max().orElse(0f);
}
public Forecast getByMinimumTemperature() {
return forecasts.stream().min(Comparator.comparing(forecast -> forecast.weatherInfo.minimumTemperature)).orElse(null);
}
public Forecast getByMaximumTemperature() {
return forecasts.stream().max(Comparator.comparing(forecast -> forecast.weatherInfo.maximumTemperature)).orElse(null);
}
public float getAveragePressure() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.pressure).average().orElse(0f);
}
public float getMinimumPressure() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.pressure).min().orElse(0f);
}
public float getMaximumPressure() {
return (float)forecasts.stream().mapToDouble(forecast -> forecast.weatherInfo.pressure).max().orElse(0f);
}
public Forecast getByMinimumPressure() {
return forecasts.stream().min(Comparator.comparing(forecast -> forecast.weatherInfo.pressure)).orElse(null);
}
public Forecast getByMaximumPressure() {
return forecasts.stream().max(Comparator.comparing(forecast -> forecast.weatherInfo.pressure)).orElse(null);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(cityInfo);
stringBuilder.append("\nForecasts: ");
forecasts.forEach(forecast -> {
stringBuilder.append("\n\t");
stringBuilder.append(forecast);
});
return stringBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HourlyForecast that = (HourlyForecast) o;
return responseCode == that.responseCode &&
Double.compare(that.message, message) == 0 &&
cnt == that.cnt &&
Objects.equals(forecasts, that.forecasts) &&
Objects.equals(cityInfo, that.cityInfo);
}
@Override
public int hashCode() {
return Objects.hash(responseCode, message, cnt, forecasts, cityInfo);
}
public static class CityInfo {
// City ID
private long id;
// City name
private String name;
@JSONField(name = "coord")
private Coordinates coordinates;
// Country code (GB, JP etc.)
private String country;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "City: " + name + "(" + id + "). Coordinates: " + coordinates + '\n' + "Country: " + country;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CityInfo cityInfo = (CityInfo) o;
return id == cityInfo.id &&
Objects.equals(name, cityInfo.name) &&
Objects.equals(coordinates, cityInfo.coordinates) &&
Objects.equals(country, cityInfo.country);
}
@Override
public int hashCode() {
return Objects.hash(id, name, coordinates, country);
}
}
public static class Forecast {
@JSONField(name = "dt")
// Time of data calculation, unix, UTC
private long dataCalculationTime;
@JSONField(name = "main")
private WeatherInfo weatherInfo;
@JSONField(name = "weather")
private List<WeatherState> weatherStates;
private Clouds clouds;
private Wind wind;
private Snow snow;
private Rain rain;
@JSONField(name = "sys")
private ForecastSystemInfo systemInfo;
// Data/time of calculation, UTC
private String dt_txt;
public long getDataCalculationTime() {
return dataCalculationTime;
}
public void setDataCalculationTime(long dataCalculationTime) {
this.dataCalculationTime = dataCalculationTime;
}
public Date getDataCalculationDate() {
return new Date(dataCalculationTime * 1000);
}
public WeatherInfo getWeatherInfo() {
return weatherInfo;
}
public void setWeatherInfo(WeatherInfo weatherInfo) {
this.weatherInfo = weatherInfo;
}
public List<WeatherState> getWeatherStates() {
return weatherStates;
}
public void setWeatherStates(List<WeatherState> weatherStates) {
this.weatherStates = weatherStates;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Snow getSnow() {
return snow;
}
public void setSnow(Snow snow) {
this.snow = snow;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public ForecastSystemInfo getSystemInfo() {
return systemInfo;
}
public void setSystemInfo(ForecastSystemInfo systemInfo) {
this.systemInfo = systemInfo;
}
public String getDt_txt() {
return dt_txt;
}
public void setDt_txt(String dt_txt) {
this.dt_txt = dt_txt;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Time: ");
stringBuilder.append(new Date(dataCalculationTime * 1000));
stringBuilder.append(". ");
if (weatherStates.size() == 1) {
stringBuilder.append(weatherStates.get(0));
} else {
stringBuilder.append(weatherStates);
}
stringBuilder.append(". ");
stringBuilder.append(weatherInfo);
if (clouds != null) {
stringBuilder.append(". ");
stringBuilder.append(clouds);
}
if (wind != null) {
stringBuilder.append(". ");
stringBuilder.append(wind);
}
if (snow != null) {
stringBuilder.append(". ");
stringBuilder.append(snow);
}
if (rain != null) {
stringBuilder.append(". ");
stringBuilder.append(rain);
}
return stringBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Forecast that = (Forecast) o;
return dataCalculationTime == that.dataCalculationTime &&
Objects.equals(weatherInfo, that.weatherInfo) &&
Objects.equals(weatherStates, that.weatherStates) &&
Objects.equals(clouds, that.clouds) &&
Objects.equals(wind, that.wind) &&
Objects.equals(snow, that.snow) &&
Objects.equals(rain, that.rain) &&
Objects.equals(systemInfo, that.systemInfo) &&
Objects.equals(dt_txt, that.dt_txt);
}
@Override
public int hashCode() {
return Objects.hash(dataCalculationTime, weatherInfo, weatherStates, clouds, wind, snow, rain, systemInfo, dt_txt);
}
public static class ForecastSystemInfo {
private String pod;
public String getPod() {
return pod;
}
public void setPod(String pod) {
this.pod = pod;
}
@Override
public String toString() {
return "ForecastSystemInfo{" +
"pod='" + pod + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ForecastSystemInfo that = (ForecastSystemInfo) o;
return Objects.equals(pod, that.pod);
}
@Override
public int hashCode() {
return Objects.hash(pod);
}
}
public static class WeatherInfo {
@JSONField(name = "temp")
// Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float temperature;
@JSONField(name = "temp_min")
// Minimum temperature at the moment of calculation. This is deviation from 'temp' that is possible for large cities and
// megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float minimumTemperature;
@JSONField(name = "temp_max")
// Maximum temperature at the moment of calculation. This is deviation from 'temp' that is possible for large cities and
// megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float maximumTemperature;
// Atmospheric pressure on the sea level by default, hPa
private float pressure;
@JSONField(name = "sea_level")
// Atmospheric pressure on the sea level, hPa
private float seaLevelPressure;
@JSONField(name = "grnd_level")
// Atmospheric pressure on the ground level, hPa
private float groundLevelPressure;
// Humidity, %
private byte humidity;
@JSONField(name = "temp_kf")
// Internal parameter
private float temperatureCoefficient;
private char temperatureUnit;
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public float getMinimumTemperature() {
return minimumTemperature;
}
public void setMinimumTemperature(float minimumTemperature) {
this.minimumTemperature = minimumTemperature;
}
public float getMaximumTemperature() {
return maximumTemperature;
}
public void setMaximumTemperature(float maximumTemperature) {
this.maximumTemperature = maximumTemperature;
}
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public float getSeaLevelPressure() {
return seaLevelPressure;
}
public void setSeaLevelPressure(float seaLevelPressure) {
this.seaLevelPressure = seaLevelPressure;
}
public float getGroundLevelPressure() {
return groundLevelPressure;
}
public void setGroundLevelPressure(float groundLevelPressure) {
this.groundLevelPressure = groundLevelPressure;
}
public byte getHumidity() {
return humidity;
}
public void setHumidity(byte humidity) {
this.humidity = humidity;
}
public float getTemperatureCoefficient() {
return temperatureCoefficient;
}
public void setTemperatureCoefficient(float temperatureCoefficient) {
this.temperatureCoefficient = temperatureCoefficient;
}
public char getTemperatureUnit() {
return temperatureUnit;
}
public void setTemperatureUnit(char temperatureUnit) {
this.temperatureUnit = temperatureUnit;
}
public String getPressureUnit() {
return "hPa";
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Temperature: ");
stringBuilder.append(temperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append(". Minimum temperature: ");
stringBuilder.append(minimumTemperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append(". Maximum temperature: ");
stringBuilder.append(maximumTemperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append(". Pressure: ");
stringBuilder.append(pressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
if (seaLevelPressure > 0) {
stringBuilder.append(". Sea-level pressure: ");
stringBuilder.append(seaLevelPressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
}
if (groundLevelPressure > 0) {
stringBuilder.append(". Ground-level pressure: ");
stringBuilder.append(groundLevelPressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
}
stringBuilder.append(". Humidity: ");
stringBuilder.append(humidity);
stringBuilder.append('%');
return stringBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherInfo weatherInfo = (WeatherInfo) o;
return Float.compare(weatherInfo.temperature, temperature) == 0 &&
Float.compare(weatherInfo.minimumTemperature, minimumTemperature) == 0 &&
Float.compare(weatherInfo.maximumTemperature, maximumTemperature) == 0 &&
Float.compare(weatherInfo.pressure, pressure) == 0 &&
Float.compare(weatherInfo.seaLevelPressure, seaLevelPressure) == 0 &&
Float.compare(weatherInfo.groundLevelPressure, groundLevelPressure) == 0 &&
humidity == weatherInfo.humidity &&
Float.compare(weatherInfo.temperatureCoefficient, temperatureCoefficient) == 0;
}
@Override
public int hashCode() {
return Objects.hash(temperature, minimumTemperature, maximumTemperature, pressure, seaLevelPressure, groundLevelPressure, humidity, temperatureCoefficient);
}
}
}
}
@@ -1,530 +0,0 @@
/*
* Copyright (c) 2018 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.response;
import com.alibaba.fastjson.annotation.JSONField;
import com.github.prominence.openweathermap.api.model.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;
public class Weather implements OpenWeatherResponse {
@JSONField(name = "id")
private long cityId;
@JSONField(name = "name")
private String cityName;
@JSONField(name = "coord")
private Coordinates coordinates;
@JSONField(name = "weather")
private List<WeatherState> weatherStates;
private String base;
@JSONField(name = "main")
private WeatherInfo weatherInfo;
private Wind wind;
private Clouds clouds;
private Rain rain;
private Snow snow;
@JSONField(name = "dt")
private long dataCalculationTime;
@JSONField(name = "sys")
private WeatherSystemInfo weatherSystemInfo;
@JSONField(name = "cod")
private short responseCode;
public long getCityId() {
return cityId;
}
public void setCityId(long cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public List<WeatherState> getWeatherStates() {
return weatherStates;
}
public void setWeatherStates(List<WeatherState> weatherStates) {
this.weatherStates = weatherStates;
}
public String getBase() {
return base;
}
public void setBase(String base) {
this.base = base;
}
public WeatherInfo getWeatherInfo() {
return weatherInfo;
}
public void setWeatherInfo(WeatherInfo weatherInfo) {
this.weatherInfo = weatherInfo;
}
public Wind getWind() {
return wind;
}
public void setWind(Wind wind) {
this.wind = wind;
}
public Clouds getClouds() {
return clouds;
}
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
public Rain getRain() {
return rain;
}
public void setRain(Rain rain) {
this.rain = rain;
}
public Snow getSnow() {
return snow;
}
public void setSnow(Snow snow) {
this.snow = snow;
}
public long getDataCalculationTime() {
return dataCalculationTime;
}
public void setDataCalculationTime(long dataCalculationTime) {
this.dataCalculationTime = dataCalculationTime;
}
public WeatherSystemInfo getWeatherSystemInfo() {
return weatherSystemInfo;
}
public void setWeatherSystemInfo(WeatherSystemInfo weatherSystemInfo) {
this.weatherSystemInfo = weatherSystemInfo;
}
public short getResponseCode() {
return responseCode;
}
public void setResponseCode(short responseCode) {
this.responseCode = responseCode;
}
public String getCountry() {
return weatherSystemInfo.country;
}
public String getWeatherDescription() {
if (weatherStates != null && weatherStates.size() > 0) {
return weatherStates.get(0).getDescription();
}
return null;
}
public Date getDataCalculationDate() {
return new Date(dataCalculationTime * 1000);
}
public float getTemperature() {
return weatherInfo.temperature;
}
public char getTemperatureUnit() {
return weatherInfo.temperatureUnit;
}
public short getPressure() {
return weatherInfo.pressure;
}
public String getPressureUnit() {
return weatherInfo.getPressureUnit();
}
public byte getHumidityPercentage() {
return weatherInfo.humidity;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("City: ");
stringBuilder.append(cityName);
stringBuilder.append('(');
stringBuilder.append(cityId);
stringBuilder.append("). ");
stringBuilder.append("Coordinates: ");
stringBuilder.append(coordinates);
stringBuilder.append('\n');
stringBuilder.append(weatherSystemInfo);
stringBuilder.append('\n');
if (weatherStates.size() == 1) {
stringBuilder.append(weatherStates.get(0));
} else {
stringBuilder.append(weatherStates);
}
stringBuilder.append('\n');
stringBuilder.append(weatherInfo);
stringBuilder.append('\n');
stringBuilder.append(wind);
stringBuilder.append('\n');
stringBuilder.append(clouds);
stringBuilder.append('\n');
if (rain != null) {
stringBuilder.append(rain);
stringBuilder.append('\n');
}
if (snow != null) {
stringBuilder.append(snow);
stringBuilder.append('\n');
}
stringBuilder.append("Data calculation time: ");
stringBuilder.append(getDataCalculationDate());
return stringBuilder.toString();
}
public static class WeatherInfo {
@JSONField(name = "temp")
// Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float temperature;
@JSONField(name = "pressure")
// Atmospheric pressure (on the sea level, if there is no sea_level or grnd_level data), hPa
private short pressure;
@JSONField(name = "humidity")
// Humidity, %
private byte humidity;
@JSONField(name = "temp_min")
// Minimum temperature at the moment. This is deviation from current temp that is possible for large cities
// and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float minimumTemperature;
@JSONField(name = "temp_max")
// Maximum temperature at the moment. This is deviation from current temp that is possible for large cities
// and megalopolises geographically expanded (use these parameter optionally). Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
private float maximumTemperature;
@JSONField(name = "sea_level")
// Atmospheric pressure on the sea level, hPa
private short seaLevelPressure;
@JSONField(name = "grnd_level")
// Atmospheric pressure on the ground level, hPa
private short groundLevelPressure;
private char temperatureUnit;
public float getTemperature() {
return temperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public short getPressure() {
return pressure;
}
public void setPressure(short pressure) {
this.pressure = pressure;
}
public byte getHumidity() {
return humidity;
}
public void setHumidity(byte humidity) {
this.humidity = humidity;
}
public float getMinimumTemperature() {
return minimumTemperature;
}
public void setMinimumTemperature(float minimumTemperature) {
this.minimumTemperature = minimumTemperature;
}
public float getMaximumTemperature() {
return maximumTemperature;
}
public void setMaximumTemperature(float maximumTemperature) {
this.maximumTemperature = maximumTemperature;
}
public short getSeaLevelPressure() {
return seaLevelPressure;
}
public void setSeaLevelPressure(short seaLevelPressure) {
this.seaLevelPressure = seaLevelPressure;
}
public short getGroundLevelPressure() {
return groundLevelPressure;
}
public void setGroundLevelPressure(short groundLevelPressure) {
this.groundLevelPressure = groundLevelPressure;
}
public char getTemperatureUnit() {
return temperatureUnit;
}
public void setTemperatureUnit(char temperatureUnit) {
this.temperatureUnit = temperatureUnit;
}
public String getPressureUnit() {
return "hPa";
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Temperature: ");
stringBuilder.append(temperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append(". Minimum temparature: ");
stringBuilder.append(minimumTemperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append(". Maximum temperature: ");
stringBuilder.append(maximumTemperature);
stringBuilder.append(' ');
stringBuilder.append(temperatureUnit);
stringBuilder.append('\n');
stringBuilder.append("Humidity: ");
stringBuilder.append(humidity);
stringBuilder.append("%");
stringBuilder.append('\n');
stringBuilder.append("Pressure: ");
stringBuilder.append(pressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
if (seaLevelPressure > 0) {
stringBuilder.append(". Sea-level pressure: ");
stringBuilder.append(seaLevelPressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
}
if (groundLevelPressure > 0) {
stringBuilder.append(". Ground-level pressure: ");
stringBuilder.append(groundLevelPressure);
stringBuilder.append(' ');
stringBuilder.append(getPressureUnit());
}
return stringBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherInfo that = (WeatherInfo) o;
return Float.compare(that.temperature, temperature) == 0 &&
pressure == that.pressure &&
humidity == that.humidity &&
Float.compare(that.minimumTemperature, minimumTemperature) == 0 &&
Float.compare(that.maximumTemperature, maximumTemperature) == 0 &&
seaLevelPressure == that.seaLevelPressure &&
groundLevelPressure == that.groundLevelPressure;
}
@Override
public int hashCode() {
return Objects.hash(temperature, pressure, humidity, minimumTemperature, maximumTemperature, seaLevelPressure, groundLevelPressure);
}
}
public static class WeatherSystemInfo {
@JSONField(name = "type")
// Internal parameter
private short type;
@JSONField(name = "id")
// Internal parameter
private long id;
@JSONField(name = "message")
// Internal parameter
private double message;
@JSONField(name = "country")
// Country code (GB, JP etc.)
private String country;
@JSONField(name = "sunrise")
// Sunrise time, unix, UTC
private long sunriseTimestamp;
@JSONField(name = "sunset")
// Sunset time, unix, UTC
private long sunsetTimestamp;
public short getType() {
return type;
}
public void setType(short type) {
this.type = type;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public double getMessage() {
return message;
}
public void setMessage(double message) {
this.message = message;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public long getSunriseTimestamp() {
return sunriseTimestamp;
}
public void setSunriseTimestamp(long sunriseTimestamp) {
this.sunriseTimestamp = sunriseTimestamp;
}
public Date getSunriseDate() {
return new Date(sunriseTimestamp * 1000);
}
public long getSunsetTimestamp() {
return sunsetTimestamp;
}
public void setSunsetTimestamp(long sunsetTimestamp) {
this.sunsetTimestamp = sunsetTimestamp;
}
public Date getSunsetDate() {
return new Date(sunsetTimestamp * 1000);
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
if (country != null) {
stringBuilder.append("Country: ");
stringBuilder.append(country);
stringBuilder.append('\n');
}
if (sunriseTimestamp > 0) {
stringBuilder.append("Sunrise: ");
stringBuilder.append(getSunriseDate());
stringBuilder.append('\n');
}
if (sunsetTimestamp > 0) {
stringBuilder.append("Sunset: ");
stringBuilder.append(getSunsetDate());
}
return stringBuilder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherSystemInfo that = (WeatherSystemInfo) o;
return type == that.type &&
id == that.id &&
Double.compare(that.message, message) == 0 &&
Objects.equals(country, that.country) &&
Objects.equals(sunriseTimestamp, that.sunriseTimestamp) &&
Objects.equals(sunsetTimestamp, that.sunsetTimestamp);
}
@Override
public int hashCode() {
return Objects.hash(type, id, message, country, sunriseTimestamp, sunsetTimestamp);
}
}
}
@@ -0,0 +1,212 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.weather;
import com.github.prominence.openweathermap.api.model.Coordinate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Objects;
/**
* Represents location information.
*/
public class Location {
private int id;
private String name;
private String countryCode;
private LocalDateTime sunriseTime;
private LocalDateTime sunsetTime;
private ZoneOffset zoneOffset;
private Coordinate coordinate;
private Location(int id, String name) {
this.id = id;
this.name = name;
}
/**
* Creates {@link Location} object with correctness check.
* @param id location id
* @param name location name
* @return location object
*/
public static Location withValues(int id, String name) {
if (name == null) {
throw new IllegalArgumentException("Name must be set.");
}
return new Location(id, name);
}
/**
* Returns ID.
* @return location ID
*/
public int getId() {
return id;
}
/**
* Sets location ID.
* @param id location id
*/
public void setId(int id) {
this.id = id;
}
/**
* Returns location name.
* @return location name
*/
public String getName() {
return name;
}
/**
* Sets location name.
* @param name location name
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns country code.
* @return location country code
*/
public String getCountryCode() {
return countryCode;
}
/**
* Sets location country code.
* @param countryCode location country code
*/
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
/**
* Returns location sunrise time.
* @return sunrise time
*/
public LocalDateTime getSunriseTime() {
return sunriseTime;
}
/**
* Sets location sunrise time.
* @param sunriseTime sunrise time
*/
public void setSunriseTime(LocalDateTime sunriseTime) {
this.sunriseTime = sunriseTime;
}
/**
* Returns location sunset time.
* @return sunset time
*/
public LocalDateTime getSunsetTime() {
return sunsetTime;
}
/**
* Sets location sunset time.
* @param sunsetTime sunset time
*/
public void setSunsetTime(LocalDateTime sunsetTime) {
this.sunsetTime = sunsetTime;
}
/**
* Returns location timezone offset.
* @return timezone offset
*/
public ZoneOffset getZoneOffset() {
return zoneOffset;
}
/**
* Sets location timezone offset.
* @param zoneOffset timezone offset
*/
public void setZoneOffset(ZoneOffset zoneOffset) {
this.zoneOffset = zoneOffset;
}
/**
* Returns location coordinates.
* @return location coordinates.
*/
public Coordinate getCoordinate() {
return coordinate;
}
/**
* Sets location coordinates.
* @param coordinate location coordinates
*/
public void setCoordinate(Coordinate coordinate) {
this.coordinate = coordinate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Location)) return false;
Location location = (Location) o;
return id == location.id &&
Objects.equals(name, location.name) &&
Objects.equals(countryCode, location.countryCode) &&
Objects.equals(sunriseTime, location.sunriseTime) &&
Objects.equals(sunsetTime, location.sunsetTime) &&
Objects.equals(zoneOffset, location.zoneOffset) &&
Objects.equals(coordinate, location.coordinate);
}
@Override
public int hashCode() {
return Objects.hash(id, name, countryCode, sunriseTime, sunsetTime, zoneOffset, coordinate);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
if (coordinate != null) {
stringBuilder.append(coordinate.toString());
stringBuilder.append(". ");
}
stringBuilder.append("ID: ");
stringBuilder.append(id);
stringBuilder.append(", Name: ");
stringBuilder.append(name);
if (countryCode != null) {
stringBuilder.append('(');
stringBuilder.append(countryCode);
stringBuilder.append(')');
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,160 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.weather;
import java.util.Objects;
/**
* Represents rain information.
*/
public class Rain {
private static final String DEFAULT_UNIT = "mm";
private Double oneHourLevel;
private Double threeHourLevel;
private Rain() {
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param oneHourLevel 1-hour rain level value
* @return rain object.
*/
public static Rain withOneHourLevelValue(double oneHourLevel) {
final Rain rain = new Rain();
rain.setOneHourLevel(oneHourLevel);
return rain;
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param threeHourLevel 3-hour rain level value
* @return rain object.
*/
public static Rain withThreeHourLevelValue(double threeHourLevel) {
final Rain rain = new Rain();
rain.setThreeHourLevel(threeHourLevel);
return rain;
}
/**
* Creates {@link Rain} object with correctness check.
*
* @param oneHourLevel the one hour rain level
* @param threeHourLevel the three hour rain level
* @return the rain
*/
public static Rain withValues(double oneHourLevel, double threeHourLevel) {
final Rain rain = new Rain();
rain.setOneHourLevel(oneHourLevel);
rain.setThreeHourLevel(threeHourLevel);
return rain;
}
/**
* Gets one hour rain level.
*
* @return the one hour rain level
*/
public Double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour rain level.
*
* @param oneHourLevel the one hour rain level
*/
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.oneHourLevel = oneHourLevel;
}
/**
* Gets three hour rain level.
*
* @return the three hour rain level
*/
public Double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets three hour rain level.
*
* @param threeHourLevel the three hour rain level
*/
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Rain level value cannot be negative.");
}
this.threeHourLevel = threeHourLevel;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Rain)) return false;
Rain rain = (Rain) o;
return Objects.equals(oneHourLevel, rain.oneHourLevel) &&
Objects.equals(threeHourLevel, rain.threeHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourLevel, threeHourLevel);
}
@Override
public String toString() {
final StringBuilder snowString = new StringBuilder();
if (oneHourLevel != null) {
snowString.append("1-hour rain level: ");
snowString.append(oneHourLevel);
snowString.append(getUnit());
}
if (threeHourLevel != null) {
if (oneHourLevel != null) {
snowString.append(", ");
}
snowString.append("3-hours rain level: ");
snowString.append(threeHourLevel);
snowString.append(getUnit());
}
return snowString.toString();
}
}
@@ -0,0 +1,160 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.weather;
import java.util.Objects;
/**
* Represents snow information.
*/
public class Snow {
private static final String DEFAULT_UNIT = "mm";
private Double oneHourLevel;
private Double threeHourLevel;
private Snow() {
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param oneHourLevel 1-hour snow level value
* @return snow object.
*/
public static Snow withOneHourLevelValue(double oneHourLevel) {
final Snow snow = new Snow();
snow.setOneHourLevel(oneHourLevel);
return snow;
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param threeHourLevel 3-hour snow level value
* @return snow object.
*/
public static Snow withThreeHourLevelValue(double threeHourLevel) {
final Snow snow = new Snow();
snow.setThreeHourLevel(threeHourLevel);
return snow;
}
/**
* Creates {@link Snow} object with correctness check.
*
* @param oneHourLevel the one hour snow level
* @param threeHourLevel the three hour snow level
* @return the snow
*/
public static Snow withValues(double oneHourLevel, double threeHourLevel) {
final Snow snow = new Snow();
snow.setOneHourLevel(oneHourLevel);
snow.setThreeHourLevel(threeHourLevel);
return snow;
}
/**
* Gets one hour snow level.
*
* @return the one hour snow level
*/
public Double getOneHourLevel() {
return oneHourLevel;
}
/**
* Sets one hour snow level.
*
* @param oneHourLevel the one hour snow level
*/
public void setOneHourLevel(double oneHourLevel) {
if (oneHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.oneHourLevel = oneHourLevel;
}
/**
* Gets three hour snow level.
*
* @return the three hour snow level
*/
public Double getThreeHourLevel() {
return threeHourLevel;
}
/**
* Sets three hour snow level.
*
* @param threeHourLevel the three hour snow level
*/
public void setThreeHourLevel(double threeHourLevel) {
if (threeHourLevel < 0) {
throw new IllegalArgumentException("Snow level value cannot be negative.");
}
this.threeHourLevel = threeHourLevel;
}
/**
* Gets unit.
*
* @return the unit
*/
public String getUnit() {
return DEFAULT_UNIT;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Snow)) return false;
Snow snow = (Snow) o;
return Objects.equals(oneHourLevel, snow.oneHourLevel) &&
Objects.equals(threeHourLevel, snow.threeHourLevel);
}
@Override
public int hashCode() {
return Objects.hash(oneHourLevel, threeHourLevel);
}
@Override
public String toString() {
final StringBuilder snowString = new StringBuilder();
if (oneHourLevel != null) {
snowString.append("1-hour snow level: ");
snowString.append(oneHourLevel);
snowString.append(getUnit());
}
if (threeHourLevel != null) {
if (oneHourLevel != null) {
snowString.append(", ");
}
snowString.append("3-hours snow level: ");
snowString.append(threeHourLevel);
snowString.append(getUnit());
}
return snowString.toString();
}
}
@@ -0,0 +1,298 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.weather;
import com.github.prominence.openweathermap.api.model.*;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* Represents weather information.
*/
public class Weather {
private LocalDateTime calculationTime;
private WeatherState weatherState;
private Temperature temperature;
private AtmosphericPressure atmosphericPressure;
private Humidity humidity;
private Wind wind;
private Rain rain;
private Snow snow;
private Clouds clouds;
private Location location;
/**
* Gets calculated on.
*
* @return the calculated on
*/
public LocalDateTime getCalculationTime() {
return calculationTime;
}
/**
* Sets calculated on.
*
* @param calculationTime the calculated on
*/
public void setCalculationTime(LocalDateTime calculationTime) {
this.calculationTime = calculationTime;
}
/**
* Gets weather state.
*
* @return the weather state
*/
public WeatherState getWeatherState() {
return weatherState;
}
/**
* Sets weather state.
*
* @param weatherState the weather state
*/
public void setWeatherState(WeatherState weatherState) {
this.weatherState = weatherState;
}
/**
* Gets temperature.
*
* @return the temperature
*/
public Temperature getTemperature() {
return temperature;
}
/**
* Sets temperature.
*
* @param temperature the temperature
*/
public void setTemperature(Temperature temperature) {
this.temperature = temperature;
}
/**
* Gets atmospheric pressure.
*
* @return the atmospheric pressure
*/
public AtmosphericPressure getAtmosphericPressure() {
return atmosphericPressure;
}
/**
* Sets atmospheric pressure.
*
* @param atmosphericPressure the atmospheric pressure
*/
public void setAtmosphericPressure(AtmosphericPressure atmosphericPressure) {
this.atmosphericPressure = atmosphericPressure;
}
/**
* Gets humidity.
*
* @return the humidity
*/
public Humidity getHumidity() {
return humidity;
}
/**
* Sets humidity.
*
* @param humidity the humidity
*/
public void setHumidity(Humidity humidity) {
this.humidity = humidity;
}
/**
* Gets wind.
*
* @return the wind
*/
public Wind getWind() {
return wind;
}
/**
* Sets wind.
*
* @param wind the wind
*/
public void setWind(Wind wind) {
this.wind = wind;
}
/**
* Gets rain.
*
* @return the rain
*/
public Rain getRain() {
return rain;
}
/**
* Sets rain.
*
* @param rain the rain
*/
public void setRain(Rain rain) {
this.rain = rain;
}
/**
* Gets snow.
*
* @return the snow
*/
public Snow getSnow() {
return snow;
}
/**
* Sets snow.
*
* @param snow the snow
*/
public void setSnow(Snow snow) {
this.snow = snow;
}
/**
* Gets clouds.
*
* @return the clouds
*/
public Clouds getClouds() {
return clouds;
}
/**
* Sets clouds.
*
* @param clouds the clouds
*/
public void setClouds(Clouds clouds) {
this.clouds = clouds;
}
/**
* Gets location.
*
* @return the location
*/
public Location getLocation() {
return location;
}
/**
* Sets location.
*
* @param location the location
*/
public void setLocation(Location location) {
this.location = location;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Weather)) return false;
Weather weather = (Weather) o;
return Objects.equals(calculationTime, weather.calculationTime) &&
Objects.equals(weatherState, weather.weatherState) &&
Objects.equals(temperature, weather.temperature) &&
Objects.equals(atmosphericPressure, weather.atmosphericPressure) &&
Objects.equals(humidity, weather.humidity) &&
Objects.equals(wind, weather.wind) &&
Objects.equals(rain, weather.rain) &&
Objects.equals(snow, weather.snow) &&
Objects.equals(clouds, weather.clouds) &&
Objects.equals(location, weather.location);
}
@Override
public int hashCode() {
return Objects.hash(calculationTime, weatherState, temperature, atmosphericPressure, humidity, wind, rain, snow, clouds, location);
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder();
if (location != null) {
stringBuilder.append("Location: ");
stringBuilder.append(location.getName());
final String countryCode = location.getCountryCode();
if (countryCode != null) {
stringBuilder.append('(');
stringBuilder.append(countryCode);
stringBuilder.append(')');
}
}
if (weatherState != null) {
stringBuilder.append(", Weather: ");
stringBuilder.append(weatherState.getDescription());
}
if (temperature != null) {
stringBuilder.append(", ");
stringBuilder.append(temperature.getValue());
stringBuilder.append(' ');
stringBuilder.append(temperature.getUnit());
}
if (atmosphericPressure != null) {
stringBuilder.append(", ");
stringBuilder.append(atmosphericPressure.getValue());
stringBuilder.append(' ');
stringBuilder.append(atmosphericPressure.getUnit());
}
if (clouds != null) {
stringBuilder.append(", ");
stringBuilder.append(clouds.toString());
}
if (rain != null && rain.getOneHourLevel() != null) {
stringBuilder.append(", Rain: ");
stringBuilder.append(rain.getOneHourLevel());
stringBuilder.append(' ');
stringBuilder.append(rain.getUnit());
}
if (snow != null && snow.getOneHourLevel() != null) {
stringBuilder.append(", Snow: ");
stringBuilder.append(snow.getOneHourLevel());
stringBuilder.append(' ');
stringBuilder.append(snow.getUnit());
}
return stringBuilder.toString();
}
}
@@ -0,0 +1,170 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.model.weather;
import java.util.Objects;
/**
* The type Wind.
*/
public class Wind {
private double speed;
private Double degrees;
private Double gust;
private String unit;
/**
* Instantiates a new Wind.
*
* @param speed the speed
* @param unit the unitSystem
*/
private Wind(double speed, String unit) {
this.speed = speed;
this.unit = unit;
}
/**
* Creates {@link Wind} object with correctness check.
* @param speed the speed
* @param unit the unitSystem
* @return wind object
*/
public static Wind withValue(double speed, String unit) {
if (speed < 0) {
throw new IllegalArgumentException("Wind speed value must be in positive or zero.");
}
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
return new Wind(speed, unit);
}
/**
* Gets speed.
*
* @return the speed
*/
public double getSpeed() {
return speed;
}
/**
* Sets speed.
*
* @param speed the speed
*/
public void setSpeed(double speed) {
if (speed < 0) {
throw new IllegalArgumentException("Wind speed value must be in positive or zero.");
}
this.speed = speed;
}
/**
* Gets gust value.
* @return the gust
*/
public Double getGust() {
return gust;
}
/**
* Sets gust value.
* @param gust the gust.
*/
public void setGust(double gust) {
if (gust < 0) {
throw new IllegalArgumentException("Gust value must be positive or zero.");
}
this.gust = gust;
}
/**
* Gets degrees.
*
* @return the degrees
*/
public Double getDegrees() {
return degrees;
}
/**
* Sets degrees.
*
* @param degrees the degrees
*/
public void setDegrees(double degrees) {
if (degrees < 0 || degrees > 360) {
throw new IllegalArgumentException("Wind direction value must be in [0, 360] range.");
}
this.degrees = degrees;
}
/**
* Gets unitSystem.
*
* @return the unitSystem
*/
public String getUnit() {
return unit;
}
/**
* Sets unitSystem.
*
* @param unit the unitSystem
*/
public void setUnit(String unit) {
if (unit == null) {
throw new IllegalArgumentException("Unit must be set.");
}
this.unit = unit;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Wind)) return false;
Wind wind = (Wind) o;
return Double.compare(wind.speed, speed) == 0 &&
Objects.equals(degrees, wind.degrees) &&
Objects.equals(gust, wind.gust) &&
Objects.equals(unit, wind.unit);
}
@Override
public int hashCode() {
return Objects.hash(speed, degrees, gust, unit);
}
@Override
public String toString() {
String output = "Wind speed: " + speed + " " + unit +
", degrees: " + degrees;
if (gust != null) {
output += ", Gust: " + gust + " " + unit;
}
return output;
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,14 +20,15 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api; package com.github.prominence.openweathermap.api.request;
abstract class AuthenticationTokenBasedRequester { import java.util.concurrent.CompletableFuture;
protected String authToken;
protected AuthenticationTokenBasedRequester(String authToken) {
this.authToken = authToken;
}
/**
* The interface Async request terminator.
*
* @param <T> the type parameter
* @param <S> the type parameter
*/
public interface AsyncRequestTerminator<T, S> extends RequestTerminator<CompletableFuture<T>, CompletableFuture<S>> {
} }
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
/**
* The interface Request customizer.
*
* @param <T> the type parameter
*/
public interface RequestCustomizer<T extends RequestCustomizer<?>> {
/**
* Customize language.
*
* @param language the language
* @return the request customizer
*/
T language(Language language);
/**
* Customize unit system.
*
* @param unitSystem the unit system
* @return the request customizer
*/
T unitSystem(UnitSystem unitSystem);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,12 +20,27 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api.constants; package com.github.prominence.openweathermap.api.request;
public final class System { /**
* The interface Request terminator.
*
* @param <T> the type parameter
* @param <S> the type parameter
*/
public interface RequestTerminator<T, S> {
private System() {} /**
* Java object response format.
*
* @return the java object
*/
T asJava();
public static final String OPEN_WEATHER_API_VERSION = "2.5"; /**
public static final String OPEN_WEATHER_API_URL = "http://api.openweathermap.org/data/" + OPEN_WEATHER_API_VERSION + "/"; * JSON response format.
*
* @return the JSON string
*/
S asJSON();
} }
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
/**
* The type Request url builder.
*/
public class RequestUrlBuilder {
private static final String API_KEY_PARAM_NAME = "appid";
private final StringBuilder builder = new StringBuilder("http://api.openweathermap.org/data/2.5/");
private final Map<String, Object> requestParameters = new HashMap<>();
/**
* Instantiates a new Request url builder.
*
* @param key the API key
*/
public RequestUrlBuilder(String key) {
requestParameters.put(API_KEY_PARAM_NAME, key);
}
/**
* Appends value.
*
* @param value the value
*/
public void append(String value) {
builder.append(value);
}
/**
* Adds request parameter.
*
* @param key the key
* @param value the value
*/
public void addRequestParameter(String key, Object value) {
requestParameters.put(key, value);
}
/**
* Applies customization.
*
* @param language the language
* @param unitSystem the unit system
*/
public void applyCustomization(Language language, UnitSystem unitSystem) {
if (language != null) {
addRequestParameter("lang", language.getValue());
}
if (unitSystem != null && unitSystem != UnitSystem.STANDARD) {
addRequestParameter("units", unitSystem.getValue());
}
}
/**
* Builds url string.
*
* @return the string
*/
public String buildUrl() {
final String joinedParameters = requestParameters.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("&"));
builder.append('?');
builder.append(joinedParameters);
return builder.toString();
}
}
@@ -0,0 +1,42 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
import java.util.concurrent.CompletableFuture;
/**
* The forecast async request terminator interface.
*/
public interface FiveDayThreeHourStepForecastAsyncRequestTerminator extends AsyncRequestTerminator<Forecast, String> {
/**
* XML response format.
*
* @return the completable future
*/
CompletableFuture<String> asXML();
}
@@ -0,0 +1,69 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* Async request terminator.
*/
public class FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl implements FiveDayThreeHourStepForecastAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CompletableFuture<Forecast> asJava() {
return CompletableFuture.supplyAsync(() -> new FiveDayThreeHourStepForecastResponseMapper(unitSystem).mapToForecast(getRawResponse()));
}
@Override
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
@Override
public CompletableFuture<String> asXML() {
urlBuilder.addRequestParameter("mode", "xml");
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
/**
* The forecast request customizer interface.
*/
public interface FiveDayThreeHourStepForecastRequestCustomizer extends RequestCustomizer<FiveDayThreeHourStepForecastRequestCustomizer> {
/**
* Count customizer.
*
* @param numberOfTimestamps the number of timestamps
* @return forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer count(int numberOfTimestamps);
/**
* Retrieve forecast request terminator.
*
* @return forecast request terminator
*/
FiveDayThreeHourStepForecastRequestTerminator retrieve();
/**
* Retrieve forecast async request terminator.
*
* @return forecast async request terminator
*/
FiveDayThreeHourStepForecastAsyncRequestTerminator retrieveAsync();
}
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
/**
* The forecast request customizer.
*/
public class FiveDayThreeHourStepForecastRequestCustomizerImpl implements FiveDayThreeHourStepForecastRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
private int count = -1;
/**
* Instantiates a new forecast request customizer.
*
* @param urlBuilder the url builder
*/
FiveDayThreeHourStepForecastRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer count(int numberOfTimestamps) {
count = numberOfTimestamps;
return this;
}
@Override
public FiveDayThreeHourStepForecastRequestTerminator retrieve() {
applyCustomization();
return new FiveDayThreeHourStepForecastRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public FiveDayThreeHourStepForecastAsyncRequestTerminator retrieveAsync() {
applyCustomization();
return new FiveDayThreeHourStepForecastAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
private void applyCustomization() {
urlBuilder.applyCustomization(language, unitSystem);
if (count >= 0) {
urlBuilder.addRequestParameter("cnt", count);
}
}
}
@@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
/**
* The forecast request terminator interface.
*/
public interface FiveDayThreeHourStepForecastRequestTerminator extends RequestTerminator<Forecast, String> {
/**
* XML response format.
*
* @return the XML string
*/
String asXML();
}
@@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.forecast.Forecast;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The forecast request terminator.
*/
public class FiveDayThreeHourStepForecastRequestTerminatorImpl implements FiveDayThreeHourStepForecastRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new forecast request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
FiveDayThreeHourStepForecastRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public Forecast asJava() {
return new FiveDayThreeHourStepForecastResponseMapper(unitSystem).mapToForecast(getRawResponse());
}
@Override
public String asJSON() {
return getRawResponse();
}
@Override
public String asXML() {
urlBuilder.addRequestParameter("mode", "xml");
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.model.Coordinate;
/**
* An interface for <a href="https://openweathermap.org/forecast5">API</a> methods.
*/
public interface FiveDayThreeHourStepForecastRequester {
/**
* By city name forecast request customizer.
*
* @param cityName the city name
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName);
/**
* By city name forecast request customizer.
*
* @param cityName the city name
* @param stateCode the state code
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode);
/**
* By city name forecast request customizer.
*
* @param cityName the city name
* @param stateCode the state code
* @param countryCode the country code
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode, String countryCode);
/**
* By city id forecast request customizer.
*
* @param cityId the city id
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCityId(long cityId);
/**
* By coordinate forecast request customizer.
*
* @param coordinate the coordinate
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byCoordinate(Coordinate coordinate);
/**
* By zip code and country forecast request customizer.
*
* @param zipCode the zip code
* @param countryCode the country code
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode);
/**
* By zip code in USA forecast request customizer.
*
* @param zipCode the zip code
* @return the forecast request customizer
*/
FiveDayThreeHourStepForecastRequestCustomizer byZipCodeInUSA(String zipCode);
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
/**
* The forecast requester.
*/
public class FiveDayThreeHourStepForecastRequesterImpl implements FiveDayThreeHourStepForecastRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new forecast requester.
*
* @param apiKey the api key
*/
public FiveDayThreeHourStepForecastRequesterImpl(String apiKey) {
urlBuilder = new RequestUrlBuilder(apiKey);
urlBuilder.append("forecast");
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName) {
urlBuilder.addRequestParameter("q", cityName);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode) {
urlBuilder.addRequestParameter("q", cityName + "," + stateCode);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byCityName(String cityName, String stateCode, String countryCode) {
urlBuilder.addRequestParameter("q", cityName + "," + stateCode + "," + countryCode);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byCityId(long cityId) {
urlBuilder.addRequestParameter("id", cityId);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byCoordinate(Coordinate coordinate) {
urlBuilder.addRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
urlBuilder.addRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byZipCodeAndCountry(String zipCode, String countryCode) {
urlBuilder.addRequestParameter("zip", zipCode + "," + countryCode);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
@Override
public FiveDayThreeHourStepForecastRequestCustomizer byZipCodeInUSA(String zipCode) {
urlBuilder.addRequestParameter("zip", zipCode);
return new FiveDayThreeHourStepForecastRequestCustomizerImpl(urlBuilder);
}
}
@@ -0,0 +1,303 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.forecast.free;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.*;
import com.github.prominence.openweathermap.api.model.forecast.*;
import com.github.prominence.openweathermap.api.model.forecast.Location;
import com.github.prominence.openweathermap.api.model.forecast.Rain;
import com.github.prominence.openweathermap.api.model.forecast.Snow;
import com.github.prominence.openweathermap.api.model.Temperature;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/**
* Official API response documentation.
* Parameters(but the real response can differ):
* --- cod Internal parameter
* --- message Internal parameter
* --- cnt A number of timestamps returned in the API response
* --- list
* |- list.dt Time of data forecasted, unix, UTC
* |- list.main
* |- list.main.temp Temperature. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
* |- list.main.feels_like This temperature parameter accounts for the human perception of weather. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
* |- list.main.temp_min Minimum temperature at the moment of calculation. This is minimal forecasted temperature (within large megalopolises and urban areas), use this parameter optionally. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
* |- list.main.temp_max Maximum temperature at the moment of calculation. This is maximal forecasted temperature (within large megalopolises and urban areas), use this parameter optionally. Unit Default: Kelvin, Metric: Celsius, Imperial: Fahrenheit.
* |- list.main.pressure Atmospheric pressure on the sea level by default, hPa
* |- list.main.sea_level Atmospheric pressure on the sea level, hPa
* |- list.main.grnd_level Atmospheric pressure on the ground level, hPa
* |- list.main.humidity Humidity, %
* |- list.main.temp_kf Internal par
* |- list.weather
* |- list.weather.id Weather condition id
* |- list.weather.main Group of weather parameters (Rain, Snow, Extreme etc.)
* |- list.weather.description Weather condition within the group. You can get the output in your language.
* |- list.weather.icon Weather icon id
* |- list.clouds
* |- list.clouds.all Cloudiness, %
* |- list.wind
* |- list.wind.speed Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour.
* |- list.wind.deg Wind direction, degrees (meteorological)
* |- list.visibility Average visibility, metres
* |- list.pop Probability of precipitation
* |- list.rain
* |- list.rain.3h Rain volume for last 3 hours, mm
* |- list.snow
* |- list.snow.3h Snow volume for last 3 hours
* |- list.sys
* |- list.sys.pod Part of the day (n - night, d - day)
* |- list.dt_txt Time of data forecasted, ISO, UTC
* --- city
* |- city.id City ID
* |- city.name City name
* |- city.coord
* |- city.coord.lat City geo location, latitude
* |- city.coord.lon City geo location, longitude
* |- city.country Country code (GB, JP etc.)
* |- city.timezone Shift in seconds from UTC
*/
public class FiveDayThreeHourStepForecastResponseMapper {
private final UnitSystem unitSystem;
/**
* Instantiates a new forecast response mapper.
*
* @param unitSystem the unit system
*/
public FiveDayThreeHourStepForecastResponseMapper(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
}
/**
* Maps forecast response into java object.
*
* @param json the json string
* @return the forecast
*/
public Forecast mapToForecast(String json) {
final ObjectMapper objectMapper = new ObjectMapper();
Forecast forecast;
try {
final JsonNode root = objectMapper.readTree(json);
forecast = mapToForecast(root);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Forecast response");
}
return forecast;
}
private Forecast mapToForecast(JsonNode root) {
final Forecast forecast = new Forecast();
forecast.setLocation(parseLocation(root.get("city")));
final List<WeatherForecast> forecasts = new ArrayList<>(root.get("cnt").asInt());
final JsonNode forecastListNode = root.get("list");
forecastListNode.forEach(forecastNode -> forecasts.add(parseWeatherForecast(forecastNode)));
forecast.setWeatherForecasts(forecasts);
return forecast;
}
private WeatherForecast parseWeatherForecast(JsonNode rootNode) {
final WeatherForecast weatherForecast = new WeatherForecast();
final JsonNode weatherArrayNode = rootNode.get("weather");
if (weatherArrayNode != null) {
final JsonNode weatherNode = weatherArrayNode.get(0);
weatherForecast.setWeatherState(parseWeatherState(weatherNode));
}
final JsonNode mainNode = rootNode.get("main");
weatherForecast.setTemperature(parseTemperature(mainNode));
weatherForecast.setAtmosphericPressure(parsePressure(mainNode));
weatherForecast.setHumidity(parseHumidity(mainNode));
weatherForecast.setClouds(parseClouds(rootNode));
weatherForecast.setWind(parseWind(rootNode));
weatherForecast.setRain(parseRain(rootNode));
weatherForecast.setSnow(parseSnow(rootNode));
final JsonNode sysNode = rootNode.get("sys");
if (sysNode != null) {
weatherForecast.setDayTime("d".equals(sysNode.get("pod").asText()) ? DayTime.DAY : DayTime.NIGHT);
}
weatherForecast.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(rootNode.get("dt").asLong()), TimeZone.getDefault().toZoneId()));
weatherForecast.setForecastTimeISO(rootNode.get("dt_txt").asText());
return weatherForecast;
}
private WeatherState parseWeatherState(JsonNode weatherNode) {
if (weatherNode == null) {
return null;
}
final WeatherState weatherState = new WeatherState(
weatherNode.get("id").asInt(),
weatherNode.get("main").asText(),
weatherNode.get("description").asText()
);
weatherState.setIconId(weatherNode.get("icon").asText());
return weatherState;
}
private Temperature parseTemperature(JsonNode rootNode) {
final double tempValue = rootNode.get("temp").asDouble();
final Temperature temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final JsonNode tempMaxNode = rootNode.get("temp_max");
if (tempMaxNode != null) {
temperature.setMaxTemperature(tempMaxNode.asDouble());
}
final JsonNode tempMinNode = rootNode.get("temp_min");
if (tempMinNode != null) {
temperature.setMinTemperature(tempMinNode.asDouble());
}
final JsonNode tempFeelsLike = rootNode.get("feels_like");
if (tempFeelsLike != null) {
temperature.setFeelsLike(tempFeelsLike.asDouble());
}
return temperature;
}
private AtmosphericPressure parsePressure(JsonNode rootNode) {
final AtmosphericPressure atmosphericPressure = AtmosphericPressure.withValue(rootNode.get("pressure").asDouble());
final JsonNode seaLevelNode = rootNode.get("sea_level");
final JsonNode groundLevelNode = rootNode.get("grnd_level");
if (seaLevelNode != null) {
atmosphericPressure.setSeaLevelValue(seaLevelNode.asDouble());
}
if (groundLevelNode != null) {
atmosphericPressure.setGroundLevelValue(groundLevelNode.asDouble());
}
return atmosphericPressure;
}
private Humidity parseHumidity(JsonNode rootNode) {
return Humidity.withValue((byte) (rootNode.get("humidity").asInt()));
}
private Wind parseWind(JsonNode root) {
final JsonNode windNode = root.get("wind");
double speed = windNode.get("speed").asDouble();
final Wind wind = Wind.withValue(speed, unitSystem.getWindUnit());
final JsonNode degNode = windNode.get("deg");
if (degNode != null) {
wind.setDegrees(degNode.asDouble());
}
return wind;
}
private Rain parseRain(JsonNode root) {
final JsonNode rainNode = root.get("rain");
if (rainNode != null) {
final JsonNode threeHourNode = rainNode.get("3h");
if (threeHourNode != null) {
return Rain.withThreeHourLevelValue(threeHourNode.asDouble());
}
}
return null;
}
private Snow parseSnow(JsonNode root) {
final JsonNode snowNode = root.get("snow");
if (snowNode != null) {
final JsonNode threeHourNode = snowNode.get("3h");
if (threeHourNode != null) {
return Snow.withThreeHourLevelValue(threeHourNode.asDouble());
}
}
return null;
}
private Clouds parseClouds(JsonNode rootNode) {
final JsonNode cloudsNode = rootNode.get("clouds");
final JsonNode allValueNode = cloudsNode.get("all");
if (allValueNode != null) {
return Clouds.withValue((byte) allValueNode.asInt());
}
return null;
}
private Location parseLocation(JsonNode rootNode) {
final Location location = Location.withValues(rootNode.get("id").asInt(), rootNode.get("name").asText());
final JsonNode timezoneNode = rootNode.get("timezone");
if (timezoneNode != null) {
location.setZoneOffset(ZoneOffset.ofTotalSeconds(timezoneNode.asInt()));
}
final JsonNode countryNode = rootNode.get("country");
if (countryNode != null) {
location.setCountryCode(countryNode.asText());
}
final JsonNode sunriseNode = rootNode.get("sunrise");
final JsonNode sunsetNode = rootNode.get("sunset");
if (sunriseNode != null) {
location.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunriseNode.asLong()), TimeZone.getDefault().toZoneId()));
}
if (sunsetNode != null) {
location.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(sunsetNode.asLong()), TimeZone.getDefault().toZoneId()));
}
final JsonNode coordNode = rootNode.get("coord");
if (coordNode != null) {
location.setCoordinate(parseCoordinate(coordNode));
}
final JsonNode populationNode = rootNode.get("population");
if (populationNode != null) {
location.setPopulation(populationNode.asLong());
}
return location;
}
private Coordinate parseCoordinate(JsonNode rootNode) {
final JsonNode latitudeNode = rootNode.get("lat");
final JsonNode longitudeNode = rootNode.get("lon");
if (latitudeNode != null && longitudeNode != null) {
return Coordinate.of(latitudeNode.asDouble(), longitudeNode.asDouble());
}
return null;
}
}
@@ -0,0 +1,45 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall;
import com.github.prominence.openweathermap.api.request.onecall.current.OneCallCurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.onecall.historical.OneCallHistoricalWeatherRequester;
/**
* The interface One call weather requester.
*/
public interface OneCallWeatherRequester {
/**
* Current one call current weather requester.
*
* @return the one call current weather requester
*/
OneCallCurrentWeatherRequester current();
/**
* Historical one call historical weather requester.
*
* @return the one call historical weather requester
*/
OneCallHistoricalWeatherRequester historical();
}
@@ -0,0 +1,55 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.onecall.current.OneCallCurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.onecall.current.OneCallCurrentWeatherRequesterImpl;
import com.github.prominence.openweathermap.api.request.onecall.historical.OneCallHistoricalWeatherRequester;
import com.github.prominence.openweathermap.api.request.onecall.historical.OneCallHistoricalWeatherRequesterImpl;
/**
* The type One call weather requester.
*/
public class OneCallWeatherRequesterImpl implements OneCallWeatherRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new One call weather requester.
*
* @param apiKey the api key
*/
public OneCallWeatherRequesterImpl(String apiKey) {
urlBuilder = new RequestUrlBuilder(apiKey);
}
@Override
public OneCallCurrentWeatherRequester current() {
return new OneCallCurrentWeatherRequesterImpl(urlBuilder);
}
@Override
public OneCallHistoricalWeatherRequester historical() {
return new OneCallHistoricalWeatherRequesterImpl(urlBuilder);
}
}
@@ -0,0 +1,430 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.Clouds;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.model.Humidity;
import com.github.prominence.openweathermap.api.model.WeatherState;
import com.github.prominence.openweathermap.api.model.onecall.*;
import com.github.prominence.openweathermap.api.model.onecall.current.*;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeather;
import com.github.prominence.openweathermap.api.model.onecall.historical.HourlyHistorical;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/**
* Object mapper for OneCall API response.
*/
public class OneCallWeatherResponseMapper {
private final UnitSystem unitSystem;
/**
* Instantiates a new forecast response mapper.
*
* @param unitSystem the unit system
*/
public OneCallWeatherResponseMapper(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
}
/**
* Maps current weather data response into java object.
*
* @param json the json string
* @return the current data object
*/
public CurrentWeatherData mapToCurrent(String json) {
final ObjectMapper objectMapper = new ObjectMapper();
CurrentWeatherData currentData;
try {
final JsonNode root = objectMapper.readTree(json);
currentData = mapToCurrent(root);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Forecast response");
}
return currentData;
}
/**
* Maps current weather data response into java object.
*
* @param json the json string
* @return the current data object
*/
public HistoricalWeatherData mapToHistorical(String json) {
final ObjectMapper objectMapper = new ObjectMapper();
HistoricalWeatherData historicalData;
try {
final JsonNode root = objectMapper.readTree(json);
historicalData = mapToHistorical(root);
} catch (JsonProcessingException e) {
throw new RuntimeException("Cannot parse Forecast response");
}
return historicalData;
}
private CurrentWeatherData mapToCurrent(JsonNode rootNode) {
final CurrentWeatherData currentData = new CurrentWeatherData();
currentData.setCoordinate(Coordinate.of(rootNode.get("lat").asDouble(), rootNode.get("lon").asDouble()));
currentData.setTimezone(ZoneId.of(rootNode.get("timezone").asText()));
currentData.setTimezoneOffset(ZoneOffset.ofTotalSeconds(rootNode.get("timezone_offset").asInt()));
currentData.setCurrent(parseCurrent(rootNode.get("current")));
currentData.setMinutelyList(parseMinutelyList(rootNode.get("minutely")));
currentData.setHourlyList(parseHourlyList(rootNode.get("hourly")));
currentData.setDailyList(parseDailyList(rootNode.get("daily")));
currentData.setAlerts(parseAlerts(rootNode.get("alerts")));
return currentData;
}
private Current parseCurrent(JsonNode currentNode) {
if (currentNode == null) {
return null;
}
final Current current = new Current();
current.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
current.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("sunrise").asInt()), TimeZone.getDefault().toZoneId()));
current.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("sunset").asInt()), TimeZone.getDefault().toZoneId()));
current.setWeatherState(parseWeatherState(currentNode.get("weather").get(0)));
current.setTemperature(parseTemperature(currentNode));
current.setAtmosphericPressure(parsePressure(currentNode));
current.setHumidity(parseHumidity(currentNode));
current.setClouds(parseClouds(currentNode));
current.setUvIndex(currentNode.get("uvi").asDouble());
final JsonNode visibilityNode = currentNode.get("visibility");
if (visibilityNode != null) {
current.setVisibilityInMetres(visibilityNode.asDouble());
}
current.setWind(parseWind(currentNode));
current.setRain(parseRain(currentNode));
current.setSnow(parseSnow(currentNode));
return current;
}
private List<Minutely> parseMinutelyList(JsonNode minutelyListNode) {
if (minutelyListNode == null) {
return null;
}
final List<Minutely> minutelyList = new ArrayList<>();
for (final JsonNode minutelyNode : minutelyListNode) {
minutelyList.add(Minutely.withValue(
LocalDateTime.ofInstant(Instant.ofEpochSecond(minutelyNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()),
minutelyNode.get("precipitation").asDouble()
));
}
return minutelyList;
}
private List<Hourly> parseHourlyList(JsonNode hourlyListNode) {
if (hourlyListNode == null) {
return null;
}
final List<Hourly> hourlyList = new ArrayList<>();
for (final JsonNode hourlyNode : hourlyListNode) {
final Hourly hourly = new Hourly();
hourly.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(hourlyNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
hourly.setWeatherState(parseWeatherState(hourlyNode.get("weather").get(0)));
hourly.setTemperature(parseTemperature(hourlyNode));
hourly.setAtmosphericPressure(parsePressure(hourlyNode));
hourly.setHumidity(parseHumidity(hourlyNode));
hourly.setClouds(parseClouds(hourlyNode));
final JsonNode uviNode = hourlyNode.get("uvi");
if (uviNode != null) {
hourly.setUvIndex(uviNode.asDouble());
}
final JsonNode visibilityNode = hourlyNode.get("visibility");
if (visibilityNode != null) {
hourly.setVisibilityInMetres(visibilityNode.asDouble());
}
hourly.setWind(parseWind(hourlyNode));
final JsonNode popNode = hourlyNode.get("pop");
if (popNode != null) {
hourly.setProbabilityOfPrecipitation(popNode.asDouble());
}
hourly.setRain(parseRain(hourlyNode));
hourly.setSnow(parseSnow(hourlyNode));
hourlyList.add(hourly);
}
return hourlyList;
}
private List<Daily> parseDailyList(JsonNode dailyListNode) {
if (dailyListNode == null) {
return null;
}
final List<Daily> dailyList = new ArrayList<>();
for (final JsonNode dailyNode : dailyListNode) {
final Daily daily = new Daily();
daily.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(dailyNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
daily.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(dailyNode.get("sunrise").asInt()), TimeZone.getDefault().toZoneId()));
daily.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(dailyNode.get("sunset").asInt()), TimeZone.getDefault().toZoneId()));
daily.setWeatherState(parseWeatherState(dailyNode.get("weather").get(0)));
daily.setTemperature(parseDailyTemperature(dailyNode));
daily.setAtmosphericPressure(parsePressure(dailyNode));
daily.setHumidity(parseHumidity(dailyNode));
daily.setWind(parseWind(dailyNode));
daily.setClouds(parseClouds(dailyNode));
daily.setUvIndex(dailyNode.get("uvi").asDouble());
daily.setProbabilityOfPrecipitation(dailyNode.get("pop").asDouble());
daily.setRain(parseDailyRain(dailyNode));
daily.setSnow(parseDailySnow(dailyNode));
dailyList.add(daily);
}
return dailyList;
}
private List<Alert> parseAlerts(JsonNode alertsNode) {
if (alertsNode == null) {
return null;
}
final List<Alert> alerts = new ArrayList<>();
for (final JsonNode alertNode : alertsNode) {
Alert alert = new Alert();
alert.setSenderName(alertNode.get("sender_name").asText());
alert.setEventName(alertNode.get("event").asText());
alert.setStartTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(alertNode.get("start").asInt()), TimeZone.getDefault().toZoneId()));
alert.setEndTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(alertNode.get("end").asInt()), TimeZone.getDefault().toZoneId()));
alert.setDescription(alertNode.get("description").asText());
alerts.add(alert);
}
return alerts;
}
private HistoricalWeatherData mapToHistorical(JsonNode rootNode) {
final HistoricalWeatherData historicalData = new HistoricalWeatherData();
historicalData.setCoordinate(Coordinate.of(rootNode.get("lat").asDouble(), rootNode.get("lon").asDouble()));
historicalData.setTimezone(ZoneId.of(rootNode.get("timezone").asText()));
historicalData.setTimezoneOffset(ZoneOffset.ofTotalSeconds(rootNode.get("timezone_offset").asInt()));
historicalData.setHistoricalWeather(parseHistoricalWeather(rootNode.get("current")));
historicalData.setHourlyList(parseHourlyHistoricalList(rootNode.get("hourly")));
return historicalData;
}
private HistoricalWeather parseHistoricalWeather(JsonNode currentNode) {
if (currentNode == null) {
return null;
}
final HistoricalWeather historicalWeather = new HistoricalWeather();
historicalWeather.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
historicalWeather.setSunriseTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("sunrise").asInt()), TimeZone.getDefault().toZoneId()));
historicalWeather.setSunsetTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(currentNode.get("sunset").asInt()), TimeZone.getDefault().toZoneId()));
final JsonNode weatherListNode = currentNode.get("weather");
if (weatherListNode != null) {
historicalWeather.setWeatherState(parseWeatherState(weatherListNode.get(0)));
}
historicalWeather.setTemperature(parseTemperature(currentNode));
historicalWeather.setAtmosphericPressure(parsePressure(currentNode));
historicalWeather.setHumidity(parseHumidity(currentNode));
historicalWeather.setClouds(parseClouds(currentNode));
historicalWeather.setUvIndex(currentNode.get("uvi").asDouble());
final JsonNode visibilityMode = currentNode.get("visibility");
if (visibilityMode != null) {
historicalWeather.setVisibilityInMetres(visibilityMode.asDouble());
}
historicalWeather.setWind(parseWind(currentNode));
historicalWeather.setRain(parseRain(currentNode));
historicalWeather.setSnow(parseSnow(currentNode));
return historicalWeather;
}
private List<HourlyHistorical> parseHourlyHistoricalList(JsonNode hourlyListNode) {
if (hourlyListNode == null) {
return null;
}
final List<HourlyHistorical> hourlyList = new ArrayList<>();
for (final JsonNode hourlyNode : hourlyListNode) {
final HourlyHistorical hourly = new HourlyHistorical();
hourly.setForecastTime(LocalDateTime.ofInstant(Instant.ofEpochSecond(hourlyNode.get("dt").asInt()), TimeZone.getDefault().toZoneId()));
hourly.setWeatherState(parseWeatherState(hourlyNode.get("weather").get(0)));
hourly.setTemperature(parseTemperature(hourlyNode));
hourly.setAtmosphericPressure(parsePressure(hourlyNode));
hourly.setHumidity(parseHumidity(hourlyNode));
hourly.setClouds(parseClouds(hourlyNode));
final JsonNode visibilityNode = hourlyNode.get("visibility");
if (visibilityNode != null) {
hourly.setVisibilityInMetres(visibilityNode.asDouble());
}
hourly.setWind(parseWind(hourlyNode));
hourly.setRain(parseRain(hourlyNode));
hourly.setSnow(parseSnow(hourlyNode));
hourlyList.add(hourly);
}
return hourlyList;
}
private WeatherState parseWeatherState(JsonNode weatherNode) {
if (weatherNode == null) {
return null;
}
final WeatherState weatherState = new WeatherState(
weatherNode.get("id").asInt(),
weatherNode.get("main").asText(),
weatherNode.get("description").asText()
);
weatherState.setIconId(weatherNode.get("icon").asText());
return weatherState;
}
private Temperature parseTemperature(JsonNode rootNode) {
final double tempValue = rootNode.get("temp").asDouble();
final Temperature temperature = Temperature.withValue(tempValue, unitSystem.getTemperatureUnit());
final JsonNode tempFeelsLike = rootNode.get("feels_like");
if (tempFeelsLike != null) {
temperature.setFeelsLike(tempFeelsLike.asDouble());
}
final JsonNode dewPoint = rootNode.get("dew_point");
if (dewPoint != null) {
temperature.setDewPoint(dewPoint.asDouble());
}
return temperature;
}
private DailyTemperature parseDailyTemperature(JsonNode dailyNode) {
final DailyTemperature temperature = new DailyTemperature();
final JsonNode tempNode = dailyNode.get("temp");
temperature.setMorning(tempNode.get("morn").asDouble());
temperature.setDay(tempNode.get("day").asDouble());
temperature.setEve(tempNode.get("eve").asDouble());
temperature.setNight(tempNode.get("night").asDouble());
temperature.setMin(tempNode.get("min").asDouble());
temperature.setMax(tempNode.get("max").asDouble());
final JsonNode feelsLikeNode = dailyNode.get("feels_like");
temperature.setMorningFeelsLike(feelsLikeNode.get("morn").asDouble());
temperature.setDayFeelsLike(feelsLikeNode.get("day").asDouble());
temperature.setEveFeelsLike(feelsLikeNode.get("eve").asDouble());
temperature.setNightFeelsLike(feelsLikeNode.get("night").asDouble());
return temperature;
}
private AtmosphericPressure parsePressure(JsonNode rootNode) {
return AtmosphericPressure.withValue(rootNode.get("pressure").asDouble());
}
private Humidity parseHumidity(JsonNode rootNode) {
return Humidity.withValue((byte) (rootNode.get("humidity").asInt()));
}
private Wind parseWind(JsonNode rootNode) {
final JsonNode windSpeedNode = rootNode.get("wind_speed");
if (windSpeedNode == null) {
return null;
}
final Wind wind = Wind.withValue(windSpeedNode.asDouble(), unitSystem.getWindUnit());
final JsonNode degNode = rootNode.get("wind_deg");
if (degNode != null) {
wind.setDegrees(degNode.asDouble());
}
final JsonNode gustNode = rootNode.get("wind_gust");
if (gustNode != null) {
wind.setGust(gustNode.asDouble());
}
return wind;
}
private Rain parseRain(JsonNode root) {
final JsonNode rainNode = root.get("rain");
if (rainNode != null) {
final JsonNode oneHourNode = rainNode.get("1h");
if (oneHourNode != null) {
return Rain.withOneHourLevelValue(oneHourNode.asDouble());
}
}
return null;
}
private DailyRain parseDailyRain(JsonNode dailyNode) {
final JsonNode valueNode = dailyNode.get("rain");
if (valueNode != null) {
return DailyRain.withValue(valueNode.asDouble());
}
return null;
}
private Snow parseSnow(JsonNode root) {
final JsonNode snowNode = root.get("snow");
if (snowNode != null) {
final JsonNode OneHourNode = snowNode.get("1h");
if (OneHourNode != null) {
Rain.withOneHourLevelValue(OneHourNode.asDouble());
}
}
return null;
}
private DailySnow parseDailySnow(JsonNode dailyNode) {
final JsonNode valueNode = dailyNode.get("snow");
if (valueNode != null) {
return DailySnow.withValue(valueNode.asDouble());
}
return null;
}
private Clouds parseClouds(JsonNode rootNode) {
final JsonNode cloudsNode = rootNode.get("clouds");
if (cloudsNode != null) {
return Clouds.withValue((byte) cloudsNode.asInt());
}
return null;
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
/**
* The interface One call current weather async request terminator.
*/
public interface OneCallCurrentWeatherAsyncRequestTerminator extends AsyncRequestTerminator<CurrentWeatherData, String> {
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The type One call current weather async request terminator.
*/
public class OneCallCurrentWeatherAsyncRequestTerminatorImpl implements OneCallCurrentWeatherAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new One call current weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
OneCallCurrentWeatherAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CompletableFuture<CurrentWeatherData> asJava() {
return CompletableFuture.supplyAsync(() -> new OneCallWeatherResponseMapper(unitSystem).mapToCurrent(getRawResponse()));
}
@Override
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.enums.OneCallResultOptions;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
/**
* The interface One call current weather request customizer.
*/
public interface OneCallCurrentWeatherRequestCustomizer extends RequestCustomizer<OneCallCurrentWeatherRequestCustomizer> {
/**
* Exclude one call current weather request customizer.
*
* @param excludeOptions the exclude options
* @return the one call current weather request customizer
*/
OneCallCurrentWeatherRequestCustomizer exclude(OneCallResultOptions... excludeOptions);
/**
* Retrieve one call current weather request terminator.
*
* @return the one call current weather request terminator
*/
OneCallCurrentWeatherRequestTerminator retrieve();
/**
* Retrieve async one call current weather async request terminator.
*
* @return the one call current weather async request terminator
*/
OneCallCurrentWeatherAsyncRequestTerminator retrieveAsync();
}
@@ -0,0 +1,88 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.OneCallResultOptions;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* The type One call current weather request customizer.
*/
public class OneCallCurrentWeatherRequestCustomizerImpl implements OneCallCurrentWeatherRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
private OneCallResultOptions[] excludeOptions;
/**
* Instantiates a new One call current weather request customizer.
*
* @param urlBuilder the url builder
*/
OneCallCurrentWeatherRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public OneCallCurrentWeatherRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public OneCallCurrentWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
@Override
public OneCallCurrentWeatherRequestCustomizer exclude(OneCallResultOptions... excludeOptions) {
this.excludeOptions = excludeOptions;
return this;
}
@Override
public OneCallCurrentWeatherRequestTerminator retrieve() {
applyCustomization();
return new OneCallCurrentWeatherRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public OneCallCurrentWeatherAsyncRequestTerminator retrieveAsync() {
applyCustomization();
return new OneCallCurrentWeatherAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
private void applyCustomization() {
urlBuilder.applyCustomization(language, unitSystem);
if (excludeOptions != null) {
urlBuilder.addRequestParameter("exclude", Stream.of(excludeOptions).map(OneCallResultOptions::getValue).collect(Collectors.joining(",")));
}
}
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,13 +20,14 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api.constants; package com.github.prominence.openweathermap.api.request.onecall.current;
public final class Accuracy { import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
private Accuracy() {} /**
* The interface One call current weather request terminator.
public static final String LIKE = "like"; */
public static final String ACCURATE = "accurate"; public interface OneCallCurrentWeatherRequestTerminator extends RequestTerminator<CurrentWeatherData, String> {
} }
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.onecall.current.CurrentWeatherData;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The type One call current weather request terminator.
*/
public class OneCallCurrentWeatherRequestTerminatorImpl implements OneCallCurrentWeatherRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new One call current weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
OneCallCurrentWeatherRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CurrentWeatherData asJava() {
return new OneCallWeatherResponseMapper(unitSystem).mapToCurrent(getRawResponse());
}
@Override
public String asJSON() {
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.current;
import com.github.prominence.openweathermap.api.model.Coordinate;
/**
* The interface One call current weather requester.
*/
public interface OneCallCurrentWeatherRequester {
/**
* By coordinate one call current weather request customizer.
*
* @param coordinate the coordinate
* @return the one call current weather request customizer
*/
OneCallCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate);
}
@@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2018 Alexey Zinchenko * Copyright (c) 2021 Alexey Zinchenko
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@@ -20,46 +20,31 @@
* SOFTWARE. * SOFTWARE.
*/ */
package com.github.prominence.openweathermap.api.model; package com.github.prominence.openweathermap.api.request.onecall.current;
import com.alibaba.fastjson.annotation.JSONField; import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import java.util.Objects; /**
* The type One call current weather requester.
*/
public class OneCallCurrentWeatherRequesterImpl implements OneCallCurrentWeatherRequester {
private final RequestUrlBuilder urlBuilder;
public class Snow { /**
* Instantiates a new One call current weather requester.
@JSONField(name = "all") *
// Snow volume for the last 3 hours * @param urlBuilder the url builder
private byte snowVolumeLast3Hrs; */
public OneCallCurrentWeatherRequesterImpl(RequestUrlBuilder urlBuilder) {
public byte getSnowVolumeLast3Hrs() { this.urlBuilder = urlBuilder;
return snowVolumeLast3Hrs; urlBuilder.append("onecall");
}
public void setSnowVolumeLast3Hrs(byte snowVolumeLast3Hrs) {
this.snowVolumeLast3Hrs = snowVolumeLast3Hrs;
}
public String getUnit() {
return "mm";
} }
@Override @Override
public String toString() { public OneCallCurrentWeatherRequestCustomizer byCoordinate(Coordinate coordinate) {
return "Snow(last 3 hrs): " + snowVolumeLast3Hrs + ' ' + getUnit(); urlBuilder.addRequestParameter("lat", String.valueOf(coordinate.getLatitude()));
} urlBuilder.addRequestParameter("lon", String.valueOf(coordinate.getLongitude()));
return new OneCallCurrentWeatherRequestCustomizerImpl(urlBuilder);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Snow snow = (Snow) o;
return snowVolumeLast3Hrs == snow.snowVolumeLast3Hrs;
}
@Override
public int hashCode() {
return Objects.hash(snowVolumeLast3Hrs);
} }
} }
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.AsyncRequestTerminator;
/**
* The interface One call historical weather async request terminator.
*/
public interface OneCallHistoricalWeatherAsyncRequestTerminator extends AsyncRequestTerminator<HistoricalWeatherData, String> {
}
@@ -0,0 +1,64 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
import java.util.concurrent.CompletableFuture;
/**
* The type One call historical weather async request terminator.
*/
public class OneCallHistoricalWeatherAsyncRequestTerminatorImpl implements OneCallHistoricalWeatherAsyncRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new One call historical weather async request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
public OneCallHistoricalWeatherAsyncRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public CompletableFuture<HistoricalWeatherData> asJava() {
return CompletableFuture.supplyAsync(() -> new OneCallWeatherResponseMapper(unitSystem).mapToHistorical(getRawResponse()));
}
@Override
public CompletableFuture<String> asJSON() {
return CompletableFuture.supplyAsync(this::getRawResponse);
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.request.RequestCustomizer;
/**
* The interface One call historical weather request customizer.
*/
public interface OneCallHistoricalWeatherRequestCustomizer extends RequestCustomizer<OneCallHistoricalWeatherRequestCustomizer> {
/**
* Retrieve one call historical weather request terminator.
*
* @return the one call historical weather request terminator
*/
OneCallHistoricalWeatherRequestTerminator retrieve();
/**
* Retrieve async one call historical weather async request terminator.
*
* @return the one call historical weather async request terminator
*/
OneCallHistoricalWeatherAsyncRequestTerminator retrieveAsync();
}
@@ -0,0 +1,70 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.enums.Language;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
/**
* The type One call historical weather request customizer.
*/
public class OneCallHistoricalWeatherRequestCustomizerImpl implements OneCallHistoricalWeatherRequestCustomizer {
private final RequestUrlBuilder urlBuilder;
private Language language;
private UnitSystem unitSystem = UnitSystem.STANDARD;
/**
* Instantiates a new One call historical weather request customizer.
*
* @param urlBuilder the url builder
*/
public OneCallHistoricalWeatherRequestCustomizerImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
}
@Override
public OneCallHistoricalWeatherRequestCustomizer language(Language language) {
this.language = language;
return this;
}
@Override
public OneCallHistoricalWeatherRequestCustomizer unitSystem(UnitSystem unitSystem) {
this.unitSystem = unitSystem;
return this;
}
@Override
public OneCallHistoricalWeatherRequestTerminator retrieve() {
urlBuilder.applyCustomization(language, unitSystem);
return new OneCallHistoricalWeatherRequestTerminatorImpl(urlBuilder, unitSystem);
}
@Override
public OneCallHistoricalWeatherAsyncRequestTerminator retrieveAsync() {
urlBuilder.applyCustomization(language, unitSystem);
return new OneCallHistoricalWeatherAsyncRequestTerminatorImpl(urlBuilder, unitSystem);
}
}
@@ -0,0 +1,32 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.RequestTerminator;
/**
* The interface One call historical weather request terminator.
*/
public interface OneCallHistoricalWeatherRequestTerminator extends RequestTerminator<HistoricalWeatherData, String> {
}
@@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.enums.UnitSystem;
import com.github.prominence.openweathermap.api.model.onecall.historical.HistoricalWeatherData;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
import com.github.prominence.openweathermap.api.request.onecall.OneCallWeatherResponseMapper;
import com.github.prominence.openweathermap.api.utils.RequestUtils;
/**
* The type One call historical weather request terminator.
*/
public class OneCallHistoricalWeatherRequestTerminatorImpl implements OneCallHistoricalWeatherRequestTerminator {
private final RequestUrlBuilder urlBuilder;
private final UnitSystem unitSystem;
/**
* Instantiates a new One call historical weather request terminator.
*
* @param urlBuilder the url builder
* @param unitSystem the unit system
*/
public OneCallHistoricalWeatherRequestTerminatorImpl(RequestUrlBuilder urlBuilder, UnitSystem unitSystem) {
this.urlBuilder = urlBuilder;
this.unitSystem = unitSystem;
}
@Override
public HistoricalWeatherData asJava() {
return new OneCallWeatherResponseMapper(unitSystem).mapToHistorical(getRawResponse());
}
@Override
public String asJSON() {
return getRawResponse();
}
private String getRawResponse() {
return RequestUtils.getResponse(urlBuilder.buildUrl());
}
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.model.Coordinate;
/**
* The interface One call historical weather requester.
*/
public interface OneCallHistoricalWeatherRequester {
/**
* By coordinate and timestamp one call historical weather request customizer.
*
* @param coordinate the coordinate
* @param unixTime the unix time
* @return the one call historical weather request customizer
*/
OneCallHistoricalWeatherRequestCustomizer byCoordinateAndTimestamp(Coordinate coordinate, long unixTime);
}
@@ -0,0 +1,51 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.onecall.historical;
import com.github.prominence.openweathermap.api.model.Coordinate;
import com.github.prominence.openweathermap.api.request.RequestUrlBuilder;
/**
* The type One call historical weather requester.
*/
public class OneCallHistoricalWeatherRequesterImpl implements OneCallHistoricalWeatherRequester {
private final RequestUrlBuilder urlBuilder;
/**
* Instantiates a new One call historical weather requester.
*
* @param urlBuilder the url builder
*/
public OneCallHistoricalWeatherRequesterImpl(RequestUrlBuilder urlBuilder) {
this.urlBuilder = urlBuilder;
urlBuilder.append("onecall/timemachine");
}
@Override
public OneCallHistoricalWeatherRequestCustomizer byCoordinateAndTimestamp(Coordinate coordinate, long unixTime) {
urlBuilder.addRequestParameter("lat", coordinate.getLatitude());
urlBuilder.addRequestParameter("lon", coordinate.getLongitude());
urlBuilder.addRequestParameter("dt", unixTime);
return new OneCallHistoricalWeatherRequestCustomizerImpl(urlBuilder);
}
}
@@ -0,0 +1,46 @@
/*
* Copyright (c) 2021 Alexey Zinchenko
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.prominence.openweathermap.api.request.weather;
import com.github.prominence.openweathermap.api.request.weather.multiple.MultipleLocationsCurrentWeatherRequester;
import com.github.prominence.openweathermap.api.request.weather.single.SingleLocationCurrentWeatherRequester;
/**
* An interface for <a href="https://openweathermap.org/current">API</a> methods.
*/
public interface CurrentWeatherRequester {
/**
* Single location current weather requester.
*
* @return the single location current weather requester
*/
SingleLocationCurrentWeatherRequester single();
/**
* Multiple locations current weather requester.
*
* @return the multiple locations current weather requester
*/
MultipleLocationsCurrentWeatherRequester multiple();
}

Some files were not shown because too many files have changed in this diff Show More